@exodus/stasis-core 1.0.0-beta.8 → 1.0.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/stasis-core.js +28 -109
- package/package.json +6 -2
- package/src/add.js +161 -157
- package/src/artifact-util.js +322 -217
- package/src/brotli.js +20 -6
- package/src/bundle-util.js +148 -98
- package/src/bundle.js +65 -128
- package/src/cli.js +123 -0
- package/src/config.js +74 -87
- package/src/extract.js +140 -67
- package/src/fs.js +57 -106
- package/src/hooks.js +126 -238
- package/src/host.js +9 -1
- package/src/loader.js +1 -1
- package/src/lockfile.js +58 -74
- package/src/policy.js +222 -0
- package/src/prune.js +60 -114
- package/src/shard.js +10 -25
- package/src/state-util.js +24 -9
- package/src/state.js +737 -862
- package/src/util.js +123 -172
package/src/bundle.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import {
|
|
2
2
|
assert,
|
|
3
3
|
assertArtifactPath,
|
|
4
|
+
assertPayloadFree,
|
|
5
|
+
assertScope,
|
|
4
6
|
canonicalFileKey,
|
|
5
7
|
duplicateKeyError,
|
|
6
8
|
fileSetToObject,
|
|
7
9
|
fromEntries,
|
|
8
10
|
flatFileKeys,
|
|
9
|
-
|
|
10
|
-
hasNodeModulesSegment,
|
|
11
|
+
isLockfileName,
|
|
11
12
|
isPlainObject,
|
|
12
13
|
mergeFormatMaps,
|
|
13
14
|
mergeImportMaps,
|
|
@@ -15,20 +16,20 @@ import {
|
|
|
15
16
|
mergeModuleMaps,
|
|
16
17
|
moduleFileKey,
|
|
17
18
|
normalizeBlock,
|
|
18
|
-
normalizeModule,
|
|
19
19
|
normalizeRepo,
|
|
20
|
+
PACKAGE_BLOCK,
|
|
21
|
+
parseBuckets,
|
|
20
22
|
parseEntries,
|
|
21
23
|
parseExecutable,
|
|
22
24
|
parseFormats,
|
|
23
25
|
parseImports,
|
|
24
|
-
serializeEntries,
|
|
25
|
-
serializeExecutable,
|
|
26
|
-
serializeFormats,
|
|
27
|
-
serializeImports,
|
|
28
26
|
posixPathEscapes,
|
|
29
27
|
REPO_FIELDS,
|
|
28
|
+
RESOURCE_FORMATS,
|
|
30
29
|
sameGithub,
|
|
30
|
+
serializedParts,
|
|
31
31
|
splitNodeModulesPath,
|
|
32
|
+
upsert,
|
|
32
33
|
} from './artifact-util.js'
|
|
33
34
|
|
|
34
35
|
const VERSION = 1
|
|
@@ -36,10 +37,33 @@ const LEGACY_VERSION = 0
|
|
|
36
37
|
|
|
37
38
|
const duplicateKey = duplicateKeyError('bundle', 'artifact (bundle=replace)')
|
|
38
39
|
|
|
39
|
-
//
|
|
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
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// '' and '.' both spell the root listing (rel '').
|
|
40
50
|
const inferModuleDir = (path) =>
|
|
41
51
|
splitNodeModulesPath(path) ?? { dir: '.', rel: path === '.' ? '' : path, name: null }
|
|
42
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
|
+
|
|
43
67
|
function contentsLocked() {
|
|
44
68
|
throw new Error('bundle: file contents are not retained by this contents-free Bundle')
|
|
45
69
|
}
|
|
@@ -54,70 +78,47 @@ const lockModule = (dir, { files, ...info }) => {
|
|
|
54
78
|
return { ...info, files: Object.freeze(locked) }
|
|
55
79
|
}
|
|
56
80
|
|
|
57
|
-
//
|
|
58
|
-
// deduped and path-sorted. Canonical even when only one side is given, so a fresh withReason()
|
|
59
|
-
// stamp or a parsed artifact can't leak discovery/record order into the map (state's
|
|
60
|
-
// #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.
|
|
61
82
|
const mergeReason = (a, b) => {
|
|
62
83
|
if (a === undefined && b === undefined) return undefined
|
|
63
84
|
// Accumulated in a Map: on a plain object a '__proto__' consumer key would hit the prototype.
|
|
64
85
|
const merged = new Map()
|
|
65
86
|
for (const src of [a, b]) {
|
|
66
87
|
for (const [consumer, files] of Object.entries(src ?? {})) {
|
|
67
|
-
if (
|
|
68
|
-
let set = merged.get(consumer)
|
|
69
|
-
if (set === undefined) merged.set(consumer, (set = new Set()))
|
|
70
|
-
for (const file of files) set.add(file)
|
|
88
|
+
if (Array.isArray(files)) merged.set(consumer, new Set([...(merged.get(consumer) ?? []), ...files]))
|
|
71
89
|
}
|
|
72
90
|
}
|
|
73
91
|
return fromEntries([...merged.keys()].toSorted().map((c) => [c, fileSetToObject(merged.get(c))]))
|
|
74
92
|
}
|
|
75
93
|
|
|
76
|
-
// Validate one `repo` field without throwing.
|
|
77
94
|
export const isValidRepoField = (key, value) => Object.hasOwn(REPO_FIELDS, key) && REPO_FIELDS[key](value)
|
|
78
95
|
|
|
79
|
-
// `repo` of a bundle plus one added to it: only agreeing fields survive, and none if `github` differs.
|
|
80
96
|
export const mergeRepo = (a, b) => {
|
|
81
97
|
if (a?.github === undefined || !sameGithub(a.github, b?.github)) return undefined
|
|
82
98
|
const kept = Object.keys(REPO_FIELDS).filter((key) => a[key] !== undefined && (key === 'github' || a[key] === b[key]))
|
|
83
99
|
return fromEntries(kept.map((key) => [key, a[key]]))
|
|
84
100
|
}
|
|
85
101
|
|
|
86
|
-
//
|
|
87
|
-
// 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.
|
|
88
103
|
const parsedRepo = (repo) => {
|
|
89
104
|
if (!isPlainObject(repo) || repo.root !== true || Object.hasOwn(repo, 'directory')) return repo
|
|
90
105
|
const { root: _root, ...rest } = repo
|
|
91
106
|
return rest
|
|
92
107
|
}
|
|
93
108
|
|
|
94
|
-
// A package name or version: characters some ecosystem uses there (npm's legacy `~'!()*` too), so not space or `"#$%&,:;<=>?[\]^`{|}`.
|
|
95
|
-
const isPackageString = (v) => typeof v === 'string' && /^[\w.+@/~'!()*-]+$/u.test(v)
|
|
96
|
-
const PACKAGE_BLOCK = { name: isPackageString, version: isPackageString }
|
|
97
|
-
// One block per ecosystem, named as a module's `ecosystem` is.
|
|
98
109
|
const PACKAGE_FIELDS = { npm: PACKAGE_BLOCK, composer: PACKAGE_BLOCK, cargo: PACKAGE_BLOCK }
|
|
99
110
|
|
|
100
|
-
// `package` of a bundle plus one added to it: per ecosystem, only agreeing fields survive, and none unless `name` does.
|
|
101
111
|
const mergePackage = (a, b) => fromEntries(Object.keys(PACKAGE_FIELDS).map((ecosystem) => {
|
|
102
112
|
const [x, y] = [a?.[ecosystem], b?.[ecosystem]]
|
|
103
113
|
return [ecosystem, x?.name !== undefined && x.name === y?.name ? fromEntries(Object.entries(x).filter(([key, value]) => value === y[key])) : undefined]
|
|
104
114
|
}))
|
|
105
115
|
|
|
106
|
-
// JSON shape of stasis.code.br; callers own the brotli wrap. parse accepts legacy v0 and v1, serialize
|
|
116
|
+
// JSON shape of stasis.code.br; callers own the brotli wrap. parse accepts legacy v0 and v1, serialize writes v1.
|
|
107
117
|
export class Bundle {
|
|
108
118
|
static VERSION = VERSION
|
|
109
119
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
entries
|
|
113
|
-
modules
|
|
114
|
-
formats
|
|
115
|
-
imports
|
|
116
|
-
// Project-relative paths of bundled files carrying a POSIX execute bit, for `stasis extract`. Files only, never a `directory`.
|
|
117
|
-
executable
|
|
118
|
-
// Informational only, NOT attested -- never consulted for verification.
|
|
119
|
-
reason
|
|
120
|
-
// Informational, not attested, never in a lockfile; validated on every assignment, and frozen.
|
|
120
|
+
// Informational, not attested; validated on every assignment, and frozen. In a lockfile of a GitHub build's alone
|
|
121
|
+
// (Lockfile#repo), never one of a bundle's.
|
|
121
122
|
#repo
|
|
122
123
|
get repo() {
|
|
123
124
|
return this.#repo
|
|
@@ -125,7 +126,7 @@ export class Bundle {
|
|
|
125
126
|
set repo(repo) {
|
|
126
127
|
this.#repo = normalizeRepo(repo)
|
|
127
128
|
}
|
|
128
|
-
// `{ npm | composer | cargo: { name, version } }`:
|
|
129
|
+
// `{ npm | composer | cargo: { name, version } }`: as `repo`, but never set by a build.
|
|
129
130
|
#package
|
|
130
131
|
get package() {
|
|
131
132
|
return this.#package
|
|
@@ -136,20 +137,20 @@ export class Bundle {
|
|
|
136
137
|
|
|
137
138
|
constructor({ config = { scope: 'full' }, entries, modules, formats, imports, executable, reason, repo, package: pkg, version = VERSION } = {}) {
|
|
138
139
|
assert([LEGACY_VERSION, VERSION].includes(version))
|
|
139
|
-
|
|
140
|
+
assertScope(config.scope, 'bundle')
|
|
140
141
|
this.version = version
|
|
141
142
|
this.config = config
|
|
142
143
|
this.entries = entries ?? new Set()
|
|
143
144
|
this.modules = modules ?? new Map()
|
|
144
145
|
this.formats = formats ?? new Map()
|
|
145
146
|
this.imports = imports ?? new Map()
|
|
146
|
-
this.executable = executable ?? new Set()
|
|
147
|
-
this.reason = reason
|
|
148
|
-
this.repo =
|
|
147
|
+
this.executable = executable ?? new Set() // files only, never a `directory`
|
|
148
|
+
this.reason = reason // informational only, NOT attested -- never consulted for verification
|
|
149
|
+
this.repo = repo
|
|
149
150
|
this.package = pkg
|
|
150
151
|
}
|
|
151
152
|
|
|
152
|
-
//
|
|
153
|
+
// The raw stored contents by flat key: resources stay base64.
|
|
153
154
|
get sources() {
|
|
154
155
|
const m = new Map()
|
|
155
156
|
for (const [dir, { files }] of this.modules) {
|
|
@@ -159,17 +160,13 @@ export class Bundle {
|
|
|
159
160
|
}
|
|
160
161
|
|
|
161
162
|
static isResourceFormat(format) {
|
|
162
|
-
return format
|
|
163
|
+
return RESOURCE_FORMATS.has(format) || format === 'directory'
|
|
163
164
|
}
|
|
164
165
|
|
|
165
|
-
//
|
|
166
|
+
// A full-scope code bundle must declare an entry to be runnable (State#absorbCodeBundle).
|
|
166
167
|
get hasCode() {
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
if (!Bundle.isResourceFormat(this.formats.get(moduleFileKey(dir, rel)))) return true
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
return false
|
|
168
|
+
return this.modules.entries().some(([dir, { files }]) =>
|
|
169
|
+
Object.keys(files).some((rel) => !Bundle.isResourceFormat(this.formats.get(moduleFileKey(dir, rel)))))
|
|
173
170
|
}
|
|
174
171
|
|
|
175
172
|
static parse(text) {
|
|
@@ -180,12 +177,10 @@ export class Bundle {
|
|
|
180
177
|
static fileKeyAt(path) {
|
|
181
178
|
const [top, dir, files, rel] = path
|
|
182
179
|
if (typeof dir !== 'string') return undefined
|
|
183
|
-
// v0 `sources.<path>`
|
|
184
180
|
if (path.length === 2 && top === 'sources') {
|
|
185
181
|
const split = inferModuleDir(dir)
|
|
186
182
|
return canonicalFileKey(split.dir, split.rel, 'bundle')
|
|
187
183
|
}
|
|
188
|
-
// v1 `sources|modules.<dir>.files.<rel>`
|
|
189
184
|
if (path.length === 4 && (top === 'sources' || top === 'modules') && files === 'files' && typeof rel === 'string') {
|
|
190
185
|
return canonicalFileKey(dir, rel, 'bundle')
|
|
191
186
|
}
|
|
@@ -195,69 +190,25 @@ export class Bundle {
|
|
|
195
190
|
// parse() on an already-parsed value; `contents: false` takes a symbol placeholder per file and locks contents out.
|
|
196
191
|
static fromJSON(json, { contents = true } = {}) {
|
|
197
192
|
assert(json.version === VERSION || json.version === LEGACY_VERSION)
|
|
198
|
-
|
|
193
|
+
assertScope(json.config?.scope, 'bundle')
|
|
199
194
|
// Validated into a typed Map early: a raw-object lookup like `__proto__` would hit the prototype.
|
|
200
195
|
const formats = parseFormats(json.formats)
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
if (json.version === VERSION) {
|
|
206
|
-
const full = json.config.scope === 'full'
|
|
207
|
-
if (json.modules !== undefined) {
|
|
208
|
-
assert(typeof json.modules === 'object' && json.modules !== null)
|
|
209
|
-
for (const [dir, info] of Object.entries(json.modules)) {
|
|
210
|
-
assert(hasNodeModulesSegment(dir))
|
|
211
|
-
assertArtifactPath(dir, 'bundle')
|
|
212
|
-
assert(info?.name && info.version && info.files)
|
|
213
|
-
modules.set(dir, normalizeModule(info, dir, 'bundle'))
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
if (full) {
|
|
217
|
-
assert(json.sources && typeof json.sources === 'object')
|
|
218
|
-
for (const [dir, info] of Object.entries(json.sources)) {
|
|
219
|
-
assert(!hasNodeModulesSegment(dir))
|
|
220
|
-
assertArtifactPath(dir, 'bundle')
|
|
221
|
-
// A workspace bucket may omit version (a private/unpublished package.json can lack one).
|
|
222
|
-
assert(info?.name && info.files)
|
|
223
|
-
modules.set(dir, normalizeModule(info, dir, 'bundle'))
|
|
224
|
-
}
|
|
225
|
-
// Empty entries are valid (`stasis add` attests files without making them entry points); state.assertEntry fails closed on an empty set.
|
|
226
|
-
if (json.entries !== undefined) entries = parseEntries(json.entries, 'bundle')
|
|
227
|
-
} else {
|
|
228
|
-
assert(json.entries === undefined)
|
|
229
|
-
assert(json.sources === undefined)
|
|
230
|
-
}
|
|
231
|
-
} else {
|
|
232
|
-
assert(json.sources)
|
|
233
|
-
for (const [path, content] of Object.entries(json.sources)) {
|
|
234
|
-
assertArtifactPath(path, 'bundle')
|
|
235
|
-
const { dir, rel, name } = inferModuleDir(path)
|
|
236
|
-
assert(!posixPathEscapes(dir) && !posixPathEscapes(rel))
|
|
237
|
-
if (!modules.has(dir)) modules.set(dir, { name, version: null, files: Object.create(null) })
|
|
238
|
-
const { files } = modules.get(dir)
|
|
239
|
-
assert(!Object.hasOwn(files, rel), `bundle: duplicate file key '.' (v0 '' and '.')`)
|
|
240
|
-
files[rel] = content
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
// Flat keys must be unique across buckets: two different bucket splits can flatten to one path, and the `sources` getter would serve either payload.
|
|
245
|
-
const flatKeys = flatFileKeys(modules, 'bundle', duplicateKey)
|
|
196
|
+
const v1 = json.version === VERSION
|
|
197
|
+
if (v1 && json.config.scope !== 'full') assert(json.entries === undefined && json.sources === undefined)
|
|
198
|
+
const modules = v1 ? parseBuckets(json, 'bundle') : legacyModules(json.sources)
|
|
199
|
+
const flatKeys = checkedFileKeys(modules, formats)
|
|
246
200
|
const imports = parseImports(json.imports)
|
|
247
|
-
|
|
248
201
|
if (!contents) for (const [dir, info] of modules) modules.set(dir, lockModule(dir, info))
|
|
249
|
-
|
|
250
202
|
return new Bundle({
|
|
251
203
|
version: json.version,
|
|
252
204
|
config: json.config,
|
|
253
|
-
entries
|
|
205
|
+
// Empty entries are valid (`stasis add` attests files without making them entry points).
|
|
206
|
+
entries: v1 && json.entries !== undefined ? parseEntries(json.entries, 'bundle') : new Set(),
|
|
254
207
|
modules,
|
|
255
208
|
formats,
|
|
256
209
|
imports,
|
|
257
|
-
//
|
|
258
|
-
executable: json.
|
|
259
|
-
? parseExecutable(json.executable, { what: 'bundle', files: flatKeys, formats, scope: json.config.scope })
|
|
260
|
-
: new Set(),
|
|
210
|
+
// A v0 `executable` is ignored: with no per-file `formats` it could point `extract` at any path to chmod +x.
|
|
211
|
+
executable: v1 ? parseExecutable(json.executable, { what: 'bundle', files: flatKeys, formats, scope: json.config.scope }) : new Set(),
|
|
261
212
|
reason: isPlainObject(json.reason) ? json.reason : undefined,
|
|
262
213
|
repo: parsedRepo(json.repo),
|
|
263
214
|
package: json.package,
|
|
@@ -265,32 +216,18 @@ export class Bundle {
|
|
|
265
216
|
}
|
|
266
217
|
|
|
267
218
|
serialize() {
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
const { modules, sources } = groupModules(this.modules, { skipEmpty: true, what: 'bundle' })
|
|
271
|
-
const full = this.config.scope === 'full'
|
|
272
|
-
const data = { version: VERSION, config: this.config }
|
|
273
|
-
if (this.repo !== undefined) data.repo = this.repo
|
|
274
|
-
if (this.package !== undefined) data.package = this.package
|
|
275
|
-
if (full) data.entries = serializeEntries(this.entries, 'bundle')
|
|
276
|
-
data.formats = serializeFormats(this.formats)
|
|
277
|
-
data.imports = serializeImports(this.imports)
|
|
278
|
-
const executable = serializeExecutable(this.executable, {
|
|
279
|
-
what: 'bundle', modules: this.modules, formats: this.formats, scope: this.config.scope,
|
|
280
|
-
})
|
|
281
|
-
if (executable !== undefined) data.executable = executable
|
|
282
|
-
// Canonicalized like every other sorted field, so a parsed artifact's order can't leak into the bytes.
|
|
283
|
-
if (this.reason !== undefined) data.reason = mergeReason(this.reason, undefined)
|
|
219
|
+
checkedFileKeys(this.modules, this.formats)
|
|
220
|
+
const { entries, sources, modules, formats, imports, executable } = serializedParts(this, 'bundle', { skipEmpty: true })
|
|
284
221
|
// File contents are written last, after every other key: sources, then modules.
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
222
|
+
return JSON.stringify({
|
|
223
|
+
version: VERSION, config: this.config, repo: this.repo, package: this.package, entries, formats, imports, executable,
|
|
224
|
+
reason: mergeReason(this.reason, undefined), sources, modules,
|
|
225
|
+
}, undefined, 2)
|
|
288
226
|
}
|
|
289
227
|
|
|
290
|
-
|
|
291
|
-
withReason(consumer) {
|
|
228
|
+
withReason(consumer, files = [...this.sources.keys()]) {
|
|
292
229
|
const { version, config, entries, modules, formats, imports, executable, repo, package: pkg } = this
|
|
293
|
-
const reason = mergeReason(this.reason, { [consumer]:
|
|
230
|
+
const reason = mergeReason(this.reason, { [consumer]: files })
|
|
294
231
|
return new Bundle({ version, config, entries, modules, formats, imports, executable, reason, repo, package: pkg })
|
|
295
232
|
}
|
|
296
233
|
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// Each command takes `label` (the CLI's name) and leaves a usage error to `fail(message)`, which exits.
|
|
2
|
+
|
|
3
|
+
import { spawn } from 'node:child_process'
|
|
4
|
+
import { once } from 'node:events'
|
|
5
|
+
import { constants as osConstants } from 'node:os'
|
|
6
|
+
import { resolve } from 'node:path'
|
|
7
|
+
import { BUNDLE_MODES, LOCK_MODES, parseBrotliQuality, parseLeadingOptions, valueFlagsOf } from './util.js'
|
|
8
|
+
|
|
9
|
+
const RUN_OPTIONS = {
|
|
10
|
+
lock: { type: 'string', default: 'none' },
|
|
11
|
+
bundle: { type: 'string', default: 'none' },
|
|
12
|
+
'bundle-file': { type: 'string' },
|
|
13
|
+
'resources-bundle-file': { type: 'string' },
|
|
14
|
+
debug: { type: 'boolean' },
|
|
15
|
+
dependencies: { type: 'boolean' },
|
|
16
|
+
'child-process': { type: 'boolean' },
|
|
17
|
+
import: { type: 'string', multiple: true },
|
|
18
|
+
fs: { type: 'string' },
|
|
19
|
+
resources: { type: 'string' },
|
|
20
|
+
'brotli-quality': { type: 'string' },
|
|
21
|
+
}
|
|
22
|
+
// `--fs` is taken only as `--fs=<mode>`: a bare `--fs` is refused rather than given the program as its mode.
|
|
23
|
+
const RUN_VALUE_FLAGS = valueFlagsOf(RUN_OPTIONS).filter((flag) => flag !== '--fs')
|
|
24
|
+
|
|
25
|
+
export function parseRunOptions(argv, { options = {}, fail }) {
|
|
26
|
+
const values = parseLeadingOptions(argv, { ...RUN_OPTIONS, ...options }, { valueFlags: RUN_VALUE_FLAGS, onError: fail })
|
|
27
|
+
if (argv.length === 0) fail('Nothing to run: no path to file given')
|
|
28
|
+
const { lock, bundle } = values
|
|
29
|
+
if (!LOCK_MODES.has(lock)) fail('Error: invalid --lock value')
|
|
30
|
+
const bundleFile = values['bundle-file'] ? resolve(values['bundle-file']) : ''
|
|
31
|
+
const resourcesBundleFile = values['resources-bundle-file'] ? resolve(values['resources-bundle-file']) : ''
|
|
32
|
+
if (!BUNDLE_MODES.has(bundle)) fail('Error: invalid --bundle value')
|
|
33
|
+
if (bundleFile && bundle === 'none') fail('Error: --bundle-file requires --bundle=(add|replace|load|frozen|ignore)')
|
|
34
|
+
// --resources-bundle-file needs an active bundle mode (unlike --bundle-file, inert under ignore).
|
|
35
|
+
if (resourcesBundleFile && (bundle === 'none' || bundle === 'ignore')) fail('Error: --resources-bundle-file requires --bundle=(add|replace|load|frozen)')
|
|
36
|
+
if (bundle === 'load' && (lock === 'add' || lock === 'replace')) fail('Error: --bundle=load is incompatible with --lock=(add|replace)')
|
|
37
|
+
if (lock === 'none' && bundle === 'none') fail('Error: stasis needs a lockfile or a bundle: set --lock or --bundle')
|
|
38
|
+
if (values.fs !== undefined && !['sync', 'async'].includes(values.fs)) fail("Error: --fs must be 'sync' or 'async'")
|
|
39
|
+
if (values.fs !== undefined && !['add', 'replace', 'load'].includes(bundle)) fail('Error: --fs requires --bundle=(add|replace|load)')
|
|
40
|
+
const brotliQuality = brotliQualityOption(values['brotli-quality'], fail)
|
|
41
|
+
const imports = values.import ?? []
|
|
42
|
+
if (imports.some((s) => s === '')) fail('Error: --import requires a module specifier (e.g. --import=./instrument.mjs)')
|
|
43
|
+
return {
|
|
44
|
+
values,
|
|
45
|
+
lock,
|
|
46
|
+
scope: values.dependencies ? 'node_modules' : 'full',
|
|
47
|
+
bundle,
|
|
48
|
+
bundleFile,
|
|
49
|
+
resourcesBundleFile,
|
|
50
|
+
debug: values.debug ? '1' : '',
|
|
51
|
+
childProcess: values['child-process'] ? '1' : '',
|
|
52
|
+
fs: values.fs ?? '',
|
|
53
|
+
resources: values.resources ?? '',
|
|
54
|
+
brotliQuality,
|
|
55
|
+
imports,
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function brotliQualityOption(value, fail) {
|
|
60
|
+
if (value === undefined) return undefined
|
|
61
|
+
try {
|
|
62
|
+
return parseBrotliQuality('--brotli-quality', value)
|
|
63
|
+
} catch (cause) {
|
|
64
|
+
return fail(`Error: ${cause.message}`)
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function setEnv(name, value) {
|
|
69
|
+
const env = process.env[name]
|
|
70
|
+
if (env && env !== value) throw new Error(`env conflict: ${name}="${env}", effective: "${value}"`)
|
|
71
|
+
process.env[name] = value
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function setRunEnv(label, run, extra = {}) {
|
|
75
|
+
const { lock, scope, bundle, bundleFile, resourcesBundleFile, debug, childProcess, fs, resources, brotliQuality, imports } = run
|
|
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 }) })
|
|
77
|
+
if (debug) console.warn(`[${label}] Warning: stasis debug mode active`)
|
|
78
|
+
setEnv('EXODUS_STASIS_LOCK', lock)
|
|
79
|
+
setEnv('EXODUS_STASIS_SCOPE', scope)
|
|
80
|
+
setEnv('EXODUS_STASIS_BUNDLE', bundle)
|
|
81
|
+
setEnv('EXODUS_STASIS_BUNDLE_FILE', bundleFile)
|
|
82
|
+
setEnv('EXODUS_STASIS_RESOURCES_BUNDLE_FILE', resourcesBundleFile)
|
|
83
|
+
setEnv('EXODUS_STASIS_DEBUG', debug)
|
|
84
|
+
setEnv('EXODUS_STASIS_CHILD_PROCESS', childProcess)
|
|
85
|
+
setEnv('EXODUS_STASIS_FS', fs)
|
|
86
|
+
setEnv('EXODUS_STASIS_RESOURCES', resources)
|
|
87
|
+
// Only when given: an unconditional setEnv('') would reject an ambient EXODUS_STASIS_BROTLI_QUALITY.
|
|
88
|
+
if (brotliQuality !== undefined) setEnv('EXODUS_STASIS_BROTLI_QUALITY', String(brotliQuality))
|
|
89
|
+
}
|
|
90
|
+
|
|
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).
|
|
93
|
+
export async function runProgram(argv, { nodeArgs = [], loader, imports }) {
|
|
94
|
+
const args = [...nodeArgs, '--import', loader, ...imports.flatMap((specifier) => ['--import', specifier]), ...argv]
|
|
95
|
+
const child = spawn(process.execPath, args, { stdio: 'inherit' })
|
|
96
|
+
const [code, signal] = await once(child, 'close')
|
|
97
|
+
process.exitCode = code ?? 128 + (osConstants.signals[signal] ?? 0)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Its runtime errors propagate as they are: wrapping them in fail() would bury the cause.
|
|
101
|
+
export async function addCli(argv, { label, fail }) {
|
|
102
|
+
if (argv.length === 0) fail('Nothing to add: no file given')
|
|
103
|
+
if (argv.some((a) => a.startsWith('-'))) fail('Error: add takes no options; its targets and resource allowlist come from stasis.config.json')
|
|
104
|
+
const { addCommand } = await import('./add.js')
|
|
105
|
+
addCommand({ entries: argv, logLabel: label })
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export async function extractCli(argv, { label, fail }) {
|
|
109
|
+
const options = { output: { type: 'string', short: 'o' }, lock: { type: 'string' } }
|
|
110
|
+
const values = parseLeadingOptions(argv, options, { valueFlags: valueFlagsOf(options), onError: fail })
|
|
111
|
+
if (argv.length === 0) fail('Nothing to extract: no bundle file given')
|
|
112
|
+
if (argv.length > 1) fail('Error: extract takes exactly one bundle file')
|
|
113
|
+
if (values.lock !== undefined && !LOCK_MODES.has(values.lock)) fail('Error: invalid --lock value')
|
|
114
|
+
const { extractCommand } = await import('./extract.js')
|
|
115
|
+
extractCommand({ bundleFile: argv[0], output: values.output, lock: values.lock, logLabel: label })
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export async function pruneCli(argv, { label, fail }) {
|
|
119
|
+
if (argv.length > 1) fail('Error: prune takes at most one path argument')
|
|
120
|
+
const { prune } = await import('./prune.js')
|
|
121
|
+
const { removed, validated, minimized } = prune({ root: argv[0] })
|
|
122
|
+
console.warn(`[${label}] prune: validated ${validated.length} file(s), removed ${removed.length} file(s), minimized ${minimized.length} package.json file(s)`)
|
|
123
|
+
}
|