@exodus/stasis-core 1.0.0-beta.14 → 1.0.0-beta.16

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/src/bundle.js CHANGED
@@ -2,13 +2,12 @@ import {
2
2
  assert,
3
3
  assertArtifactPath,
4
4
  assertPayloadFree,
5
+ assertScope,
5
6
  canonicalFileKey,
6
7
  duplicateKeyError,
7
8
  fileSetToObject,
8
9
  fromEntries,
9
10
  flatFileKeys,
10
- groupModules,
11
- hasNodeModulesSegment,
12
11
  isLockfileName,
13
12
  isPlainObject,
14
13
  mergeFormatMaps,
@@ -17,21 +16,20 @@ import {
17
16
  mergeModuleMaps,
18
17
  moduleFileKey,
19
18
  normalizeBlock,
20
- normalizeModule,
21
19
  normalizeRepo,
22
20
  PACKAGE_BLOCK,
21
+ parseBuckets,
23
22
  parseEntries,
24
23
  parseExecutable,
25
24
  parseFormats,
26
25
  parseImports,
27
- serializeEntries,
28
- serializeExecutable,
29
- serializeFormats,
30
- serializeImports,
31
26
  posixPathEscapes,
32
27
  REPO_FIELDS,
28
+ RESOURCE_FORMATS,
33
29
  sameGithub,
30
+ serializedParts,
34
31
  splitNodeModulesPath,
32
+ upsert,
35
33
  } from './artifact-util.js'
36
34
 
37
35
  const VERSION = 1
@@ -39,16 +37,33 @@ const LEGACY_VERSION = 0
39
37
 
40
38
  const duplicateKey = duplicateKeyError('bundle', 'artifact (bundle=replace)')
41
39
 
42
- // No bundle carries a stasis lockfile: extracted, one would replace the lockfile there (the attestation a frozen
43
- // extract checks the bundle against), or root a stasis project of its own wherever it lands.
44
- const assertNoLockfile = (keys) => {
45
- for (const key of keys) assert(!isLockfileName(key), `bundle: ${key} is a stasis lockfile, which no bundle may carry`)
40
+ // Unique across buckets, else the `sources` getter would serve either payload. No bundle carries a stasis lockfile:
41
+ // extracted, one would replace the attestation a frozen extract checks against, or root a project of its own.
42
+ const checkedFileKeys = (modules, formats) => {
43
+ const flatKeys = flatFileKeys(modules, 'bundle', duplicateKey)
44
+ for (const key of flatKeys.keys()) assert(!isLockfileName(key), `bundle: ${key} is a stasis lockfile, which no bundle may carry`)
45
+ assertPayloadFree(formats, flatKeys, 'bundle')
46
+ return flatKeys
46
47
  }
47
48
 
48
- // A v0 path's bucket split; '' and '.' both spell the root listing (rel '').
49
+ // '' and '.' both spell the root listing (rel '').
49
50
  const inferModuleDir = (path) =>
50
51
  splitNodeModulesPath(path) ?? { dir: '.', rel: path === '.' ? '' : path, name: null }
51
52
 
53
+ function legacyModules(sources) {
54
+ assert(isPlainObject(sources), 'bundle: sources must be an object')
55
+ const modules = new Map()
56
+ for (const [path, content] of Object.entries(sources)) {
57
+ assertArtifactPath(path, 'bundle')
58
+ const { dir, rel, name } = inferModuleDir(path)
59
+ assert(!posixPathEscapes(dir) && !posixPathEscapes(rel))
60
+ const { files } = upsert(modules, dir, () => ({ name, version: null, files: Object.create(null) }))
61
+ assert(!Object.hasOwn(files, rel), `bundle: duplicate file key '.' (v0 '' and '.')`)
62
+ files[rel] = content
63
+ }
64
+ return modules
65
+ }
66
+
52
67
  function contentsLocked() {
53
68
  throw new Error('bundle: file contents are not retained by this contents-free Bundle')
54
69
  }
@@ -63,66 +78,45 @@ const lockModule = (dir, { files, ...info }) => {
63
78
  return { ...info, files: Object.freeze(locked) }
64
79
  }
65
80
 
66
- // Union of the informational `reason` maps in canonical form: consumers sorted, each file list
67
- // deduped and path-sorted. Canonical even when only one side is given, so a fresh withReason()
68
- // stamp or a parsed artifact can't leak discovery/record order into the map (state's
69
- // #bundleReason sorts the same way). A non-array list (unvalidated -- informational) is dropped.
81
+ // Canonical even from one side, so no stamp or parsed artifact leaks discovery order; a non-array list is dropped.
70
82
  const mergeReason = (a, b) => {
71
83
  if (a === undefined && b === undefined) return undefined
72
84
  // Accumulated in a Map: on a plain object a '__proto__' consumer key would hit the prototype.
73
85
  const merged = new Map()
74
86
  for (const src of [a, b]) {
75
87
  for (const [consumer, files] of Object.entries(src ?? {})) {
76
- if (!Array.isArray(files)) continue
77
- let set = merged.get(consumer)
78
- if (set === undefined) merged.set(consumer, (set = new Set()))
79
- for (const file of files) set.add(file)
88
+ if (Array.isArray(files)) merged.set(consumer, new Set([...(merged.get(consumer) ?? []), ...files]))
80
89
  }
81
90
  }
82
91
  return fromEntries([...merged.keys()].toSorted().map((c) => [c, fileSetToObject(merged.get(c))]))
83
92
  }
84
93
 
85
- // Validate one `repo` field without throwing.
86
94
  export const isValidRepoField = (key, value) => Object.hasOwn(REPO_FIELDS, key) && REPO_FIELDS[key](value)
87
95
 
88
- // `repo` of a bundle plus one added to it: only agreeing fields survive, and none if `github` differs.
89
96
  export const mergeRepo = (a, b) => {
90
97
  if (a?.github === undefined || !sameGithub(a.github, b?.github)) return undefined
91
98
  const kept = Object.keys(REPO_FIELDS).filter((key) => a[key] !== undefined && (key === 'github' || a[key] === b[key]))
92
99
  return fromEntries(kept.map((key) => [key, a[key]]))
93
100
  }
94
101
 
95
- // A parsed header `repo`, an older stasis's `root: true` read as unknown: it recorded one from a
96
- // package.json's claim as well as from a git work tree.
102
+ // An older stasis's `root: true` is read as unknown: it recorded one from a package.json's claim too.
97
103
  const parsedRepo = (repo) => {
98
104
  if (!isPlainObject(repo) || repo.root !== true || Object.hasOwn(repo, 'directory')) return repo
99
105
  const { root: _root, ...rest } = repo
100
106
  return rest
101
107
  }
102
108
 
103
- // One block per ecosystem, named as a module's `ecosystem` is.
104
109
  const PACKAGE_FIELDS = { npm: PACKAGE_BLOCK, composer: PACKAGE_BLOCK, cargo: PACKAGE_BLOCK }
105
110
 
106
- // `package` of a bundle plus one added to it: per ecosystem, only agreeing fields survive, and none unless `name` does.
107
111
  const mergePackage = (a, b) => fromEntries(Object.keys(PACKAGE_FIELDS).map((ecosystem) => {
108
112
  const [x, y] = [a?.[ecosystem], b?.[ecosystem]]
109
113
  return [ecosystem, x?.name !== undefined && x.name === y?.name ? fromEntries(Object.entries(x).filter(([key, value]) => value === y[key])) : undefined]
110
114
  }))
111
115
 
112
- // JSON shape of stasis.code.br; callers own the brotli wrap. parse accepts legacy v0 and v1, serialize always writes v1.
116
+ // JSON shape of stasis.code.br; callers own the brotli wrap. parse accepts legacy v0 and v1, serialize writes v1.
113
117
  export class Bundle {
114
118
  static VERSION = VERSION
115
119
 
116
- version = VERSION
117
- config
118
- entries
119
- modules
120
- formats
121
- imports
122
- // Project-relative paths of bundled files carrying a POSIX execute bit, for `stasis extract`. Files only, never a `directory`.
123
- executable
124
- // Informational only, NOT attested -- never consulted for verification.
125
- reason
126
120
  // Informational, not attested, never in a lockfile; validated on every assignment, and frozen.
127
121
  #repo
128
122
  get repo() {
@@ -131,7 +125,7 @@ export class Bundle {
131
125
  set repo(repo) {
132
126
  this.#repo = normalizeRepo(repo)
133
127
  }
134
- // `{ npm | composer | cargo: { name, version } }`: the package this bundle is; as `repo`, but never set by a build.
128
+ // `{ npm | composer | cargo: { name, version } }`: as `repo`, but never set by a build.
135
129
  #package
136
130
  get package() {
137
131
  return this.#package
@@ -142,20 +136,20 @@ export class Bundle {
142
136
 
143
137
  constructor({ config = { scope: 'full' }, entries, modules, formats, imports, executable, reason, repo, package: pkg, version = VERSION } = {}) {
144
138
  assert([LEGACY_VERSION, VERSION].includes(version))
145
- assert(['node_modules', 'full'].includes(config.scope))
139
+ assertScope(config.scope, 'bundle')
146
140
  this.version = version
147
141
  this.config = config
148
142
  this.entries = entries ?? new Set()
149
143
  this.modules = modules ?? new Map()
150
144
  this.formats = formats ?? new Map()
151
145
  this.imports = imports ?? new Map()
152
- this.executable = executable ?? new Set()
153
- this.reason = reason
146
+ this.executable = executable ?? new Set() // files only, never a `directory`
147
+ this.reason = reason // informational only, NOT attested -- never consulted for verification
154
148
  this.repo = repo
155
149
  this.package = pkg
156
150
  }
157
151
 
158
- // Flat project-relative view of the raw stored file contents (resources stay base64).
152
+ // The raw stored contents by flat key: resources stay base64.
159
153
  get sources() {
160
154
  const m = new Map()
161
155
  for (const [dir, { files }] of this.modules) {
@@ -165,17 +159,13 @@ export class Bundle {
165
159
  }
166
160
 
167
161
  static isResourceFormat(format) {
168
- return format === 'resource' || format === 'resource:base64' || format === 'directory'
162
+ return RESOURCE_FORMATS.has(format) || format === 'directory'
169
163
  }
170
164
 
171
- // True if any bundled file is non-resource; a full-scope code bundle must declare an entry to be runnable (State#absorbCodeBundle).
165
+ // A full-scope code bundle must declare an entry to be runnable (State#absorbCodeBundle).
172
166
  get hasCode() {
173
- for (const [dir, { files }] of this.modules) {
174
- for (const rel of Object.keys(files)) {
175
- if (!Bundle.isResourceFormat(this.formats.get(moduleFileKey(dir, rel)))) return true
176
- }
177
- }
178
- return false
167
+ return this.modules.entries().some(([dir, { files }]) =>
168
+ Object.keys(files).some((rel) => !Bundle.isResourceFormat(this.formats.get(moduleFileKey(dir, rel)))))
179
169
  }
180
170
 
181
171
  static parse(text) {
@@ -186,12 +176,10 @@ export class Bundle {
186
176
  static fileKeyAt(path) {
187
177
  const [top, dir, files, rel] = path
188
178
  if (typeof dir !== 'string') return undefined
189
- // v0 `sources.<path>`
190
179
  if (path.length === 2 && top === 'sources') {
191
180
  const split = inferModuleDir(dir)
192
181
  return canonicalFileKey(split.dir, split.rel, 'bundle')
193
182
  }
194
- // v1 `sources|modules.<dir>.files.<rel>`
195
183
  if (path.length === 4 && (top === 'sources' || top === 'modules') && files === 'files' && typeof rel === 'string') {
196
184
  return canonicalFileKey(dir, rel, 'bundle')
197
185
  }
@@ -201,71 +189,25 @@ export class Bundle {
201
189
  // parse() on an already-parsed value; `contents: false` takes a symbol placeholder per file and locks contents out.
202
190
  static fromJSON(json, { contents = true } = {}) {
203
191
  assert(json.version === VERSION || json.version === LEGACY_VERSION)
204
- assert(['node_modules', 'full'].includes(json.config?.scope))
192
+ assertScope(json.config?.scope, 'bundle')
205
193
  // Validated into a typed Map early: a raw-object lookup like `__proto__` would hit the prototype.
206
194
  const formats = parseFormats(json.formats)
207
-
208
- const modules = new Map()
209
- let entries = new Set()
210
-
211
- if (json.version === VERSION) {
212
- const full = json.config.scope === 'full'
213
- if (json.modules !== undefined) {
214
- assert(typeof json.modules === 'object' && json.modules !== null)
215
- for (const [dir, info] of Object.entries(json.modules)) {
216
- assert(hasNodeModulesSegment(dir))
217
- assertArtifactPath(dir, 'bundle')
218
- assert(info?.name && info.version && info.files)
219
- modules.set(dir, normalizeModule(info, dir, 'bundle'))
220
- }
221
- }
222
- if (full) {
223
- assert(json.sources && typeof json.sources === 'object')
224
- for (const [dir, info] of Object.entries(json.sources)) {
225
- assert(!hasNodeModulesSegment(dir))
226
- assertArtifactPath(dir, 'bundle')
227
- // A workspace bucket may omit version (a private/unpublished package.json can lack one).
228
- assert(info?.name && info.files)
229
- modules.set(dir, normalizeModule(info, dir, 'bundle'))
230
- }
231
- // Empty entries are valid (`stasis add` attests files without making them entry points); state.assertEntry fails closed on an empty set.
232
- if (json.entries !== undefined) entries = parseEntries(json.entries, 'bundle')
233
- } else {
234
- assert(json.entries === undefined)
235
- assert(json.sources === undefined)
236
- }
237
- } else {
238
- assert(json.sources)
239
- for (const [path, content] of Object.entries(json.sources)) {
240
- assertArtifactPath(path, 'bundle')
241
- const { dir, rel, name } = inferModuleDir(path)
242
- assert(!posixPathEscapes(dir) && !posixPathEscapes(rel))
243
- if (!modules.has(dir)) modules.set(dir, { name, version: null, files: Object.create(null) })
244
- const { files } = modules.get(dir)
245
- assert(!Object.hasOwn(files, rel), `bundle: duplicate file key '.' (v0 '' and '.')`)
246
- files[rel] = content
247
- }
248
- }
249
-
250
- // Flat keys must be unique across buckets: two different bucket splits can flatten to one path, and the `sources` getter would serve either payload.
251
- const flatKeys = flatFileKeys(modules, 'bundle', duplicateKey)
252
- assertNoLockfile(flatKeys.keys())
253
- assertPayloadFree(formats, flatKeys, 'bundle')
195
+ const v1 = json.version === VERSION
196
+ if (v1 && json.config.scope !== 'full') assert(json.entries === undefined && json.sources === undefined)
197
+ const modules = v1 ? parseBuckets(json, 'bundle') : legacyModules(json.sources)
198
+ const flatKeys = checkedFileKeys(modules, formats)
254
199
  const imports = parseImports(json.imports)
255
-
256
200
  if (!contents) for (const [dir, info] of modules) modules.set(dir, lockModule(dir, info))
257
-
258
201
  return new Bundle({
259
202
  version: json.version,
260
203
  config: json.config,
261
- entries,
204
+ // Empty entries are valid (`stasis add` attests files without making them entry points).
205
+ entries: v1 && json.entries !== undefined ? parseEntries(json.entries, 'bundle') : new Set(),
262
206
  modules,
263
207
  formats,
264
208
  imports,
265
- // Every executable must be a file this bundle carries. A v0 `executable` is ignored: with no per-file `formats` it could point `extract` at any path to chmod +x.
266
- executable: json.version === VERSION
267
- ? parseExecutable(json.executable, { what: 'bundle', files: flatKeys, formats, scope: json.config.scope })
268
- : new Set(),
209
+ // A v0 `executable` is ignored: with no per-file `formats` it could point `extract` at any path to chmod +x.
210
+ executable: v1 ? parseExecutable(json.executable, { what: 'bundle', files: flatKeys, formats, scope: json.config.scope }) : new Set(),
269
211
  reason: isPlainObject(json.reason) ? json.reason : undefined,
270
212
  repo: parsedRepo(json.repo),
271
213
  package: json.package,
@@ -273,31 +215,15 @@ export class Bundle {
273
215
  }
274
216
 
275
217
  serialize() {
276
- // Never write an artifact that parse would reject.
277
- const flatKeys = flatFileKeys(this.modules, 'bundle', duplicateKey)
278
- assertNoLockfile(flatKeys.keys())
279
- assertPayloadFree(this.formats, flatKeys, 'bundle')
280
- const { modules, sources } = groupModules(this.modules, { skipEmpty: true, what: 'bundle' })
281
- const full = this.config.scope === 'full'
282
- const data = { version: VERSION, config: this.config }
283
- if (this.repo !== undefined) data.repo = this.repo
284
- if (this.package !== undefined) data.package = this.package
285
- if (full) data.entries = serializeEntries(this.entries, 'bundle')
286
- data.formats = serializeFormats(this.formats)
287
- data.imports = serializeImports(this.imports)
288
- const executable = serializeExecutable(this.executable, {
289
- what: 'bundle', modules: this.modules, formats: this.formats, scope: this.config.scope,
290
- })
291
- if (executable !== undefined) data.executable = executable
292
- // Canonicalized like every other sorted field, so a parsed artifact's order can't leak into the bytes.
293
- if (this.reason !== undefined) data.reason = mergeReason(this.reason, undefined)
218
+ checkedFileKeys(this.modules, this.formats)
219
+ const { entries, sources, modules, formats, imports, executable } = serializedParts(this, 'bundle', { skipEmpty: true })
294
220
  // File contents are written last, after every other key: sources, then modules.
295
- if (full) data.sources = sources
296
- data.modules = modules
297
- return JSON.stringify(data, undefined, 2)
221
+ return JSON.stringify({
222
+ version: VERSION, config: this.config, repo: this.repo, package: this.package, entries, formats, imports, executable,
223
+ reason: mergeReason(this.reason, undefined), sources, modules,
224
+ }, undefined, 2)
298
225
  }
299
226
 
300
- // Stamp `consumer` onto `files` in the informational `reason` map: by default every carried file.
301
227
  withReason(consumer, files = [...this.sources.keys()]) {
302
228
  const { version, config, entries, modules, formats, imports, executable, repo, package: pkg } = this
303
229
  const reason = mergeReason(this.reason, { [consumer]: files })
package/src/cli.js CHANGED
@@ -1,14 +1,10 @@
1
- // The commands both CLIs take, `stasis-core` and `stasis`, from their arguments: `add`, `extract` and
2
- // `prune` whole, and `run` in steps, so `stasis run` can add its own options on top -- its options
3
- // parsed and checked, the config the loader reads set in the environment, and the program run under
4
- // the loader. Each names itself `label` (the CLI's name) and leaves a usage error to `fail(message)`,
5
- // which exits.
1
+ // Each command takes `label` (the CLI's name) and leaves a usage error to `fail(message)`, which exits.
6
2
 
7
3
  import { spawn } from 'node:child_process'
8
4
  import { once } from 'node:events'
9
5
  import { constants as osConstants } from 'node:os'
10
6
  import { resolve } from 'node:path'
11
- import { parseBrotliQuality, parseLeadingOptions, valueFlagsOf } from './util.js'
7
+ import { BUNDLE_MODES, LOCK_MODES, parseBrotliQuality, parseLeadingOptions, valueFlagsOf } from './util.js'
12
8
 
13
9
  const RUN_OPTIONS = {
14
10
  lock: { type: 'string', default: 'none' },
@@ -24,31 +20,24 @@ const RUN_OPTIONS = {
24
20
  'brotli-quality': { type: 'string' },
25
21
  }
26
22
  // `--fs` is taken only as `--fs=<mode>`: a bare `--fs` is refused rather than given the program as its mode.
27
- const RUN_VALUE_FLAGS = ['--bundle', '--bundle-file', '--resources-bundle-file', '--lock', '--import', '--resources', '--brotli-quality']
23
+ const RUN_VALUE_FLAGS = valueFlagsOf(RUN_OPTIONS).filter((flag) => flag !== '--fs')
28
24
 
29
- // `run`'s options, and the caller's own `options` (boolean ones), shifted off the front of `argv`,
30
- // which keeps the program and its arguments; checked, a usage error being `fail(message)`'s (which
31
- // exits). -> the run: `values` as parsed, and the config they set.
32
25
  export function parseRunOptions(argv, { options = {}, fail }) {
33
26
  const values = parseLeadingOptions(argv, { ...RUN_OPTIONS, ...options }, { valueFlags: RUN_VALUE_FLAGS, onError: fail })
34
27
  if (argv.length === 0) fail('Nothing to run: no path to file given')
35
28
  const { lock, bundle } = values
36
- if (!['none', 'ignore', 'add', 'replace', 'frozen'].includes(lock)) fail('Error: invalid --lock value')
29
+ if (!LOCK_MODES.has(lock)) fail('Error: invalid --lock value')
37
30
  const bundleFile = values['bundle-file'] ? resolve(values['bundle-file']) : ''
38
31
  const resourcesBundleFile = values['resources-bundle-file'] ? resolve(values['resources-bundle-file']) : ''
39
- if (!['none', 'ignore', 'add', 'replace', 'load', 'frozen'].includes(bundle)) fail('Error: invalid --bundle value')
32
+ if (!BUNDLE_MODES.has(bundle)) fail('Error: invalid --bundle value')
40
33
  if (bundleFile && bundle === 'none') fail('Error: --bundle-file requires --bundle=(add|replace|load|frozen|ignore)')
41
34
  // --resources-bundle-file needs an active bundle mode (unlike --bundle-file, inert under ignore).
42
35
  if (resourcesBundleFile && (bundle === 'none' || bundle === 'ignore')) fail('Error: --resources-bundle-file requires --bundle=(add|replace|load|frozen)')
43
- if (bundle === 'load' && lock !== 'frozen' && lock !== 'none' && lock !== 'ignore') fail('Error: --bundle=load is incompatible with --lock=(add|replace)')
36
+ if (bundle === 'load' && (lock === 'add' || lock === 'replace')) fail('Error: --bundle=load is incompatible with --lock=(add|replace)')
44
37
  if (lock === 'none' && bundle === 'none') fail('Error: stasis needs a lockfile or a bundle: set --lock or --bundle')
45
- // --fs requires a bundle mode (add|replace|load); `sync` patches the sync fs readers,
46
- // `async` adds their callback + fs.promises counterparts on top.
47
38
  if (values.fs !== undefined && !['sync', 'async'].includes(values.fs)) fail("Error: --fs must be 'sync' or 'async'")
48
39
  if (values.fs !== undefined && !['add', 'replace', 'load'].includes(bundle)) fail('Error: --fs requires --bundle=(add|replace|load)')
49
40
  const brotliQuality = brotliQualityOption(values['brotli-quality'], fail)
50
- // --import: extra preload module(s) passed through to the spawned node. Node resolves each
51
- // against the project cwd; they ride AFTER stasis's own loader import.
52
41
  const imports = values.import ?? []
53
42
  if (imports.some((s) => s === '')) fail('Error: --import requires a module specifier (e.g. --import=./instrument.mjs)')
54
43
  return {
@@ -59,17 +48,14 @@ export function parseRunOptions(argv, { options = {}, fail }) {
59
48
  bundleFile,
60
49
  resourcesBundleFile,
61
50
  debug: values.debug ? '1' : '',
62
- // --child-process: forward forked-child (e.g. Metro worker) capture to the root via per-pid shards.
63
51
  childProcess: values['child-process'] ? '1' : '',
64
52
  fs: values.fs ?? '',
65
- // --resources: comma-separated extension/filename allowlist for `--fs` captures.
66
53
  resources: values.resources ?? '',
67
54
  brotliQuality,
68
55
  imports,
69
56
  }
70
57
  }
71
58
 
72
- // The `--brotli-quality` given as `value`, a usage error where it's no quality. -> it, or undefined
73
59
  export function brotliQualityOption(value, fail) {
74
60
  if (value === undefined) return undefined
75
61
  try {
@@ -79,16 +65,12 @@ export function brotliQualityOption(value, fail) {
79
65
  }
80
66
  }
81
67
 
82
- // Sets the environment variable `name` to `value` (a string), refusing one the environment already
83
- // sets otherwise.
84
68
  export function setEnv(name, value) {
85
69
  const env = process.env[name]
86
70
  if (env && env !== value) throw new Error(`env conflict: ${name}="${env}", effective: "${value}"`)
87
71
  process.env[name] = value
88
72
  }
89
73
 
90
- // Announces `run` on stderr as `label` (the CLI's name), with the caller's own `extra` config after
91
- // childProcess, and sets it in the environment the loader reads it from.
92
74
  export function setRunEnv(label, run, extra = {}) {
93
75
  const { lock, scope, bundle, bundleFile, resourcesBundleFile, debug, childProcess, fs, resources, brotliQuality, imports } = run
94
76
  console.warn(`[${label}] Running stasis with config:`, { lock, scope, bundle, ...(bundleFile && { bundleFile }), ...(resourcesBundleFile && { resourcesBundleFile }), ...(childProcess && { childProcess: true }), ...extra, ...(imports.length > 0 && { import: imports }), ...(fs && { fs }), ...(resources && { resources }), ...(brotliQuality !== undefined && { brotliQuality }) })
@@ -102,15 +84,12 @@ export function setRunEnv(label, run, extra = {}) {
102
84
  setEnv('EXODUS_STASIS_CHILD_PROCESS', childProcess)
103
85
  setEnv('EXODUS_STASIS_FS', fs)
104
86
  setEnv('EXODUS_STASIS_RESOURCES', resources)
105
- // Only set when given: an unconditional setEnv('') would reject an ambient EXODUS_STASIS_BROTLI_QUALITY as a conflict.
87
+ // Only when given: an unconditional setEnv('') would reject an ambient EXODUS_STASIS_BROTLI_QUALITY.
106
88
  if (brotliQuality !== undefined) setEnv('EXODUS_STASIS_BROTLI_QUALITY', String(brotliQuality))
107
89
  }
108
90
 
109
- // Runs the program `argv` in a node taking `nodeArgs`, then `--import`ing `loader` (a URL) and the
110
- // run's `imports`. Those preloads ride after the loader, so they evaluate under its hooks; their
111
- // module graphs pass through uncaptured unless the app graph reaches them -- then they're promoted
112
- // into the capture (see hooks.js). Exits as the program does: its code, or 128+signo when a signal
113
- // killed it (the shell's convention) instead of the implicit 0.
91
+ // The run's `imports` evaluate under `loader`'s hooks: their graphs pass uncaptured unless the app's reaches them
92
+ // (hooks.js). Exits as the program does: its code, or 128+signo when a signal killed it (the shell's convention).
114
93
  export async function runProgram(argv, { nodeArgs = [], loader, imports }) {
115
94
  const args = [...nodeArgs, '--import', loader, ...imports.flatMap((specifier) => ['--import', specifier]), ...argv]
116
95
  const child = spawn(process.execPath, args, { stdio: 'inherit' })
@@ -118,36 +97,27 @@ export async function runProgram(argv, { nodeArgs = [], loader, imports }) {
118
97
  process.exitCode = code ?? 128 + (osConstants.signals[signal] ?? 0)
119
98
  }
120
99
 
121
- // `add`: packs the listed files (no resolver), taking split targets + resource allowlist from
122
- // stasis.config.json; it takes no flags. Its runtime errors propagate as they are: wrapping them in
123
- // fail() would bury the cause.
100
+ // Its runtime errors propagate as they are: wrapping them in fail() would bury the cause.
124
101
  export async function addCli(argv, { label, fail }) {
125
102
  if (argv.length === 0) fail('Nothing to add: no file given')
126
103
  if (argv.some((a) => a.startsWith('-'))) fail('Error: add takes no options; its targets and resource allowlist come from stasis.config.json')
127
104
  const { addCommand } = await import('./add.js')
128
- addCommand({ cwd: process.cwd(), entries: argv, logLabel: label })
105
+ addCommand({ entries: argv, logLabel: label })
129
106
  }
130
107
 
131
- // `extract`: a bundle's files written out, as `--output` and `--lock` say.
132
108
  export async function extractCli(argv, { label, fail }) {
133
- const options = {
134
- output: { type: 'string', short: 'o' },
135
- lock: { type: 'string' },
136
- }
109
+ const options = { output: { type: 'string', short: 'o' }, lock: { type: 'string' } }
137
110
  const values = parseLeadingOptions(argv, options, { valueFlags: valueFlagsOf(options), onError: fail })
138
111
  if (argv.length === 0) fail('Nothing to extract: no bundle file given')
139
112
  if (argv.length > 1) fail('Error: extract takes exactly one bundle file')
140
- // Unset: frozen when the output dir holds a stasis.lock.json, else none (see extractCommand).
141
- if (values.lock !== undefined && !['frozen', 'add', 'replace', 'ignore', 'none'].includes(values.lock)) fail('Error: invalid --lock value')
113
+ if (values.lock !== undefined && !LOCK_MODES.has(values.lock)) fail('Error: invalid --lock value')
142
114
  const { extractCommand } = await import('./extract.js')
143
- extractCommand({ cwd: process.cwd(), bundleFile: argv[0], output: values.output, lock: values.lock, logLabel: label })
115
+ extractCommand({ bundleFile: argv[0], output: values.output, lock: values.lock, logLabel: label })
144
116
  }
145
117
 
146
- // `prune`: the project's node_modules (the one given, else the cwd's) cut down to its lockfile.
147
118
  export async function pruneCli(argv, { label, fail }) {
148
119
  if (argv.length > 1) fail('Error: prune takes at most one path argument')
149
- const root = argv[0] ? resolve(argv[0]) : process.cwd()
150
120
  const { prune } = await import('./prune.js')
151
- const { removed, validated, minimized } = prune({ root })
121
+ const { removed, validated, minimized } = prune({ root: argv[0] })
152
122
  console.warn(`[${label}] prune: validated ${validated.length} file(s), removed ${removed.length} file(s), minimized ${minimized.length} package.json file(s)`)
153
123
  }