@exodus/stasis 1.0.0-beta.12 → 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.
package/bin/stasis.js CHANGED
@@ -24,7 +24,7 @@ const HELP = `Usage:
24
24
  stasis bundle [--mapping=path/to/remappings(.txt|.toml)] [--manifests] [--add] [--output=(path|-)] path/to/(file.sol|dir) ...
25
25
  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
26
  stasis bundle [--add] [--output=(path|-)] path/to/file.(php|sh|bash) ...
27
- stasis bundle [--babel] [--metro-resolver] [--flow] [--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 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
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) ...]
29
29
  stasis add path/to/(file|dir) ...
30
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]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@exodus/stasis",
3
- "version": "1.0.0-beta.12",
3
+ "version": "1.0.0-beta.13",
4
4
  "description": "File-level source bundles and lockfiles",
5
5
  "type": "module",
6
6
  "exports": {
@@ -97,19 +97,19 @@
97
97
  "homepage": "https://github.com/PreventiveMeasures/stasis#readme",
98
98
  "dependencies": {
99
99
  "@exodus/bytes": "^1.16.0",
100
- "@exodus/stasis-core": "1.0.0-beta.12",
101
- "@exodus/stasis-plugins": "1.0.0-beta.12",
100
+ "@exodus/stasis-core": "1.0.0-beta.13",
101
+ "@exodus/stasis-plugins": "1.0.0-beta.13",
102
102
  "@preventive/archive": "^1.2.0",
103
103
  "@preventive/deptree": "^1.0.1",
104
104
  "@preventive/lockfile": "^1.2.0",
105
105
  "@preventive/upstream": "^1.3.0",
106
106
  "@preventive/vfs": "1.0.0-beta.4",
107
+ "flow-remove-types": "^2.322.0",
107
108
  "oxc-parser": "^0.152.0"
108
109
  },
109
110
  "peerDependencies": {
110
111
  "@prisma/client-generator-ts": "7.10.0",
111
- "esbuild": "*",
112
- "flow-remove-types": "*"
112
+ "esbuild": "*"
113
113
  },
114
114
  "peerDependenciesMeta": {
115
115
  "@prisma/client-generator-ts": {
@@ -117,9 +117,6 @@
117
117
  },
118
118
  "esbuild": {
119
119
  "optional": true
120
- },
121
- "flow-remove-types": {
122
- "optional": true
123
120
  }
124
121
  }
125
122
  }
@@ -55,7 +55,6 @@ const REPEATED_FLAGS = new Set(['define'])
55
55
  const CONSENT_FLAGS = new Map([
56
56
  ['babel', "the project's Babel config"],
57
57
  ['metro-resolver', "the project's metro-resolver"],
58
- ['flow', "the flow-remove-types the project installs (stasis's peer)"],
59
58
  ['cargo', "cargo, and what the project's .cargo/config.toml names"],
60
59
  ['cargo-target', 'rustc'],
61
60
  ])
@@ -68,12 +67,13 @@ function entryKey(cwd, entry) {
68
67
  return relativeEscapes(rel) ? null : toPosix(rel) || '.'
69
68
  }
70
69
 
71
- // The language `entries` share, one bundle being built from one: which of them they all are in.
72
- function entriesLanguage(entries, cwd) {
73
- const dirError = directoryEntryError(entries, cwd)
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
74
  if (dirError !== null) throw new Error(dirError)
75
75
  const lang = {
76
- allSol: entries.every((f) => isSolidityEntry(f, cwd)),
76
+ allSol: entries.every((f) => isSolidityEntry(f, cwd, host)),
77
77
  allPhp: entries.every((f) => f.endsWith('.php')),
78
78
  allJs: entries.every((f) => /\.(?:js|cjs|mjs|ts|cts|mts|jsx|tsx)$/u.test(f)),
79
79
  allBash: entries.every((f) => /\.(?:sh|bash)$/u.test(f)),
@@ -134,7 +134,7 @@ function buildOptions(values, { allSol, allJs, allRust }) {
134
134
  if (values.conditions !== undefined && conditions.length === 0) {
135
135
  throw new Error('--conditions must list at least one condition name (e.g. --conditions=react-native,browser)')
136
136
  }
137
- // --flow: strip Flow type syntax (via the optional flow-remove-types dep) before parsing; JS-only.
137
+ // --flow: strip Flow type syntax (via stasis's own flow-remove-types) before parsing; JS-only.
138
138
  if (values.flow && !allJs) throw new Error('--flow is only valid for JS bundles')
139
139
  const flow = Boolean(values.flow)
140
140
  // --typescript: resolve like tsc -- a specifier naming a missing JS output (./x.js, .mjs, .cjs,
@@ -320,3 +320,79 @@ export function bundlePlan({ cwd = process.cwd(), entries, values, config = null
320
320
  }
321
321
  return { ...output, builds: [...builds.values()] }
322
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
+ }
package/src/cmd/bundle.js CHANGED
@@ -7,7 +7,7 @@ import { brotliDecompressSync } from 'node:zlib'
7
7
  import { Bundle, isValidRepoField } from '@exodus/stasis-core/bundle'
8
8
  import { Lockfile } from '@exodus/stasis-core/lockfile'
9
9
  import { extraArtifacts } from '@exodus/stasis-core/add'
10
- import { importsTypescriptByOutputName, scan } from '../scan.js'
10
+ import { Scan, importsTypescriptByOutputName, scan } from '../scan.js'
11
11
  import { parseDefine } from '../define.js'
12
12
  import { createFieldResolver, resolveConditions } from '../resolve-fields.js'
13
13
  import { discoverTsconfig, isDir, loadTsconfigPaths, packageTsconfigPaths } from '../resolve-typescript.js'
@@ -17,7 +17,7 @@ import { linkedNativePackages, looksNative, nativeInputs } from '@exodus/stasis-
17
17
  import { pinInstalledCommits } from '../installed-commits.js'
18
18
  import { State } from '@exodus/stasis-core/state'
19
19
  import { readFileSyncMaybe, sha512integrity } from '@exodus/stasis-core/state-util'
20
- import { checkoutCommit, detectRepo, findPackageMetadata, normalizeEntries, packageType, parseGithubRepository, readJson, readModuleManifest, readPackageJson, readRegularFileOrNull } from '@exodus/stasis-core/bundle-util'
20
+ import { checkoutCommit, detectRepo, findPackageMetadata, normalizeEntries, packageJSONStat, packageType, parseGithubRepository, readJson, readModuleManifest, readPackageJson, readRegularFileOrNull, scopeManifestOf } from '@exodus/stasis-core/bundle-util'
21
21
  import { EMPTY_MODULE_PATH, RN_CORE_INCLUDE_FILES, assertRealPathWithinBase, hasNodeModulesSegment, isDotEnvFile, isExecutableFile, isPathWithin, isPlainObject, moduleFileKey, moduleInfo, parseExtraOption, parseResourcesOption, posixPathEscapes, relativeEscapes, splitNodeModulesPath, toPosix, withMetadataOf } from '@exodus/stasis-core/util'
22
22
  import { diskHost } from '@exodus/stasis-core/host'
23
23
  import { parseSoldeerLockfile } from '@preventive/lockfile/soldeer.js'
@@ -960,6 +960,11 @@ function innermostRootOf(baseDir, files, root, host) {
960
960
  const SOURCE_EXTS = ['js', 'jsx', 'json', 'ts', 'tsx']
961
961
  // React Native preset mainFields for `--metro` (which also sets the RN conditions + platform suffixes).
962
962
  const METRO_MAIN_FIELDS = ['react-native', 'browser', 'main']
963
+
964
+ // The config files a React Native app's build loads from its project root, though nothing the app
965
+ // imports reaches them: Metro's and the React Native CLI's, and with --babel(-aliases) Babel's.
966
+ const METRO_CONFIG_FILES = ['metro.config.js', 'react-native.config.js']
967
+ const BABEL_CONFIG_FILE = 'babel.config.js'
963
968
  // What esbuild and webpack 5 both assert on every platform besides `import`/`require` and
964
969
  // `default`, and so `--mainFields` too: `module`, the bundler-only condition a package's ESM build
965
970
  // sits under, from an import and a require alike. (esbuild drops it when given conditions of its
@@ -1348,23 +1353,44 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
1348
1353
  }
1349
1354
  }
1350
1355
  }
1356
+
1357
+ // And the project's configs the Metro plugin's run loads, which nothing the app imports reaches:
1358
+ // Metro's and the React Native CLI's, and with --babel or --babel-aliases the Babel config Metro's
1359
+ // transformer runs. Each file itself, in the format Node loads it in (its package's `type`, else
1360
+ // the one Node detects from its syntax, as Scan#parseFile has it), not what it imports.
1361
+ const configs = [...METRO_CONFIG_FILES, ...(babel || aliasesFile !== undefined ? [BABEL_CONFIG_FILE] : [])]
1362
+ const configScan = new Scan({ host })
1363
+ for (const rel of configs) {
1364
+ const abs = join(baseDir, rel)
1365
+ if (sources.has(rel) || !host.stat(abs)?.isFile()) continue
1366
+ assertRealPathWithinBase(realBase, baseDir, rel, host)
1367
+ const buf = host.readFile(abs)
1368
+ if (!isUtf8(buf)) throw new Error(`config is not valid UTF-8: ${rel}`)
1369
+ const parsed = configScan.parseFile(abs)
1370
+ put(rel, buf.toString('utf8'), parsed.format ?? parsed.declared ?? 'commonjs', buf)
1371
+ }
1351
1372
  }
1352
1373
 
1353
1374
  // --package-json (or the config's packageJSON): fold each bundled module's package.json into
1354
- // `sources` (and its integrity into the companion lockfile) even when the scan never reached it.
1375
+ // `sources` (and its integrity into the companion lockfile) even when the scan never reached it,
1376
+ // and the nearer one a reached file of it has (scopeManifestOf: a `{"type":"module"}` marker such
1377
+ // as `esm/package.json`), which Metro's resolver reads for the file, as the State path does.
1355
1378
  // Buckets are the ones assembleCodeBundle derives, from the same `packageOf` (its pkgDir, else the
1356
1379
  // '.' workspace bucket). readModuleManifest applies the read/validate rules shared with the State
1357
1380
  // path (containment, UTF-8-aborts); no identity check here -- these buckets are all fresh from disk.
1358
1381
  if (withManifests) {
1359
- const pkgDirs = new Set()
1382
+ const found = new Map()
1383
+ const exists = (rel) => found.get(rel) ?? found.set(rel, packageJSONStat(host, join(baseDir, rel))?.isFile() ?? false).get(rel)
1384
+ const manifests = new Set()
1360
1385
  for (const abs of reached) {
1361
1386
  const rel = toRel(abs)
1362
- const meta = packageOf(rel)
1363
- if (meta) pkgDirs.add(meta.pkgDir)
1364
- else if (!splitNodeModulesPath(rel)) pkgDirs.add('.')
1387
+ const pkgDir = packageOf(rel)?.pkgDir ?? (splitNodeModulesPath(rel) ? undefined : '.')
1388
+ if (pkgDir === undefined) continue
1389
+ manifests.add(moduleFileKey(pkgDir, 'package.json'))
1390
+ const nearest = scopeManifestOf(rel, pkgDir, exists)
1391
+ if (nearest !== undefined) manifests.add(nearest)
1365
1392
  }
1366
- for (const pkgDir of pkgDirs) {
1367
- const rel = moduleFileKey(pkgDir, 'package.json')
1393
+ for (const rel of manifests) {
1368
1394
  if (sources.has(rel)) continue
1369
1395
  const buf = readModuleManifest({ baseDir, realBase, rel, host })
1370
1396
  if (!buf) continue
@@ -1424,7 +1450,9 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
1424
1450
 
1425
1451
  // Classify entries into their single shared language and check option applicability; `name` prefixes
1426
1452
  // errors. A directory entry (resolved against `cwd`, on `host`) stands for the .sol files under it: Solidity only.
1427
- function classifyEntries(name, { cwd = process.cwd(), entries, mappingFile, manifests, scope, lockfile, conditions, mainFields, platforms, metro, metroResolver, babel, babelAliases, jsx, flow, typescript, tsconfig, resources, define, packageJSON, cargo, cargoFeatures, cargoNoDefaultFeatures, cargoAllFeatures, cargoTarget, cargoManifests, host = diskHost, fetched }) {
1453
+ // `partial`: the options may yet be completed by a stasis.config.json entry's (configuredBuilds), so
1454
+ // what one needs of another one there could set (`--platforms` of `--metro`) is left to the build.
1455
+ function classifyEntries(name, { cwd = process.cwd(), entries, mappingFile, manifests, scope, lockfile, conditions, mainFields, platforms, metro, metroResolver, babel, babelAliases, jsx, flow, typescript, tsconfig, resources, define, packageJSON, cargo, cargoFeatures, cargoNoDefaultFeatures, cargoAllFeatures, cargoTarget, cargoManifests, host = diskHost, fetched, partial = false }) {
1428
1456
  if (!Array.isArray(entries) || entries.length === 0) {
1429
1457
  throw new Error(`${name}: at least one entry file is required`)
1430
1458
  }
@@ -1471,7 +1499,7 @@ function classifyEntries(name, { cwd = process.cwd(), entries, mappingFile, mani
1471
1499
  throw new Error(`${name}: --typescript is only valid for JS bundles`)
1472
1500
  }
1473
1501
  // --tsconfig names the config whose `paths` aliases --typescript honours; meaningless without it.
1474
- if (tsconfig !== undefined && !typescript) {
1502
+ if (tsconfig !== undefined && !typescript && !partial) {
1475
1503
  throw new Error(`${name}: --tsconfig is only valid with --typescript`)
1476
1504
  }
1477
1505
  // --resources carries allowlisted assets reached through the JS import graph; JS-only. The list
@@ -1511,17 +1539,17 @@ function classifyEntries(name, { cwd = process.cwd(), entries, mappingFile, mani
1511
1539
  if (mainFields !== undefined) {
1512
1540
  throw new Error(`${name}: --mainFields can't be combined with --metro (it sets its own mainFields)`)
1513
1541
  }
1514
- if (!Array.isArray(platforms) || platforms.length === 0) {
1542
+ if ((!Array.isArray(platforms) || platforms.length === 0) && !partial) {
1515
1543
  throw new Error(`${name}: --metro requires --platforms (e.g. --platforms=ios,android)`)
1516
1544
  }
1517
1545
  // A platform name becomes an edge key: reject '/' (Bundle/Lockfile parse refuse it) and
1518
1546
  // the reserved '*' placeholder, so the writer never emits a map the readers reject.
1519
- for (const p of platforms) {
1547
+ for (const p of Array.isArray(platforms) ? platforms : []) {
1520
1548
  if (typeof p !== 'string' || p.length === 0 || p === '*' || p.includes('/')) {
1521
1549
  throw new Error(`${name}: invalid platform '${p}' (a platform name can't be empty, contain '/', or be '*')`)
1522
1550
  }
1523
1551
  }
1524
- } else if (Array.isArray(platforms) && platforms.length > 0) {
1552
+ } else if (Array.isArray(platforms) && platforms.length > 0 && !partial) {
1525
1553
  throw new Error(`${name}: --platforms is only valid with --metro`)
1526
1554
  }
1527
1555
  // --metro-resolver swaps in the project's real metro-resolver; it only means something under --metro.
@@ -1535,7 +1563,7 @@ function classifyEntries(name, { cwd = process.cwd(), entries, mappingFile, mani
1535
1563
  // --babel-aliases takes the same aliases from a JSON file instead, so the two don't combine.
1536
1564
  if (babelAliases !== undefined) {
1537
1565
  if (typeof babelAliases !== 'string' || babelAliases === '') throw new TypeError(`${name}: babelAliases must be a path to a JSON file`)
1538
- if (!metro) throw new Error(`${name}: --babel-aliases is only valid with --metro`)
1566
+ if (!metro && !partial) throw new Error(`${name}: --babel-aliases is only valid with --metro`)
1539
1567
  if (babel) throw new Error(`${name}: --babel-aliases can't be combined with --babel (both set the import aliases)`)
1540
1568
  }
1541
1569
  // metro-resolver has no TS extension substitution, so --typescript would silently not apply -- reject it.
@@ -1630,7 +1658,11 @@ export function checkVfsOptions(name, options) {
1630
1658
  // would install, or its Solidity options, through the dependencies folder 'soldeer' would install; with
1631
1659
  // nothing read from disk but tarballs and zips, nor from the environment: a Solidity bundle is
1632
1660
  // built with foundry.toml's default profile, whatever FOUNDRY_PROFILE or remappings one sets, and no
1633
- // EXODUS_STASIS_* setting is read. `repo`, the informational `{ github, directory, commit }`,
1661
+ // EXODUS_STASIS_* setting is read. The entries the stasis.config.json in cwd names in its `entries`
1662
+ // (every one, where none are given) are built with their options there, as `stasis bundle` builds
1663
+ // them, but none that runs a program; an option given has to agree with theirs, one left out is
1664
+ // theirs (configuredBuilds).
1665
+ // `repo`, the informational `{ github, directory, commit }`,
1634
1666
  // is the Bundle's, over what is detected in the Vfs as `stasis bundle` detects it on disk. `os`,
1635
1667
  // `cpu` and `libc` are loadNodeModules'. Without a `packageManager`, it is the one whose lockfile
1636
1668
  // installs cwd, where only one's does. `innermostRoot` is buildJsBundle's, for a JS bundle built
@@ -1645,6 +1677,7 @@ export function checkVfsOptions(name, options) {
1645
1677
  // -> { bundle: Bundle, lockfile: Lockfile (of a JS bundle), stats, packageManager, root }
1646
1678
  export async function buildVfsBundle({ vfs, packageManager, cwd = '/', packageManagerVersion, os, cpu, libc, repo, innermostRoot = false, generate = [], client, cache, ...options } = {}) {
1647
1679
  const { checkCache, checkKind, checkTarget, checkVfs, loadTree, packageManagerFor, packageManagerOf, pinCommits, treeHost, vfsHost } = await import('../vfs-bundle/tree.js')
1680
+ const { configuredBuilds } = await import('./bundle-options.js')
1648
1681
  checkVfs('buildVfsBundle', vfs)
1649
1682
  checkTarget('buildVfsBundle', { os, cpu, libc })
1650
1683
  checkCache('buildVfsBundle', cache)
@@ -1655,10 +1688,15 @@ export async function buildVfsBundle({ vfs, packageManager, cwd = '/', packageMa
1655
1688
  cwd = project.realpath(posix.resolve('/', cwd))
1656
1689
  packageManager = packageManagerFor('buildVfsBundle', project, cwd, { packageManager, packageManagerVersion, os })
1657
1690
  const pm = packageManagerOf('buildVfsBundle', packageManager)
1658
- checkKind('buildVfsBundle', checkVfsOptions('buildVfsBundle', { ...options, generate, cwd, host: project }), [packageManager])
1691
+ // The entries stasis.config.json's `entries` names, every one where none are given, each built
1692
+ // with its options there, which the options given agree with (configuredBuilds); else built with
1693
+ // the options given. Each build is checked with the options it is built with.
1694
+ const builds = configuredBuilds('buildVfsBundle', { cwd, host: project, entries: options.entries, options })?.builds ?? [options]
1695
+ if (builds.length === 0) throw new Error(`buildVfsBundle: no entries given, and ${CONFIG_FILE}'s entries name none`)
1696
+ for (const build of builds) checkKind('buildVfsBundle', checkVfsOptions('buildVfsBundle', { ...build, lockfile: options.lockfile, generate, cwd, host: project }), [packageManager])
1659
1697
  // Checked before anything is fetched: an entry out of what the tree installs is in the project
1660
1698
  // already. (A Solidity entry that is no .sol file is a directory, skipped where it is missing.)
1661
- for (const entry of options.entries) {
1699
+ for (const entry of builds.flatMap((build) => build.entries)) {
1662
1700
  const abs = posix.resolve(cwd, entry)
1663
1701
  if (pm.kind === 'sol' && !abs.endsWith('.sol')) continue
1664
1702
  if (!posix.relative(cwd, abs).split('/').includes(pm.installs) && project.stat(abs) === null) throw new Error(`entry not found: ${abs}`)
@@ -1670,11 +1708,23 @@ export async function buildVfsBundle({ vfs, packageManager, cwd = '/', packageMa
1670
1708
  const outputs = await generatePrismaClients({ host, root: tree.root, projects: tree.projects })
1671
1709
  if (outputs.length > 0) host = treeHost(tree, vfsHost(withPrismaClients(vfs, outputs)))
1672
1710
  }
1673
- const args = { ...options, cwd, host, env: {} }
1674
- const { bundle, lockfile, stateBuilt, root } = pm.kind === 'sol' ? { bundle: await buildSolidityBundle(args), root: cwd } : await buildJs({ ...args, innermostRoot })
1711
+ const args = { cwd, host, env: {} }
1712
+ const builts = []
1713
+ for (const build of builds) {
1714
+ // eslint-disable-next-line no-await-in-loop -- one build at a time, in the order its warnings read
1715
+ const built = pm.kind === 'sol' ? { bundle: await buildSolidityBundle({ ...build, ...args }), root: cwd } : await buildJs({ ...build, ...args, innermostRoot })
1716
+ // Rooted at cwd, where `stasis bundle` detects its repo.
1717
+ if (repo === undefined && !built.stateBuilt) built.bundle.repo ??= detectRepo(cwd, host)
1718
+ builts.push(built)
1719
+ }
1720
+ // Merged as bundleCommand merges its builds: rooted where every one of them is.
1721
+ const { root } = builts[0]
1722
+ const other = builts.findIndex((built) => built.root !== root)
1723
+ if (other !== -1) {
1724
+ throw new Error(`buildVfsBundle: ${builds[0].entries[0]} and ${builds[other].entries[0]} can't be bundled together: their bundles' paths are relative to different roots (${root} and ${builts[other].root})`)
1725
+ }
1726
+ const { bundle, lockfile } = builts.reduce((a, b) => ({ bundle: a.bundle.merge(b.bundle), lockfile: a.lockfile && (() => a.lockfile().merge(b.lockfile())) }))
1675
1727
  if (repo !== undefined) bundle.repo = repo
1676
- // Rooted at cwd, where `stasis bundle` detects its repo.
1677
- else if (!stateBuilt) bundle.repo ??= detectRepo(cwd, host)
1678
1728
  pinCommits(bundle, root, tree)
1679
1729
  return { bundle, lockfile: lockfile?.(), stats: tree.stats, packageManager, root }
1680
1730
  }
package/src/scan.js CHANGED
@@ -35,20 +35,12 @@ export function getParser() {
35
35
  return _parser
36
36
  }
37
37
 
38
- // flow-remove-types is an optional dependency, loaded lazily and only under --flow: it strips
39
- // Flow type syntax down to plain JS before oxc (which parses JS/TS, not Flow) sees it. A missing
40
- // dep is an env error, so surface it with an actionable install hint rather than a bare resolve throw.
38
+ // flow-remove-types is stasis's own dependency, resolved from stasis itself (never from the project
39
+ // being bundled) and loaded lazily, only under --flow: it strips Flow type syntax down to plain JS
40
+ // before oxc (which parses JS/TS, not Flow) sees it.
41
41
  let _flowRemoveTypes
42
42
  function getFlowRemoveTypes() {
43
- if (_flowRemoveTypes) return _flowRemoveTypes
44
- try {
45
- _flowRemoveTypes = createRequire(import.meta.url)('flow-remove-types')
46
- } catch (cause) {
47
- throw new Error(
48
- "--flow needs the optional 'flow-remove-types' dependency; install it (e.g. `npm i flow-remove-types`)",
49
- { cause }
50
- )
51
- }
43
+ _flowRemoveTypes ??= createRequire(import.meta.url)('flow-remove-types')
52
44
  return _flowRemoveTypes
53
45
  }
54
46
 
@@ -302,10 +294,10 @@ export class Scan {
302
294
  return hit == null ? null : pathToFileURL(hit).toString()
303
295
  }
304
296
 
305
- // Strip Flow type syntax to plain JS via the optional flow-remove-types dep (resolved lazily; a
306
- // missing dep is an env error and propagates). Only invoked as a parse fallback (see #scanFile),
307
- // so plain-JS files never reach it. Returns the rewritten source, or null when the transform
308
- // itself fails on this file -- the caller then keeps oxc's original parse error.
297
+ // Strip Flow type syntax to plain JS via stasis's flow-remove-types (loaded lazily). Only invoked
298
+ // as a parse fallback (see #scanFile), so plain-JS files never reach it. Returns the rewritten
299
+ // source, or null when the transform itself fails on this file -- the caller then keeps oxc's
300
+ // original parse error.
309
301
  #stripFlow(src, file) {
310
302
  const flowRemoveTypes = getFlowRemoveTypes()
311
303
  try {
@@ -5,6 +5,7 @@ import { readJson } from '@exodus/stasis-core/bundle-util'
5
5
  import { isAutoExcludedDir, isPlainObject, posixPathEscapes, relativeEscapes } from '@exodus/stasis-core/util'
6
6
  import { Vfs } from '@preventive/vfs'
7
7
  import { checkVfsOptions, fieldResolverFor } from '../cmd/bundle.js'
8
+ import { configuredBuilds } from '../cmd/bundle-options.js'
8
9
  import { foundrySourceDir } from '../loaders/foundry.js'
9
10
  import { resolveConditions } from '../resolve-fields.js'
10
11
  import { resolveTypescriptFallback, typescriptExportsTarget } from '../resolve-typescript.js'
@@ -124,15 +125,32 @@ export const KINDS = {
124
125
 
125
126
  const EMPTY = vfsHost(new Vfs())
126
127
 
128
+ // What a stasis.config.json's empty `entries` says of the directory holding it.
129
+ const CONFIGURED_NONE = 'has a stasis.config.json whose entries name none'
130
+
131
+ // -> { entries, none }: the entries a build of the project in `dir` (read through `host`) takes
132
+ // where none are given, as paths from `dir`, and what having none says of `dir`. Those its
133
+ // stasis.config.json's `entries` names, checked with `options` as the build checks them
134
+ // (configuredBuilds), where it has `entries`, whatever it names; else those of `kind` (KINDS'),
135
+ // with `options` then checked on their own, as the build checks them, which nothing completes.
136
+ export function defaultEntries(name, host, dir, kind, options) {
137
+ const configured = configuredBuilds(name, { cwd: dir, host, options })
138
+ if (configured !== null) return { entries: configured.entries, none: CONFIGURED_NONE }
139
+ checkVfsOptions(name, { ...options, entries: [kind.standIn], cwd: '/', host: EMPTY, fetched: false })
140
+ return { entries: kind.entries(host, dir, options), none: kind.none }
141
+ }
142
+
127
143
  // The build's checks of `options` before anything is fetched, over an empty tree, which never
128
144
  // decides them: for the package manager given, else for any; over the entries given, else over one
129
- // of the kind the default ones are. -> the PACKAGE_MANAGERS entry of the one given
145
+ // of the kind the default ones are. But for what one of them needs of another, which the options of
146
+ // an entry stasis.config.json names may set (`partial`), left to the build, which knows whether it
147
+ // names it. -> the PACKAGE_MANAGERS entry of the one given
130
148
  export function checkAhead(name, packageManager, options) {
131
149
  checkVersion(name, { packageManager, ...options })
132
150
  const pm = packageManager === undefined ? undefined : packageManagerOf(name, packageManager)
133
151
  const refusal = (entries) => {
134
152
  try {
135
- checkKind(name, checkVfsOptions(name, { ...options, entries, cwd: '/', host: EMPTY, fetched: false }), packageManager === undefined ? undefined : [packageManager])
153
+ checkKind(name, checkVfsOptions(name, { ...options, entries, cwd: '/', host: EMPTY, fetched: false, partial: true }), packageManager === undefined ? undefined : [packageManager])
136
154
  return null
137
155
  } catch (error) {
138
156
  return error
@@ -7,7 +7,7 @@ import { ArchiveError, unpack } from '@preventive/archive/tar.js'
7
7
  import { createClient } from '@preventive/upstream/github.js'
8
8
  import { vfsFromEntries } from '@preventive/vfs'
9
9
  import { buildVfsBundle } from '../cmd/bundle.js'
10
- import { KINDS, checkAhead } from './entries.js'
10
+ import { KINDS, checkAhead, defaultEntries } from './entries.js'
11
11
  import { checkCache, checkTarget, detectPackageManager, installedAlone, lockfileOf, lockfilesListed, noLockfile, packageManagerOf, vfsHost } from './tree.js'
12
12
 
13
13
  // As upstream's tree verification bounds a tarball's unpacked size.
@@ -168,7 +168,8 @@ async function repoTree(name, { github, sha, tag, directory, client, packageMana
168
168
  // A GitHub repo at a full commit, or the one `tag` names, the default branch's head without either,
169
169
  // as buildVfsBundle builds it: `directory` downloaded alone where it stands alone, else the whole
170
170
  // repo, and without a `packageManager`, the one whose lockfile installs it, where only one's does
171
- // (repoTree). Without `entries`, they are the ones suggestedEntries suggests. The bundle's paths are
171
+ // (repoTree). Without `entries`, they are the ones suggestedEntries suggests: those its
172
+ // stasis.config.json's `entries` names, where it has `entries`. The bundle's paths are
172
173
  // relative to `directory`, or for a JS bundle, to the innermost package directory at or above it
173
174
  // holding every file it bundles (buildJsBundle's innermostRoot), which is the project's root where
174
175
  // one is outside the others; `repo` names that directory and the commit. Nothing is read from disk:
@@ -185,8 +186,9 @@ export async function buildGitHubBundle({ github, sha, tag, directory, client, p
185
186
  let { entries } = options
186
187
  if (entries === undefined) {
187
188
  // As suggestedEntries suggests them, from the tree at hand.
188
- entries = tree.kind.entries(tree.host, tree.cwd, options)
189
- if (entries.length === 0) throw new Error(`${tree.where}: no entries given, and ${directory || 'the repo root'} ${tree.kind.none}`)
189
+ const suggested = defaultEntries('buildGitHubBundle', tree.host, tree.cwd, tree.kind, options)
190
+ entries = suggested.entries
191
+ if (entries.length === 0) throw new Error(`${tree.where}: no entries given, and ${directory || 'the repo root'} ${suggested.none}`)
190
192
  }
191
193
  const repo = { github, commit: tree.sha }
192
194
  const built = await buildVfsBundle({ ...options, entries, packageManager: tree.packageManager, vfs: tree.vfs, cwd: tree.cwd, innermostRoot: true, repo, client })
@@ -200,5 +202,5 @@ export async function buildGitHubBundle({ github, sha, tag, directory, client, p
200
202
  // buildGitHubBundle downloads it.
201
203
  export async function suggestedRepoEntries(repo, resolution) {
202
204
  const tree = await repoTree('suggestedEntries', repo, resolution)
203
- return tree.kind.entries(tree.host, tree.cwd, resolution)
205
+ return defaultEntries('suggestedEntries', tree.host, tree.cwd, tree.kind, resolution).entries
204
206
  }
@@ -395,10 +395,10 @@ const githubRoot = (url) => {
395
395
 
396
396
  // Each dependency of `bundle`, its paths from `root`, at the commit the tree (layOutTree's) installs
397
397
  // it from, where deptree names a full one: an npm package at its gitHead, which the registry's
398
- // version document names, a commit of the repository its own package.json names, so taken only
399
- // where the bundle records that one; a Soldeer git dependency at its lockfile's `rev`, the root of
400
- // the repository it is fetched from, where that is a GitHub one. Metadata, as `repo` is: the
401
- // publisher's word, held to no repository.
398
+ // version document names, over the one its package.json may name (packageRepo), a commit of the
399
+ // repository its own package.json names, so taken only where the bundle records that one; a
400
+ // Soldeer git dependency at its lockfile's `rev`, the root of the repository it is fetched from,
401
+ // where that is a GitHub one. Metadata, as `repo` is: the publisher's word, held to no repository.
402
402
  export function pinCommits(bundle, root, { root: from, installed }) {
403
403
  const byDir = new Map(installed.map((pkg) => [posix.relative(root, posix.join(from, pkg.path)), pkg]))
404
404
  for (const [dir, info] of bundle.modules) {
package/src/vfs-bundle.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { posix } from 'node:path'
2
2
 
3
3
  import { Vfs } from '@preventive/vfs'
4
- import { KINDS, checkAhead } from './vfs-bundle/entries.js'
4
+ import { KINDS, checkAhead, defaultEntries } from './vfs-bundle/entries.js'
5
5
  import { suggestedRepoEntries } from './vfs-bundle/github.js'
6
6
  import { NODE_MODULES_MANAGERS, checkCache, checkTarget, checkVfs, detectPackageManager, loadTree, packageManagerFor, vfsHost } from './vfs-bundle/tree.js'
7
7
 
@@ -58,14 +58,15 @@ export async function loadNodeModules({ vfs, packageManager, cwd = '/', packageM
58
58
  }
59
59
 
60
60
  // -> the entries buildGitHubBundle takes where none are given, as paths from the project's
61
- // directory, of the kind its package manager builds: `packageManager` if given, else the one
62
- // detected as the build detects it. For pnpm and yarn 1, the entry points its package.json names,
63
- // resolved as the build resolves them with the same `conditions`, `mainFields`, `metro`,
64
- // `platforms` and `typescript` (packageEntries); for Soldeer, its .sol entry points by name
65
- // and layout (solidityEntries). The options are checked as the build checks them, and `os`, the
66
- // one the build is for, detects the package manager as there. Of the project held in `vfs`, from
67
- // `cwd`; or of a GitHub repo, `{ github, sha, tag, directory, client }` as buildGitHubBundle takes
68
- // them, downloaded as it downloads them.
61
+ // directory: those its stasis.config.json's `entries` names, where it has `entries` (none of an
62
+ // empty one), checked with the options as the build checks them; else of the kind its package
63
+ // manager builds: `packageManager` if given, else the one detected as the build detects it. For
64
+ // pnpm and yarn 1, the entry points its package.json names, resolved as the build resolves them
65
+ // with the same `conditions`, `mainFields`, `metro`, `platforms` and `typescript` (packageEntries);
66
+ // for Soldeer, its .sol entry points by name and layout (solidityEntries). The options are checked
67
+ // as the build checks them, and `os`, the one the build is for, detects the package manager as
68
+ // there. Of the project held in `vfs`, from `cwd`; or of a GitHub repo, `{ github, sha, tag,
69
+ // directory, client }` as buildGitHubBundle takes them, downloaded as it downloads them.
69
70
  export async function suggestedEntries({ vfs, cwd = '/', packageManager, conditions, mainFields, metro, platforms, jsx, typescript, os, ...repo } = {}) {
70
71
  checkTarget('suggestedEntries', { os })
71
72
  const resolution = { conditions, mainFields, metro, platforms, jsx, typescript }
@@ -76,5 +77,5 @@ export async function suggestedEntries({ vfs, cwd = '/', packageManager, conditi
76
77
  const host = vfsHost(vfs)
77
78
  const at = posix.resolve('/', cwd)
78
79
  const pm = checkAhead('suggestedEntries', packageManager ?? detectPackageManager('suggestedEntries', host, at, { os }), resolution)
79
- return KINDS[pm.kind].entries(host, at, resolution)
80
+ return defaultEntries('suggestedEntries', host, at, KINDS[pm.kind], resolution).entries
80
81
  }