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

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.
@@ -0,0 +1,398 @@
1
+ import { isAbsolute, relative, resolve } from 'node:path'
2
+
3
+ import { diskHost } from '@exodus/stasis-core/host'
4
+ import { readFileSyncMaybe } from '@exodus/stasis-core/state-util'
5
+ import { isPlainObject, parseBrotliQuality, parseResourcesOption, relativeEscapes, toPosix } from '@exodus/stasis-core/util'
6
+ import { parseFeatureList } from '../loaders/cargo.js'
7
+ import { parseDefineFlags } from '../define.js'
8
+ import { directoryEntryError, isSolidityEntry } from './bundle.js'
9
+
10
+ const CONFIG_FILE = 'stasis.config.json'
11
+
12
+ // `stasis bundle`'s flags, as parseArgs takes them, and those taking their value as the next argument.
13
+ export const BUNDLE_FLAGS = {
14
+ mapping: { type: 'string' },
15
+ manifests: { type: 'boolean' },
16
+ output: { type: 'string', short: 'o' },
17
+ scope: { type: 'string' },
18
+ lockfile: { type: 'string' },
19
+ conditions: { type: 'string' },
20
+ mainFields: { type: 'string' },
21
+ metro: { type: 'boolean' },
22
+ 'metro-resolver': { type: 'boolean' },
23
+ babel: { type: 'boolean' },
24
+ 'babel-aliases': { type: 'string' },
25
+ platforms: { type: 'string', multiple: true },
26
+ jsx: { type: 'boolean' },
27
+ flow: { type: 'boolean' },
28
+ typescript: { type: 'boolean' },
29
+ tsconfig: { type: 'string' },
30
+ resources: { type: 'string' },
31
+ 'package-json': { type: 'boolean' },
32
+ define: { type: 'string', multiple: true },
33
+ cargo: { type: 'boolean' },
34
+ 'cargo-features': { type: 'string', multiple: true },
35
+ 'cargo-no-default-features': { type: 'boolean' },
36
+ 'cargo-all-features': { type: 'boolean' },
37
+ 'cargo-target': { type: 'string' },
38
+ 'cargo-manifests': { type: 'boolean' },
39
+ 'brotli-quality': { type: 'string' },
40
+ add: { type: 'boolean' },
41
+ }
42
+ export const BUNDLE_VALUE_FLAGS = ['--mapping', '--output', '--scope', '--lockfile', '--conditions', '--mainFields', '--babel-aliases', '--platforms', '--resources', '--tsconfig', '--define', '--cargo-features', '--cargo-target', '--brotli-quality', '-o']
43
+
44
+ // The flags saying where and how the bundle is written. Every other one says how its entries are
45
+ // built, which stasis.config.json's `entries` sets per entry instead.
46
+ const OUTPUT_FLAGS = new Set(['output', 'lockfile', 'brotli-quality', 'add'])
47
+ // The entry flags taking a list (comma-separated, or repeated), which an entry's options may give as an array.
48
+ const LIST_FLAGS = new Set(['conditions', 'mainFields', 'platforms', 'resources', 'cargo-features'])
49
+ // The entry flags given once per value, which a comma doesn't separate (a define's JSON value may
50
+ // hold one): an entry's options give them as an array, or one as a string.
51
+ const REPEATED_FLAGS = new Set(['define'])
52
+ // The entry flags that run a program -> what they run. Set in stasis.config.json, they take effect
53
+ // only with the same flag given too (a value one, with the same value), as consent: the config can't
54
+ // make a bare `stasis bundle` run anything.
55
+ const CONSENT_FLAGS = new Map([
56
+ ['babel', "the project's Babel config"],
57
+ ['metro-resolver', "the project's metro-resolver"],
58
+ ['cargo', "cargo, and what the project's .cargo/config.toml names"],
59
+ ['cargo-target', 'rustc'],
60
+ ])
61
+ // A flag as given: `--name`, or `--name=value` for one taking a value.
62
+ const flagText = (name, value) => (value === true ? `--${name}` : `--${name}=${value}`)
63
+
64
+ // `entry` as a path relative to `cwd` ('.' for cwd itself), or null where it lies out of it.
65
+ function entryKey(cwd, entry) {
66
+ const rel = relative(resolve(cwd), resolve(cwd, entry))
67
+ return relativeEscapes(rel) ? null : toPosix(rel) || '.'
68
+ }
69
+
70
+ // The language `entries` share, one bundle being built from one: which of them they all are in, as
71
+ // the project in `cwd`, read through `host`, holds them.
72
+ function entriesLanguage(entries, cwd, host = diskHost) {
73
+ const dirError = directoryEntryError(entries, cwd, host)
74
+ if (dirError !== null) throw new Error(dirError)
75
+ const lang = {
76
+ allSol: entries.every((f) => isSolidityEntry(f, cwd, host)),
77
+ allPhp: entries.every((f) => f.endsWith('.php')),
78
+ allJs: entries.every((f) => /\.(?:js|cjs|mjs|ts|cts|mts|jsx|tsx)$/u.test(f)),
79
+ allBash: entries.every((f) => /\.(?:sh|bash)$/u.test(f)),
80
+ allRust: entries.every((f) => f.endsWith('.rs')),
81
+ }
82
+ if (!Object.values(lang).some(Boolean)) {
83
+ throw new Error('bundle entries must all be .sol, all be .php, all be .js/.cjs/.mjs/.ts/.cts/.mts/.jsx/.tsx, all be .sh/.bash, or all be .rs')
84
+ }
85
+ return lang
86
+ }
87
+
88
+ // bundleCommand's options for building `entries` (in `lang`, entriesLanguage's) from the parsed
89
+ // entry flags in `values`. A usage error throws.
90
+ function buildOptions(values, { allSol, allJs, allRust }) {
91
+ if (values.mapping && !allSol) throw new Error('--mapping is only valid for .sol bundles')
92
+ // --manifests: carry the Solidity build's description files (foundry.toml, remappings.txt, ...).
93
+ const manifests = Boolean(values.manifests)
94
+ if (manifests && !allSol) throw new Error('--manifests is only valid for .sol bundles')
95
+ // --cargo: take the Rust feature/dependency resolution from `cargo metadata` (runs cargo; opt-in).
96
+ const cargo = Boolean(values.cargo)
97
+ if (cargo && !allRust) throw new Error('--cargo is only valid for Rust bundles')
98
+ // --cargo-features / --cargo-no-default-features / --cargo-all-features: cargo's own feature flags
99
+ // for the entries' packages (`pkg/feat` targets one, or a dependency). --cargo-features is
100
+ // repeatable and/or comma-separated; parseFeatureList is the one splitter (the resolver reuses it).
101
+ const cargoFeatures = parseFeatureList(values['cargo-features'] ?? [])
102
+ if (values['cargo-features'] !== undefined && cargoFeatures.length === 0) {
103
+ throw new Error('--cargo-features must list at least one feature (e.g. --cargo-features=serde,app/tls)')
104
+ }
105
+ const cargoNoDefaultFeatures = Boolean(values['cargo-no-default-features'])
106
+ const cargoAllFeatures = Boolean(values['cargo-all-features'])
107
+ // --cargo-target=<triple|host>: the build's target, whose cfgs (from `rustc --print cfg`) decide
108
+ // `#[cfg(unix)]`-style code. A triple is letters, digits, `-`, `_` and `.` (`x86_64-unknown-linux-gnu`).
109
+ const cargoTarget = values['cargo-target'] ?? null
110
+ if (cargoTarget !== null && !/^[\w.-]+$/u.test(cargoTarget)) {
111
+ throw new Error('--cargo-target must be a target triple or "host" (e.g. --cargo-target=aarch64-apple-darwin)')
112
+ }
113
+ // --cargo-manifests: carry each bundled package's Cargo.toml and build script, the workspace
114
+ // Cargo.toml, Cargo.lock and .cargo/config.toml too (the Rust counterpart of --package-json).
115
+ const cargoManifests = Boolean(values['cargo-manifests'])
116
+ if (!allRust) {
117
+ const given = { 'cargo-features': cargoFeatures.length > 0, 'cargo-no-default-features': cargoNoDefaultFeatures, 'cargo-all-features': cargoAllFeatures, 'cargo-target': cargoTarget !== null, 'cargo-manifests': cargoManifests }
118
+ for (const [flag, on] of Object.entries(given)) if (on) throw new Error(`--${flag} is only valid for Rust bundles`)
119
+ }
120
+ if (values.scope && !allJs) throw new Error('--scope is only valid for JS bundles')
121
+ if (values.scope && !['node_modules', 'full'].includes(values.scope)) {
122
+ throw new Error('--scope must be node_modules or full')
123
+ }
124
+ // --mainFields/--metro always emit a full-scope bundle, so they'd silently ignore a narrower --scope.
125
+ if (values.scope !== undefined && values.scope !== 'full' && (values.mainFields !== undefined || values.metro)) {
126
+ throw new Error(`--scope=${values.scope} is not supported with --mainFields or --metro (they always build a full-scope bundle)`)
127
+ }
128
+ // --conditions: extra exports/imports resolution conditions merged onto Node's defaults;
129
+ // they don't honour legacy `mainFields` or platform suffixes (see --mainFields).
130
+ if (values.conditions !== undefined && !allJs) throw new Error('--conditions is only valid for JS bundles')
131
+ const conditions = values.conditions === undefined
132
+ ? []
133
+ : values.conditions.split(',').map((s) => s.trim()).filter(Boolean)
134
+ if (values.conditions !== undefined && conditions.length === 0) {
135
+ throw new Error('--conditions must list at least one condition name (e.g. --conditions=react-native,browser)')
136
+ }
137
+ // --flow: strip Flow type syntax (via stasis's own flow-remove-types) before parsing; JS-only.
138
+ if (values.flow && !allJs) throw new Error('--flow is only valid for JS bundles')
139
+ const flow = Boolean(values.flow)
140
+ // --typescript: resolve like tsc -- a specifier naming a missing JS output (./x.js, .mjs, .cjs,
141
+ // extensionless) lands on its on-disk TS source (./x.ts, .mts, .cts); an existing .js always wins.
142
+ if (values.typescript && !allJs) throw new Error('--typescript is only valid for JS bundles')
143
+ const typescript = Boolean(values.typescript)
144
+ // --tsconfig: the config whose compilerOptions.paths aliases --typescript honours (default: the
145
+ // tsconfig.json beside each importing file's package.json). Meaningless without --typescript.
146
+ if (values.tsconfig !== undefined && !typescript) throw new Error('--tsconfig is only valid with --typescript')
147
+ // --mainFields: legacy package entry fields (e.g. react-native,browser,main) for the non-exports resolver.
148
+ if (values.mainFields !== undefined && !allJs) throw new Error('--mainFields is only valid for JS bundles')
149
+ const mainFields = values.mainFields === undefined
150
+ ? undefined
151
+ : values.mainFields.split(',').map((s) => s.trim()).filter(Boolean)
152
+ if (values.mainFields !== undefined && mainFields.length === 0) {
153
+ throw new Error('--mainFields must list at least one field (e.g. --mainFields=react-native,browser,main)')
154
+ }
155
+ // --metro: resolve like Metro/RN (its own conditions + mainFields, platform suffixes per
156
+ // --platforms target). --platforms is repeatable and/or comma-separated; the values union.
157
+ const metro = Boolean(values.metro)
158
+ // --metro-resolver: resolve through the project's own metro-resolver instead of the built-in
159
+ // approximation. Only meaningful alongside --metro (enforced below and in classifyEntries).
160
+ const metroResolver = Boolean(values['metro-resolver'])
161
+ const platforms = [...new Set((values.platforms ?? []).flatMap((p) => p.split(',')).map((s) => s.trim()).filter(Boolean))]
162
+ // A platform name becomes an edge key: reject '/' (parsers reject it) and '*' (reserved placeholder).
163
+ for (const p of platforms) {
164
+ if (p === '*' || p.includes('/')) throw new Error(`invalid --platforms value '${p}' (a platform name can't contain '/' or be '*')`)
165
+ }
166
+ if ((metro || platforms.length > 0) && !allJs) throw new Error('--metro is only valid for JS bundles')
167
+ // --jsx: parse React Native's JSX-in-.js source in the static scanner (off by default; oxc,
168
+ // like tsc, auto-enables JSX for .jsx/.tsx only). Orthogonal to the resolver, so it pairs with
169
+ // plain/--mainFields/--metro alike -- JS-only, since no other entry language is scanned.
170
+ const jsx = Boolean(values.jsx)
171
+ if (jsx && !allJs) throw new Error('--jsx is only valid for JS bundles')
172
+ // --package-json: fold each bundled module's package.json into the bundle. JS-only (only JS
173
+ // modules carry an npm package.json; the sol/php/bash/rust bucketizers have no such manifest).
174
+ const packageJSON = Boolean(values['package-json'])
175
+ if (packageJSON && !allJs) throw new Error('--package-json is only valid for JS bundles')
176
+ // --resources: comma-separated extension/filename allowlist for assets reached through the graph
177
+ // (e.g. --resources=png,svg). They're carried as resources instead of failing "can't carry" --
178
+ // for graphs that aren't fully loadable in JS (Metro consumes such assets). JS-only.
179
+ if (values.resources !== undefined && !allJs) throw new Error('--resources is only valid for JS bundles')
180
+ const resources = values.resources === undefined
181
+ ? undefined
182
+ : values.resources.split(',').map((s) => s.trim()).filter(Boolean)
183
+ if (values.resources !== undefined && resources.length === 0) {
184
+ throw new Error('--resources must list at least one extension or filename (e.g. --resources=png,svg)')
185
+ }
186
+ parseResourcesOption('--resources', resources) // validate early for a clean usage error (code exts / bad chars rejected)
187
+ if (metro) {
188
+ if (conditions.length > 0) throw new Error("--conditions can't be combined with --metro (it sets its own conditions)")
189
+ if (mainFields !== undefined) throw new Error("--mainFields can't be combined with --metro (it sets its own mainFields)")
190
+ if (platforms.length === 0) throw new Error('--metro requires --platforms (e.g. --platforms=ios,android)')
191
+ } else if (platforms.length > 0) {
192
+ throw new Error('--platforms is only valid with --metro')
193
+ }
194
+ if (metroResolver && !metro) throw new Error('--metro-resolver is only valid with --metro')
195
+ // --babel: resolve through the import aliases (babel-plugin-module-resolver) of the project's
196
+ // babel.config.*, which Metro runs before it resolves. Runs that config, so opt-in; --metro only.
197
+ const babel = Boolean(values.babel)
198
+ if (babel && !metro) throw new Error('--babel is only valid with --metro')
199
+ // --babel-aliases: the same aliases from a JSON file of the project (module-resolver's `alias` option as
200
+ // data), which runs nothing, so stasis.config.json's entries may set it alone. --metro only.
201
+ if (values['babel-aliases'] !== undefined && !metro) throw new Error('--babel-aliases is only valid with --metro')
202
+ if (values['babel-aliases'] !== undefined && babel) throw new Error("--babel-aliases can't be combined with --babel (both set the import aliases)")
203
+ // metro-resolver can't substitute .js -> .ts, so --typescript would silently not apply -- reject it.
204
+ if (typescript && metroResolver) throw new Error("--typescript is not supported with --metro-resolver (the project's metro-resolver doesn't substitute .js -> .ts)")
205
+ // --define=KEY=VALUE: a global's value (JSON), repeatable; the scan leaves out the imports of the
206
+ // branches the values keep from running (`if (__DEV__)` under __DEV__=false). JS-only.
207
+ if (values.define !== undefined && !allJs) throw new Error('--define is only valid for JS bundles')
208
+ const define = values.define === undefined ? undefined : parseDefineFlags(null, values.define)
209
+ return { mappingFile: values.mapping, manifests, scope: values.scope, conditions, mainFields, metro, metroResolver, babel, babelAliases: values['babel-aliases'], platforms, jsx, flow, typescript, tsconfig: values.tsconfig, resources, define, packageJSON, cargo, cargoFeatures, cargoNoDefaultFeatures, cargoAllFeatures, cargoTarget, cargoManifests }
210
+ }
211
+
212
+ // bundleCommand's options for writing the bundle of entries in `lang` from the parsed output flags in `values`.
213
+ function outputOptions(values, { allJs }) {
214
+ if (values.lockfile && !allJs) throw new Error('--lockfile is only valid for JS bundles')
215
+ // --brotli-quality: valid for every entry language (no allJs gate).
216
+ const brotliQuality = values['brotli-quality'] === undefined ? undefined : parseBrotliQuality('--brotli-quality', values['brotli-quality'])
217
+ // --add merges into the existing bundle at --output, so it can't target write-only stdout.
218
+ const add = Boolean(values.add)
219
+ if (add && values.output === '-') throw new Error('--add cannot be combined with --output=-')
220
+ return { output: values.output, lockfile: values.lockfile, brotliQuality, add }
221
+ }
222
+
223
+ // An entry's options in stasis.config.json's `entries` (`what` names it) as the flags they alias, in
224
+ // parseArgs' shape: `true` for a boolean flag set (`false`, its default, is no flag), a string for one
225
+ // taking a value, which a list flag takes as an array too, and an array of it for a repeatable one
226
+ // (each of a REPEATED_FLAGS one's values, as given).
227
+ function entryFlags(what, options) {
228
+ if (!isPlainObject(options)) throw new Error(`${what} must be an object of stasis bundle options`)
229
+ const values = {}
230
+ for (const [flag, value] of Object.entries(options)) {
231
+ if (OUTPUT_FLAGS.has(flag)) throw new Error(`${what}: ${flag} is the bundle's option, not an entry's: pass --${flag}`)
232
+ if (!Object.hasOwn(BUNDLE_FLAGS, flag)) throw new Error(`${what}: unknown option ${JSON.stringify(flag)}`)
233
+ const { type, multiple } = BUNDLE_FLAGS[flag]
234
+ if (type === 'boolean') {
235
+ if (typeof value !== 'boolean') throw new Error(`${what}: ${flag} must be true or false`)
236
+ if (value) values[flag] = true
237
+ continue
238
+ }
239
+ const takesArray = LIST_FLAGS.has(flag) || REPEATED_FLAGS.has(flag)
240
+ const list = takesArray && Array.isArray(value) && value.every((v) => typeof v === 'string')
241
+ if (typeof value !== 'string' && !list) throw new Error(`${what}: ${flag} must be a string${takesArray ? ' or an array of strings' : ''}`)
242
+ if (REPEATED_FLAGS.has(flag)) {
243
+ values[flag] = [value].flat()
244
+ continue
245
+ }
246
+ const text = list ? value.join(',') : value
247
+ values[flag] = multiple ? [text] : text
248
+ }
249
+ return values
250
+ }
251
+
252
+ // The `entries` of the stasis.config.json in `cwd`: each entry it names, as a path relative to cwd
253
+ // -> { entry: the name as written, values: its options as flags (entryFlags') }. null where there is
254
+ // none.
255
+ export function readConfigEntries(cwd = process.cwd(), host = diskHost) {
256
+ const text = readFileSyncMaybe(resolve(cwd), CONFIG_FILE, 'utf8', host)
257
+ if (text === null) return null
258
+ let config
259
+ try {
260
+ config = JSON.parse(text)
261
+ } catch (cause) {
262
+ throw new Error(`${CONFIG_FILE} is not valid JSON`, { cause })
263
+ }
264
+ const entries = config?.entries
265
+ if (entries === undefined) return null
266
+ if (!isPlainObject(entries)) throw new Error(`${CONFIG_FILE}: entries must be an object of each entry's stasis bundle options`)
267
+ const named = new Map()
268
+ for (const [entry, options] of Object.entries(entries)) {
269
+ const what = `${CONFIG_FILE}: entries ${JSON.stringify(entry)}`
270
+ const key = isAbsolute(entry) ? null : entryKey(cwd, entry)
271
+ if (key === null) throw new Error(`${what}: an entry must be a path relative to the directory of ${CONFIG_FILE}, within it`)
272
+ if (named.has(key)) throw new Error(`${what} names the same entry as ${JSON.stringify(named.get(key).entry)}`)
273
+ named.set(key, { entry, values: entryFlags(what, options) })
274
+ }
275
+ return named
276
+ }
277
+
278
+ // bundleCommand's options for bundling `entries` with the parsed flags `values` in `cwd`, whose
279
+ // stasis.config.json's `entries` is `config` (readConfigEntries'). Where it names every entry, each is
280
+ // built with its options there, the ones with the same options together (a build each), and none
281
+ // may be given as a flag but the bundle's own (OUTPUT_FLAGS) and the consent to a CONSENT_FLAGS
282
+ // option, which an entry setting it needs and some entry must set. Where it names none, they are all
283
+ // built with the flags; it may not name only some. A usage error throws.
284
+ export function bundlePlan({ cwd = process.cwd(), entries, values, config = null }) {
285
+ const lang = entriesLanguage(entries, cwd)
286
+ const output = outputOptions(values, lang)
287
+ const keys = entries.map((entry) => entryKey(cwd, entry))
288
+ const configured = config === null ? [] : entries.filter((_, i) => config.has(keys[i]))
289
+ if (configured.length === 0) return { ...output, entries, ...buildOptions(values, lang) }
290
+ const unnamed = entries.find((_, i) => !config.has(keys[i]))
291
+ if (unnamed !== undefined) {
292
+ throw new Error(`${CONFIG_FILE}'s entries name ${configured[0]} but not ${unnamed}: bundle either the entries it names or others, not both`)
293
+ }
294
+ const flag = Object.keys(values).find((name) => !OUTPUT_FLAGS.has(name) && !CONSENT_FLAGS.has(name))
295
+ if (flag !== undefined) throw new Error(`--${flag} can't be given for ${configured[0]}, whose options ${CONFIG_FILE}'s entries set: set it there`)
296
+ const named = keys.map((key) => config.get(key))
297
+ for (const consent of CONSENT_FLAGS.keys()) {
298
+ const given = values[consent]
299
+ if (given !== undefined && !named.some(({ values: flags }) => flags[consent] === given)) {
300
+ throw new Error(`${flagText(consent, given)} is given, but ${CONFIG_FILE}'s entries set ${flagText(consent, given).slice(2)} for none of ${entries.join(', ')}`)
301
+ }
302
+ }
303
+ const builds = new Map()
304
+ for (const [i, entry] of entries.entries()) {
305
+ const { entry: name, values: flags } = named[i]
306
+ const unconsented = [...CONSENT_FLAGS.keys()].find((consent) => flags[consent] !== undefined && values[consent] !== flags[consent])
307
+ if (unconsented !== undefined) {
308
+ const consent = flagText(unconsented, flags[unconsented])
309
+ throw new Error(`${CONFIG_FILE}: entries ${JSON.stringify(name)} sets ${consent.slice(2)}, which runs ${CONSENT_FLAGS.get(unconsented)}: pass ${consent} to allow it`)
310
+ }
311
+ let options
312
+ try {
313
+ options = buildOptions(flags, entriesLanguage([entry], cwd))
314
+ } catch (cause) {
315
+ throw new Error(`${CONFIG_FILE}: entries ${JSON.stringify(name)}: ${cause.message}`, { cause })
316
+ }
317
+ const id = JSON.stringify(options)
318
+ if (builds.has(id)) builds.get(id).entries.push(entry)
319
+ else builds.set(id, { entries: [entry], ...options })
320
+ }
321
+ return { ...output, builds: [...builds.values()] }
322
+ }
323
+
324
+ // buildOptions' options, each by the flag it is given as; and those whose values are a set, in
325
+ // whatever order given (each value of `resources` as parseResourcesOption takes it).
326
+ const OPTION_FLAGS = {
327
+ mappingFile: 'mapping', manifests: 'manifests', scope: 'scope', conditions: 'conditions', mainFields: 'mainFields', metro: 'metro', metroResolver: 'metro-resolver', babel: 'babel', babelAliases: 'babel-aliases', platforms: 'platforms', jsx: 'jsx', flow: 'flow', typescript: 'typescript', tsconfig: 'tsconfig', resources: 'resources', define: 'define', packageJSON: 'package-json', cargo: 'cargo', cargoFeatures: 'cargo-features', cargoNoDefaultFeatures: 'cargo-no-default-features', cargoAllFeatures: 'cargo-all-features', cargoTarget: 'cargo-target', cargoManifests: 'cargo-manifests',
328
+ }
329
+ const SET_OPTIONS = new Set(['conditions', 'platforms', 'resources', 'cargoFeatures'])
330
+ // buildOptions' options where no flag is given.
331
+ const DEFAULT_OPTIONS = buildOptions({}, {})
332
+ // An option's value as compared: a set's sorted, defines by name, none (null) for no value or no define.
333
+ const comparable = (key, value) => {
334
+ if (value === undefined || value === null || (key === 'define' && isPlainObject(value) && Object.keys(value).length === 0)) return 'null'
335
+ if (key === 'resources' && Array.isArray(value)) value = value.map((v) => (typeof v === 'string' ? v.toLowerCase().replace(/^\./u, '') : v))
336
+ if (SET_OPTIONS.has(key) && Array.isArray(value)) return JSON.stringify([...new Set(value)].toSorted())
337
+ if (key === 'define' && isPlainObject(value)) return JSON.stringify(Object.entries(value).toSorted(([a], [b]) => (a < b ? -1 : 1)))
338
+ return JSON.stringify(value)
339
+ }
340
+ // An option as its flags give it: `--jsx`, `--platforms=ios,android`, `--define=__DEV__=false`.
341
+ const optionText = (key, value) => (key === 'define'
342
+ ? Object.entries(value).map(([name, v]) => `--define=${name}=${JSON.stringify(v)}`).join(' ')
343
+ : flagText(OPTION_FLAGS[key], Array.isArray(value) ? value.join(',') : value))
344
+
345
+ // The builds of `entries` that the stasis.config.json in `cwd` (read through `host`) names in its
346
+ // `entries`, for `name`'s bundle, built from a project it runs nothing of
347
+ // (@exodus/stasis/vfs-bundle's): every entry it names where none are given (none, of an empty
348
+ // `entries`: nothing else stands in for them), as paths from `cwd`.
349
+ // -> { entries, builds }, each build `{ entries, ...options }` with the options there (buildOptions'),
350
+ // the entries with the same ones together; null where it names none of those given, or has no
351
+ // `entries`: they are built with `options` alone. It may not name only some. Each of `options`
352
+ // (buildOptions' shape) given other than at its default has to be the one each entry's options
353
+ // set, else it is refused, neither taken over them nor left aside; one left out is theirs. One that
354
+ // runs a program (CONSENT_FLAGS'), set by an entry or given, is refused: nothing of the project
355
+ // runs, so no option allows it. A usage error throws.
356
+ export function configuredBuilds(name, { cwd, host = diskHost, entries, options = {} }) {
357
+ const prefixed = (fn, what = `${name}: `) => {
358
+ try {
359
+ return fn()
360
+ } catch (cause) {
361
+ throw new Error(`${what}${cause.message}`, { cause })
362
+ }
363
+ }
364
+ const config = prefixed(() => readConfigEntries(cwd, host))
365
+ if (config === null || (entries !== undefined && !Array.isArray(entries))) return null
366
+ if (entries === undefined) {
367
+ entries = [...config.keys()]
368
+ if (entries.length === 0) return { entries, builds: [] }
369
+ }
370
+ const keys = entries.map((entry) => entryKey(cwd, entry))
371
+ const configured = entries.filter((_, i) => config.has(keys[i]))
372
+ if (configured.length === 0) return null
373
+ const unnamed = entries.find((_, i) => !config.has(keys[i]))
374
+ if (unnamed !== undefined) {
375
+ throw new Error(`${name}: ${CONFIG_FILE}'s entries name ${configured[0]} but not ${unnamed}: bundle either the entries it names or others, not both`)
376
+ }
377
+ const given = Object.keys(OPTION_FLAGS).filter((key) => options[key] !== undefined && comparable(key, options[key]) !== comparable(key, DEFAULT_OPTIONS[key]))
378
+ const builds = new Map()
379
+ for (const [i, entry] of entries.entries()) {
380
+ const { entry: written, values } = config.get(keys[i])
381
+ const what = `${name}: ${CONFIG_FILE}: entries ${JSON.stringify(written)}`
382
+ const running = [...CONSENT_FLAGS.keys()].find((flag) => values[flag] !== undefined)
383
+ if (running !== undefined) throw new Error(`${what} sets ${running}, which runs ${CONSENT_FLAGS.get(running)}, and nothing of the project runs here`)
384
+ const built = prefixed(() => buildOptions(values, entriesLanguage([entry], cwd, host)), `${what}: `)
385
+ for (const key of given) {
386
+ if (CONSENT_FLAGS.has(OPTION_FLAGS[key])) continue
387
+ if (comparable(key, options[key]) === comparable(key, built[key])) continue
388
+ const set = comparable(key, built[key]) === comparable(key, DEFAULT_OPTIONS[key]) ? `without --${OPTION_FLAGS[key]}` : `with ${optionText(key, built[key])}`
389
+ throw new Error(`${name}: ${optionText(key, options[key])} is given, but ${CONFIG_FILE}'s entries build ${JSON.stringify(written)} ${set}: an entry it names is built with its options there`)
390
+ }
391
+ const id = JSON.stringify(built)
392
+ if (builds.has(id)) builds.get(id).entries.push(entry)
393
+ else builds.set(id, { entries: [entry], ...built })
394
+ }
395
+ const running = given.find((key) => CONSENT_FLAGS.has(OPTION_FLAGS[key]))
396
+ if (running !== undefined) throw new Error(`${name}: ${optionText(running, options[running])} is given, which runs ${CONSENT_FLAGS.get(OPTION_FLAGS[running])}, and nothing of the project runs here`)
397
+ return { entries, builds: [...builds.values()] }
398
+ }