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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cmd/bundle.js CHANGED
@@ -6,15 +6,19 @@ import { brotliDecompressSync } from 'node:zlib'
6
6
 
7
7
  import { Bundle, isValidRepoField } from '@exodus/stasis-core/bundle'
8
8
  import { Lockfile } from '@exodus/stasis-core/lockfile'
9
+ import { extraArtifacts } from '@exodus/stasis-core/add'
9
10
  import { importsTypescriptByOutputName, scan } from '../scan.js'
11
+ import { parseDefine } from '../define.js'
10
12
  import { createFieldResolver, resolveConditions } from '../resolve-fields.js'
11
13
  import { discoverTsconfig, isDir, loadTsconfigPaths, packageTsconfigPaths } from '../resolve-typescript.js'
12
14
  import { createMetroResolver } from '../metro-resolver.js'
15
+ import { createAliases, createBabelAliases } from '../babel.js'
16
+ import { linkedNativePackages, looksNative, nativeInputs } from '@exodus/stasis-plugins/metro-native'
13
17
  import { pinInstalledCommits } from '../installed-commits.js'
14
18
  import { State } from '@exodus/stasis-core/state'
15
- import { sha512integrity } from '@exodus/stasis-core/state-util'
19
+ import { readFileSyncMaybe, sha512integrity } from '@exodus/stasis-core/state-util'
16
20
  import { checkoutCommit, detectRepo, findPackageMetadata, normalizeEntries, packageType, parseGithubRepository, readJson, readModuleManifest, readPackageJson, readRegularFileOrNull } from '@exodus/stasis-core/bundle-util'
17
- import { EMPTY_MODULE_PATH, RN_CORE_INCLUDE_FILES, assertRealPathWithinBase, classifyNativeCapture, hasNodeModulesSegment, isDotEnvFile, isExcludedNativeDir, isExecutableFile, isNativeArtifact, isNativeManifest, isPathWithin, isPodspec, isSkippedNativeWalkDir, moduleFileKey, moduleInfo, parseResourcesOption, posixPathEscapes, refineNativeCapture, relativeEscapes, splitNodeModulesPath, toPosix, withMetadataOf } from '@exodus/stasis-core/util'
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'
18
22
  import { diskHost } from '@exodus/stasis-core/host'
19
23
  import { parseSoldeerLockfile } from '@preventive/lockfile/soldeer.js'
20
24
  import {
@@ -264,10 +268,11 @@ function assertSelfContained(lang, noun, entries, sources, missing) {
264
268
  // (packageLookup by default, which walks past a malformed one). `classifyDep(path)` optionally
265
269
  // places a file directly (non-node_modules ecosystems like Soldeer/github); null defers. `format` tags
266
270
  // every file; `formats` (Map<path,format>) overrides it per file. `resolutions` values are
267
- // a flat target string or a Map<platform,target>; both round-trip untouched.
271
+ // a flat target string or a Map<platform,target>; both round-trip untouched. `consumer` is
272
+ // codeBundle's.
268
273
  function assembleCodeBundle({
269
274
  baseDir, entries, sources, resolutions, workspaceName, workspaceVersion, format, formats, conditionKey, classifyDep, host,
270
- packageOf = packageLookup(baseDir, { host }),
275
+ packageOf = packageLookup(baseDir, { host }), consumer,
271
276
  }) {
272
277
  const modules = new Map()
273
278
  // `identity`'s name, version, ecosystem, repo and vendored (moduleInfo takes those alone); a later
@@ -297,14 +302,19 @@ function assembleCodeBundle({
297
302
  }
298
303
  }
299
304
 
300
- return codeBundle({ baseDir, entries, sources, modules, resolutions, format, formats, conditionKey, host })
305
+ return codeBundle({ baseDir, entries, sources, modules, resolutions, format, formats, conditionKey, host, consumer })
301
306
  }
302
307
 
303
308
  // A full-scope code Bundle of `sources`, bucketed as `modules`: `format` tags every file, `formats`
304
- // (Map<path,format>) overrides it per file, and the `resolutions` edges are keyed under `conditionKey`.
305
- function codeBundle({ baseDir, entries, sources, modules, resolutions, format, formats, conditionKey, host }) {
309
+ // (Map<path,format>) overrides it per file (a file neither tags has none), and the `resolutions` edges
310
+ // are keyed under `conditionKey`. Every file is attributed to `consumer` in the `reason` map: `bundle`,
311
+ // or `bundle:metro` for --metro.
312
+ function codeBundle({ baseDir, entries, sources, modules, resolutions, format, formats, conditionKey, host, consumer = 'bundle' }) {
306
313
  const formatsMap = new Map()
307
- for (const path of sources.keys()) formatsMap.set(path, formats?.get(path) ?? format)
314
+ for (const path of sources.keys()) {
315
+ const fileFormat = formats?.get(path) ?? format
316
+ if (fileFormat !== undefined) formatsMap.set(path, fileFormat)
317
+ }
308
318
 
309
319
  const importsForKey = new Map()
310
320
  for (const [parent, specMap] of resolutions) importsForKey.set(parent, specMap)
@@ -314,7 +324,7 @@ function codeBundle({ baseDir, entries, sources, modules, resolutions, format, f
314
324
  // executable). Shell bundles lean on this most: `stasis extract` puts the +x back on the scripts.
315
325
  const executable = executableSources(baseDir, sources, host)
316
326
 
317
- // Attribute files to the `bundle` consumer (static builders skip State's per-file tagging).
327
+ // Attribute files to the static build's consumer (static builders skip State's per-file tagging).
318
328
  return new Bundle({
319
329
  config: { scope: 'full' },
320
330
  entries: new Set(entries),
@@ -322,7 +332,7 @@ function codeBundle({ baseDir, entries, sources, modules, resolutions, format, f
322
332
  formats: formatsMap,
323
333
  imports,
324
334
  executable,
325
- }).withReason('bundle')
335
+ }).withReason(consumer)
326
336
  }
327
337
 
328
338
  // Files never carried, whatever reads them: `.env` files, and Hardhat's config, which is code
@@ -666,25 +676,89 @@ function describeUnresolved(u, show) {
666
676
  return `${u.kind} ${u.spec ?? '<dynamic>'} from ${show(u.parentURL)} (${u.reason}${typescript})`
667
677
  }
668
678
 
669
- // Classify scanner unresolved edges + parse errors into fatal (broken/divergent at load)
670
- // vs tolerated (a catchable runtime miss). Shared so the plain and --mainFields JS paths
671
- // gate identically. `baseDir` relativizes the paths in the emitted messages (see displayPath).
672
- function analyzeScanner(scanner, { baseDir }) {
673
- const show = (url) => displayPath(url, baseDir)
674
- // Static ESM import/export-from edges load eagerly before user code, so a failure there is
675
- // uncatchable (fatal); misses below a require()/dynamic-import() boundary are catchable (warn).
676
- const staticKinds = new Set(['import', 'export-from'])
677
- const staticReachable = new Set(scanner.entries)
679
+ // Static ESM import/export-from edges load eagerly before user code, so a failure there is
680
+ // uncatchable; one below a require()/dynamic-import() boundary is catchable.
681
+ const STATIC_KINDS = new Set(['import', 'export-from'])
682
+
683
+ // The files the entries link eagerly, through static edges alone.
684
+ function eagerlyLinked(scanner) {
685
+ const linked = new Set(scanner.entries)
678
686
  const walk = [...scanner.entries]
679
687
  while (walk.length > 0) {
680
688
  for (const e of scanner.files.get(walk.shift())?.edges ?? []) {
681
- if (staticKinds.has(e.kind) && e.child && !staticReachable.has(e.child)) {
682
- staticReachable.add(e.child)
689
+ if (STATIC_KINDS.has(e.kind) && e.child && !linked.has(e.child)) {
690
+ linked.add(e.child)
691
+ walk.push(e.child)
692
+ }
693
+ }
694
+ }
695
+ return linked
696
+ }
697
+
698
+ // The scan within the project root (`within(url)`), since a bundle can't carry a file outside it.
699
+ // One the entries link eagerly is returned in `outside`, for the caller to refuse. One reached
700
+ // only past a require()/import() boundary is left out, with whatever only it reaches, and its edges
701
+ // are returned in `leftOut`, misses that load can catch as it does an unresolved one: an optional
702
+ // peer dependency's lazy require() reaching a copy hoisted above a root that a stasis file pins, say.
703
+ function withinRoot(scanner, within) {
704
+ const outside = [...eagerlyLinked(scanner)].filter((url) => scanner.files.has(url) && !within(url))
705
+ if (outside.length > 0) return { scanner, outside, leftOut: [] }
706
+ const kept = new Set([...scanner.entries].filter((url) => scanner.files.has(url)))
707
+ const walk = [...kept]
708
+ while (walk.length > 0) {
709
+ for (const e of scanner.files.get(walk.shift())?.edges ?? []) {
710
+ if (e.child && scanner.files.has(e.child) && !kept.has(e.child) && within(e.child)) {
711
+ kept.add(e.child)
683
712
  walk.push(e.child)
684
713
  }
685
714
  }
686
715
  }
687
- const fatalUnresolved = (u) => staticKinds.has(u.kind) && staticReachable.has(u.parentURL)
716
+ if (kept.size === scanner.files.size) return { scanner, outside, leftOut: [] }
717
+ const leftOut = []
718
+ const files = new Map()
719
+ for (const url of kept) {
720
+ const info = scanner.files.get(url)
721
+ const edges = info.edges.map((e) => {
722
+ if (!e.child || within(e.child)) return e
723
+ const { child, ...rest } = e
724
+ leftOut.push({ parentURL: url, kind: e.kind, spec: e.spec, outsideURL: child })
725
+ return { ...rest, error: 'outside the project root' }
726
+ })
727
+ files.set(url, { ...info, edges })
728
+ }
729
+ const imports = new Map()
730
+ for (const [key, byParent] of scanner.imports) {
731
+ const parents = new Map()
732
+ for (const [parentURL, specMap] of byParent) {
733
+ if (!files.has(parentURL)) continue
734
+ const specs = new Map([...specMap].filter(([, childURL]) => within(childURL)))
735
+ if (specs.size > 0) parents.set(parentURL, specs)
736
+ }
737
+ if (parents.size > 0) imports.set(key, parents)
738
+ }
739
+ const unresolved = scanner.unresolved.filter((u) => files.has(u.parentURL))
740
+ const parseErrors = scanner.parseErrors.filter((p) => files.has(p.url))
741
+ return { scanner: { entries: scanner.entries, files, imports, unresolved, parseErrors }, outside, leftOut }
742
+ }
743
+
744
+ // Refuse an edge one --metro platform resolves within the root and another leaves out (see
745
+ // withinRoot): collapsed to the one target, it would serve that platform the other's file.
746
+ function refuseSplit(split, baseDir) {
747
+ for (const { parentURL, spec, outsideURL } of split) {
748
+ throw new Error(
749
+ `${spec} from ${displayPath(parentURL, baseDir)} resolves within the project root in one context and outside it, ` +
750
+ `at ${relative(baseDir, fileURLToPath(outsideURL))}, in another: a bundle can't leave out the one without serving the other in its place`
751
+ )
752
+ }
753
+ }
754
+
755
+ // Classify scanner unresolved edges + parse errors into fatal (broken/divergent at load)
756
+ // vs tolerated (a catchable runtime miss). Shared so the plain and --mainFields JS paths
757
+ // gate identically. `baseDir` relativizes the paths in the emitted messages (see displayPath).
758
+ function analyzeScanner(scanner, { baseDir }) {
759
+ const show = (url) => displayPath(url, baseDir)
760
+ const staticReachable = eagerlyLinked(scanner)
761
+ const fatalUnresolved = (u) => STATIC_KINDS.has(u.kind) && staticReachable.has(u.parentURL)
688
762
  const fatal = scanner.unresolved
689
763
  .filter((u) => fatalUnresolved(u))
690
764
  .map((u) => `unresolved ${describeUnresolved(u, show)}`)
@@ -711,7 +785,7 @@ function analyzeScanner(scanner, { baseDir }) {
711
785
 
712
786
  // Throw on fatal scan issues; warn on tolerated ones. `label` tags the scan pass; `baseDir`
713
787
  // relativizes the paths in the warnings (see displayPath), matching analyzeScanner's messages.
714
- function reportScanIssues({ fatal, tolerated, toleratedParse }, { label = '', baseDir }) {
788
+ function reportScanIssues({ fatal, tolerated, toleratedParse, leftOut = [] }, { label = '', baseDir, root = '' }) {
715
789
  const where = label ? ` (${label})` : ''
716
790
  const show = (url) => displayPath(url, baseDir)
717
791
  // The first 10 of `items` as indented lines (`line` renders one), then how many more there are.
@@ -730,6 +804,11 @@ function reportScanIssues({ fatal, tolerated, toleratedParse }, { label = '', ba
730
804
  const summary = listed(toleratedParse, (p) => `${show(p.url)}: ${p.message}`)
731
805
  console.warn(`[stasis] Bundle has ${toleratedParse.length} file(s) with parse errors${where}; their recorded imports may be incomplete:\n${summary}`)
732
806
  }
807
+ if (leftOut.length > 0) {
808
+ // The file outside the root by its path from the cwd, as the refusal of one linked eagerly names it.
809
+ const summary = listed(leftOut, (u) => `${u.kind} ${u.spec} from ${show(u.parentURL)} (at ${relative(baseDir, fileURLToPath(u.outsideURL))})`)
810
+ console.warn(`[stasis] Bundle leaves out ${leftOut.length} import(s) of files outside the project root${root}${where}; they will fall through at load time:\n${summary}`)
811
+ }
733
812
  }
734
813
 
735
814
  // Normalize conditions (trim, drop empties) so a sloppy programmatic caller can't push a bogus
@@ -754,11 +833,16 @@ function typescriptPathsFor(typescript, baseDir, tsconfig, host, env) {
754
833
  // resolution to its on-disk TS source (tsc's rules; see resolve-typescript.js), honouring the
755
834
  // `paths` aliases of `tsconfig` (an explicit config path, default each package's tsconfig.json); it
756
835
  // is taken as given where the entries import TS sources by output name (importsTypescriptByOutputName).
836
+ // `define` gives globals their values, a branch they keep from running reaching nothing (define.js).
757
837
  // Files are read through `host` (@exodus/stasis-core/host), the disk by default; EXODUS_STASIS_*
758
838
  // settings from `env`. With `innermostRoot`, the State is rooted at the innermost package at or
759
839
  // above cwd that holds every file the scan reaches (innermostRootOf), rather than at the project's
760
- // root above it, where that holds no stasis file of its own.
761
- export async function buildJsBundle({ cwd = process.cwd(), env = process.env, entries, scope, conditions = [], jsx = false, flow = false, typescript = false, tsconfig, resources = [], packageJSON = false, host = diskHost, innermostRoot = false } = {}) {
840
+ // root above it, where that holds no stasis file of its own. With `extra`, the files its
841
+ // stasis.config.json's `extra` names are added as `stasis run` adds them (State#includeExtra), never
842
+ // one of `outputsAt(root)` (the absolute paths the build writes, given the root its paths are
843
+ // relative to), resources by `resources` where given, else by the config's; from disk alone, as
844
+ // Node's glob reads it.
845
+ export async function buildJsBundle({ cwd = process.cwd(), env = process.env, entries, scope, conditions = [], jsx = false, flow = false, typescript = false, tsconfig, resources, define, packageJSON = false, host = diskHost, innermostRoot = false, extra = false, outputsAt = () => [] } = {}) {
762
846
  if (!Array.isArray(entries) || entries.length === 0) {
763
847
  throw new Error('buildJsBundle: at least one entry .js/.cjs/.mjs/.ts/.cts/.mts/.jsx/.tsx file is required')
764
848
  }
@@ -776,10 +860,7 @@ export async function buildJsBundle({ cwd = process.cwd(), env = process.env, en
776
860
  typescript ||= importsTypescriptByOutputName(absEntries, host)
777
861
  const typescriptPaths = typescriptPathsFor(typescript, baseDir, tsconfig, host, env)
778
862
 
779
- const scanner = scan(absEntries, { conditions: scanConditions, jsx, flow, typescript, typescriptPaths, resources: resourceSet, host })
780
-
781
- // Fail closed where the bundle is guaranteed broken at load; warn on catchable misses (see analyzeScanner).
782
- reportScanIssues(analyzeScanner(scanner, { baseDir }), { baseDir })
863
+ const scanned = scan(absEntries, { conditions: scanConditions, jsx, flow, typescript, typescriptPaths, resources: resourceSet, define, host })
783
864
 
784
865
  // Materialise via a non-preload State: addFile bucketizes + records sources/formats,
785
866
  // addImport replays the edge map; serialize emits the runtime loader's v1 layout.
@@ -790,33 +871,41 @@ export async function buildJsBundle({ cwd = process.cwd(), env = process.env, en
790
871
  let state = new State(baseDir, { ...stateOptions, env })
791
872
  // A root holding a stasis file is the project's own choice, whose config the build takes.
792
873
  if (innermostRoot && !STASIS_ROOT_FILES.some((file) => host.stat(join(state.root, file)) !== null)) {
793
- const root = innermostRootOf(baseDir, [...scanner.files.keys()].map((url) => host.realpath(fileURLToPath(url))), state.root, host)
874
+ const root = innermostRootOf(baseDir, [...scanned.files.keys()].map((url) => host.realpath(fileURLToPath(url))), state.root, host)
794
875
  // The State's walk up from cwd stops at PROJECT_CWD, as it does where yarn sets it.
795
876
  if (root !== state.root) state = new State(baseDir, { ...stateOptions, env: { ...env, PROJECT_CWD: root } })
796
877
  }
797
- // Named here rather than as the State's bare assertion: a stasis file in a directory below the
798
- // project's root (a stray stasis.code.br there, say) roots the State at it, out of the files above.
799
- for (const url of scanner.files.keys()) {
800
- const file = fileURLToPath(url)
801
- if (!relativeEscapes(relative(state.root, file))) continue
802
- const markers = STASIS_ROOT_FILES.filter((name) => host.stat(join(state.root, name)) !== null)
803
- const rootedBy = markers.length === 0 ? '' : ` (rooted there by its ${markers.join(' and ')}, which can be removed if stale)`
804
- throw new Error(`buildJsBundle: ${relative(baseDir, file)} is outside the project root at ${relative(baseDir, state.root) || '.'}${rootedBy}`)
878
+ // Only what lies within the root is carried (see withinRoot). One the entries link eagerly is
879
+ // refused, named here rather than as the State's bare assertion: a stasis file in a directory below
880
+ // the project's root (a stray stasis.code.br there, say) roots the State at it, out of the files above.
881
+ const { scanner, outside, leftOut } = withinRoot(scanned, (url) => !relativeEscapes(relative(state.root, fileURLToPath(url))))
882
+ const markers = STASIS_ROOT_FILES.filter((name) => host.stat(join(state.root, name)) !== null)
883
+ const rootedBy = markers.length === 0 ? '' : ` (rooted there by its ${markers.join(' and ')}, which can be removed if stale)`
884
+ const root = ` at ${relative(baseDir, state.root) || '.'}${rootedBy}`
885
+ for (const url of outside) {
886
+ throw new Error(`buildJsBundle: ${relative(baseDir, fileURLToPath(url))} is outside the project root${root}`)
805
887
  }
888
+ // Fail closed where the bundle is guaranteed broken at load; warn on catchable misses (see analyzeScanner).
889
+ reportScanIssues({ ...analyzeScanner(scanner, { baseDir }), leftOut }, { baseDir, root })
806
890
  for (const [url, info] of scanner.files) {
807
891
  // A resource carries bytes only: addFile derives resource vs resource:base64 from the content
808
892
  // and stores it under `resources` (a resource can't be an entry, so no isEntry).
893
+ // Recorded as the `bundle` consumer's, which `extra` files are not.
809
894
  if (info.resource) {
810
- state.addFile(url, { resource: true })
895
+ state.addFile(url, { resource: true, reason: 'bundle' })
811
896
  continue
812
897
  }
813
898
  const isEntry = scanner.entries.has(url)
814
- state.addFile(url, { format: info.format, isEntry })
899
+ state.addFile(url, { format: info.format, isEntry, reason: 'bundle' })
815
900
  }
816
901
  // Edges where every context agrees keep the wildcard '*' key (getImport's fallback when a
817
902
  // condition lookup misses). Where the require()- and import()-context resolutions of one
818
903
  // (parent, specifier) DIVERGE, each target keeps its real condition key -- one '*' entry
819
904
  // would serve one context the other's file; an unmatched set fails closed via resolveBundled.
905
+ // So does one that a context resolves and another misses or leaves out (an `exports` map with
906
+ // a `require` branch alone, say): getImport serves no context the other's key where conditions
907
+ // decide the resolution, so the miss stays one, as under Node.
908
+ const missed = new Set([...scanner.unresolved, ...leftOut].filter((u) => u.spec !== undefined).map((u) => `${u.parentURL}\0${u.spec}`))
820
909
  const byParent = new Map()
821
910
  for (const [key, parents] of scanner.imports) {
822
911
  for (const [parentURL, specs] of parents) {
@@ -831,7 +920,7 @@ export async function buildJsBundle({ cwd = process.cwd(), env = process.env, en
831
920
  for (const [parentURL, bySpec] of byParent) {
832
921
  for (const [spec, byKey] of bySpec) {
833
922
  const targets = new Set(byKey.values())
834
- if (targets.size === 1) {
923
+ if (targets.size === 1 && !missed.has(`${parentURL}\0${spec}`)) {
835
924
  state.addImport(parentURL, spec, [...targets][0], { conditions: '*' })
836
925
  } else {
837
926
  for (const [key, childURL] of byKey) {
@@ -840,9 +929,12 @@ export async function buildJsBundle({ cwd = process.cwd(), env = process.env, en
840
929
  }
841
930
  }
842
931
  }
843
- // --package-json: fold each bundled module's package.json into the State's buckets (idempotent --
844
- // no-ops any manifest the scan already reached). State's bundle=replace makes writeBundle true, so addFile accepts them.
845
- if (packageJSON) state.includePackageJson()
932
+ // Its own targets are none of the State's: it writes nothing.
933
+ if (extra) state.includeExtra({ outputs: outputsAt(state.root), resources: resources === undefined ? undefined : resourceSet })
934
+ // --package-json, or the `packageJSON` of the stasis.config.json the State took, as `stasis run` takes
935
+ // it: fold each bundled module's package.json into the State's buckets (idempotent -- no-ops any
936
+ // manifest the scan already reached). State's bundle=replace makes writeBundle true, so addFile accepts them.
937
+ if (packageJSON || state.config.packageJSON) state.includePackageJson()
846
938
  return state
847
939
  }
848
940
 
@@ -874,47 +966,6 @@ const METRO_MAIN_FIELDS = ['react-native', 'browser', 'main']
874
966
  // own; webpack keeps it, as `--conditions` adds to it here.) Node and Metro never assert it.
875
967
  const BUNDLER_CONDITIONS = ['module']
876
968
 
877
- // Recursively collect the files under `dirAbs` whose name `keep` takes, skipping build output,
878
- // symlinks (cycle/escape hazard) and, directly in `dirAbs`, the dirs `skipAtRoot` names. Absolute
879
- // paths into `out`.
880
- function walkNative(dirAbs, out, host, keep, skipAtRoot) {
881
- let entries
882
- try {
883
- entries = host.readdir(dirAbs)
884
- } catch {
885
- return // absent -- nothing for this platform
886
- }
887
- for (const ent of entries) {
888
- if (ent.isSymbolicLink()) continue
889
- const full = join(dirAbs, ent.name)
890
- if (ent.isDirectory()) {
891
- if (!isSkippedNativeWalkDir(ent.name) && !skipAtRoot?.(ent.name)) walkNative(full, out, host, keep)
892
- } else if (ent.isFile() && keep(ent.name)) {
893
- out.push(full)
894
- }
895
- }
896
- }
897
-
898
- // The files of a native ios/android dir: all but build artifacts.
899
- const isNativeSource = (name) => !isNativeArtifact(name)
900
-
901
- // Native source files a bundled RN dep contributes to the app's native build (podspecs +
902
- // ios/android sources). Manifests are kept only when the package is actually native (podspec
903
- // or ios/android dir), else a JS-only dep's package.json would be pulled in. Deduped absolute paths.
904
- function nativeModuleFiles(pkgAbs, host) {
905
- // Podspec-load manifests: RN's own podspecs live in scattered subdirs a root-only scan would miss,
906
- // so recurse fully.
907
- const manifests = []
908
- walkNative(pkgAbs, manifests, host, isNativeManifest, isExcludedNativeDir)
909
- const hasIos = host.stat(join(pkgAbs, 'ios')) !== null
910
- const hasAndroid = host.stat(join(pkgAbs, 'android')) !== null
911
- if (!hasIos && !hasAndroid && !manifests.some((f) => isPodspec(f))) return []
912
- const out = [...manifests]
913
- if (hasIos) walkNative(join(pkgAbs, 'ios'), out, host, isNativeSource)
914
- if (hasAndroid) walkNative(join(pkgAbs, 'android'), out, host, isNativeSource)
915
- return [...new Set(out)]
916
- }
917
-
918
969
  // The built-in field/suffix resolver (resolve-fields.js) the legacy-field build resolves with on
919
970
  // `platform` (null for --mainFields), its `mainFields` (Metro's under --metro), and the conditions
920
971
  // it adds to the bundler base (`import`/`require` + `default`, never Node's `node`; see
@@ -941,10 +992,93 @@ export function fieldResolverFor(platform, { mainFields, metro = false, conditio
941
992
  return { extras, mainFields: fields, resolver }
942
993
  }
943
994
 
995
+ const CONFIG_FILE = 'stasis.config.json'
996
+
997
+ // The stasis.config.json in `cwd`, parsed; null where there is none.
998
+ function readConfigFile(name, cwd, host = diskHost) {
999
+ const text = readFileSyncMaybe(resolve(cwd), CONFIG_FILE, 'utf8', host)
1000
+ try {
1001
+ return text === null ? null : JSON.parse(text)
1002
+ } catch (cause) {
1003
+ throw new Error(`${name}: ${CONFIG_FILE} is not valid JSON`, { cause })
1004
+ }
1005
+ }
1006
+
1007
+ // --babel-aliases: the alias map of the JSON file `file` (a path from `baseDir`, in the project, read through
1008
+ // `host`), babel-plugin-module-resolver's `alias` option as data: each alias to the string it maps to.
1009
+ function readAliasesFile(baseDir, file, host = diskHost) {
1010
+ const rel = relative(baseDir, resolve(baseDir, file))
1011
+ if (relativeEscapes(rel)) throw new Error(`stasis bundle: --babel-aliases must name a file in the project: ${file}`)
1012
+ const text = readFileSyncMaybe(baseDir, toPosix(rel), 'utf8', host)
1013
+ if (text === null) throw new Error(`stasis bundle: --babel-aliases file not found: ${file}`)
1014
+ // A link to a file out of the project is refused too.
1015
+ assertRealPathWithinBase(host.realpath(baseDir), baseDir, toPosix(rel), host)
1016
+ let alias
1017
+ try {
1018
+ alias = JSON.parse(text)
1019
+ } catch (cause) {
1020
+ throw new Error(`stasis bundle: --babel-aliases file ${file} is not valid JSON`, { cause })
1021
+ }
1022
+ if (!isPlainObject(alias) || !Object.values(alias).every((value) => typeof value === 'string')) {
1023
+ throw new Error(`stasis bundle: --babel-aliases file ${file} must be an object mapping each alias to a string`)
1024
+ }
1025
+ for (const key of Object.keys(alias)) {
1026
+ if (!key.startsWith('^') && !key.endsWith('$')) continue
1027
+ try {
1028
+ RegExp(key) // compiled to check it, as createAliases compiles it
1029
+ } catch (cause) {
1030
+ throw new Error(`stasis bundle: --babel-aliases file ${file}: ${JSON.stringify(key)} is not a valid regular expression`, { cause })
1031
+ }
1032
+ }
1033
+ return alias
1034
+ }
1035
+
1036
+ // The `scope`, `resources` and `packageJSON` of a --mainFields/--metro build: as given (an empty
1037
+ // `resources` too, for no allowlist; `packageJSON` true), else as the stasis.config.json in `cwd`
1038
+ // sets them (the directory these bundles' paths are relative to, and where one is written by
1039
+ // default). The field resolver builds a full-scope bundle alone, so a narrower scope, from either,
1040
+ // is refused rather than silently ignored.
1041
+ // -> { resources: Set<string> (parseResourcesOption's), packageJSON: boolean }
1042
+ function fieldBuildOptions(name, { cwd = process.cwd(), scope, resources, packageJSON = false, host = diskHost }) {
1043
+ const resourcesGiven = resources !== undefined
1044
+ const config = scope === undefined || !resourcesGiven || !packageJSON ? readConfigFile(name, cwd, host) : null
1045
+ if (scope !== undefined && scope !== 'full') {
1046
+ throw new Error(`${name}: --scope=${scope} is not supported with --mainFields or --metro (they always build a full-scope bundle)`)
1047
+ }
1048
+ if (scope === undefined && config?.scope !== undefined && config.scope !== 'full') {
1049
+ throw new Error(`${name}: ${CONFIG_FILE} sets scope ${JSON.stringify(config.scope)}, which --mainFields and --metro don't support (they always build a full-scope bundle); pass --scope=full to override it`)
1050
+ }
1051
+ if (config?.packageJSON !== undefined && typeof config.packageJSON !== 'boolean') {
1052
+ throw new Error(`${name}: ${CONFIG_FILE} sets packageJSON ${JSON.stringify(config.packageJSON)}, which must be true or false`)
1053
+ }
1054
+ return {
1055
+ resources: resourcesGiven ? parseResourcesOption(name, resources) : parseResourcesOption(CONFIG_FILE, config?.resources),
1056
+ packageJSON: packageJSON || config?.packageJSON === true,
1057
+ }
1058
+ }
1059
+
1060
+ // Metro's own empty module, which it resolves a disabled import to (its default
1061
+ // resolver.emptyModulePath), where the project installs metro-runtime at its root.
1062
+ const METRO_EMPTY_MODULE = 'node_modules/metro-runtime/src/modules/empty-module.js'
1063
+ // An empty module's source, trimmed: nothing, or a lone "use strict" directive.
1064
+ const EMPTY_MODULE_SOURCE = /^(?:(["'])use strict\1;?)?$/u
1065
+
1066
+ // The real path of METRO_EMPTY_MODULE under `baseDir`, where it is a file in the project that is in
1067
+ // fact empty (EMPTY_MODULE_SOURCE), else null.
1068
+ function metroEmptyModule(baseDir, host) {
1069
+ const abs = join(baseDir, METRO_EMPTY_MODULE)
1070
+ if (!host.stat(abs)?.isFile()) return null
1071
+ const real = host.realpath(abs)
1072
+ if (!isPathWithin(host.realpath(baseDir), real)) return null
1073
+ const buf = host.readFile(real)
1074
+ return isUtf8(buf) && EMPTY_MODULE_SOURCE.test(buf.toString('utf8').trim()) ? real : null
1075
+ }
1076
+
944
1077
  // Build a JS/TS Bundle + companion Lockfile via the legacy-field resolver (`--mainFields`/
945
1078
  // `--metro`). Scanned once per platform; each edge is recorded flat when the platforms that
946
- // have it agree, or as a `{ platform: target }` map where they diverge. Returns { bundle, lockfile }.
947
- async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, entries, mainFields, platforms, conditions = [], metro = false, metroResolver = false, jsx = false, flow = false, typescript = false, tsconfig, resources = [], packageJSON = false, host = diskHost }) {
1079
+ // have it agree, or as a `{ platform: target }` map where they diverge. `scope` and `resources`
1080
+ // are fieldBuildOptions'. Returns { bundle, lockfile }.
1081
+ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, entries, mainFields, platforms, conditions = [], metro = false, metroResolver = false, babel = false, babelAliases: aliasesFile, jsx = false, flow = false, typescript = false, tsconfig, scope, resources, define, packageJSON = false, host = diskHost }) {
948
1082
  const baseDir = resolve(cwd)
949
1083
  const absEntries = entries.map((e) => resolve(baseDir, e))
950
1084
  const normalized = normalizeEntries(entries, cwd)
@@ -954,15 +1088,17 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
954
1088
  // is the root; a file below neither is outside it. (Realpathed only when needed, so a missing cwd
955
1089
  // is still the scan's missing entry.)
956
1090
  let realRoot
957
- const toRel = (abs) => {
1091
+ const relWithin = (abs) => {
958
1092
  let rel = toPosix(relative(baseDir, abs))
959
1093
  if (relativeEscapes(rel)) {
960
1094
  realRoot ??= host.realpath(baseDir)
961
1095
  rel = toPosix(relative(realRoot, abs))
962
1096
  }
963
- if (relativeEscapes(rel)) {
964
- throw new Error(`Bundle would reach a file outside the project root: ${abs}`)
965
- }
1097
+ return relativeEscapes(rel) ? null : rel
1098
+ }
1099
+ const toRel = (abs) => {
1100
+ const rel = relWithin(abs)
1101
+ if (rel === null) throw new Error(`Bundle would reach a file outside the project root: ${abs}`)
966
1102
  return rel
967
1103
  }
968
1104
 
@@ -973,8 +1109,9 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
973
1109
  if (!metroResolver) typescript ||= importsTypescriptByOutputName(absEntries, host)
974
1110
  // --typescript's tsconfig `paths` matcher, shared by every per-platform resolver below.
975
1111
  const typescriptPaths = typescriptPathsFor(typescript, baseDir, tsconfig, host, env)
976
- // --resources: extensions/filenames carried as opaque assets instead of failing "can't carry".
977
- const resourceSet = parseResourcesOption('buildResolvedJsBundle', resources)
1112
+ // --resources (else the config's): extensions/filenames carried as opaque assets instead of
1113
+ // failing "can't carry". --package-json, else the config's `packageJSON`: see withManifests below.
1114
+ const { resources: resourceSet, packageJSON: withManifests } = fieldBuildOptions('buildResolvedJsBundle', { cwd, scope, resources, packageJSON, host })
978
1115
 
979
1116
  const formatsByRel = new Map()
980
1117
  // Reached files the scanner tagged as resources (rel keys); read as bytes below, not UTF-8 source.
@@ -983,7 +1120,15 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
983
1120
  const edges = new Map()
984
1121
  const reached = new Set() // absolute paths reached on any platform
985
1122
  let usesEmpty = false
986
-
1123
+ // What a disabled import resolves to: under --metro Metro's own empty module where the project
1124
+ // has it (metroEmptyModule), as Metro resolves it; else the reserved synthetic one.
1125
+ const metroEmpty = metro ? metroEmptyModule(baseDir, host) : null
1126
+ const emptyTarget = metroEmpty === null ? EMPTY_MODULE_PATH : toRel(metroEmpty)
1127
+
1128
+ // --babel-aliases: the same aliasing as --babel's, from a JSON file of the project, for every platform alike.
1129
+ const fileAliases = aliasesFile === undefined ? null : createAliases(readAliasesFile(baseDir, aliasesFile, host), baseDir)
1130
+ // The edges each platform's scan left out above the root (withinRoot's leftOut), across platforms.
1131
+ const leftOutEdges = []
987
1132
  for (const platform of platforms) {
988
1133
  const field = fieldResolverFor(platform, { mainFields, metro, conditions: scanConditions, typescript, typescriptPaths, host })
989
1134
  const { extras } = field
@@ -997,8 +1142,16 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
997
1142
  // Without --typescript, the field resolver --typescript would build names the file a miss would
998
1143
  // land on: a hint in the unresolved report, never an edge (see Scan#typescriptCandidate).
999
1144
  const typescriptResolve = typescript || metroResolver ? null : fieldResolverFor(platform, { mainFields, metro, conditions: scanConditions, typescript: true, typescriptPaths, host }).resolver
1000
- const scanner = scan(absEntries, { conditions: extras, resolve: resolver, typescriptResolve, jsx, flow, resources: resourceSet, host })
1001
- reportScanIssues(analyzeScanner(scanner, { baseDir }), { baseDir, label: platform ?? 'mainFields' })
1145
+ // --babel: a specifier the project's babel-plugin-module-resolver rewrites resolves as rewritten,
1146
+ // as Metro resolves it after Babel; its edge stays keyed by the specifier the source holds.
1147
+ const aliases = babel ? createBabelAliases({ projectDir: baseDir, platform }) : fileAliases
1148
+ const aliased = (resolveFn) => (aliases && resolveFn ? (file, spec, conds) => resolveFn(file, aliases(file, spec) ?? spec, conds) : resolveFn)
1149
+ const scanned = scan(absEntries, { conditions: extras, resolve: aliased(resolver), typescriptResolve: aliased(typescriptResolve), jsx, flow, resources: resourceSet, define, host })
1150
+ // Only what lies within the root is carried; one the entries link eagerly is refused (see withinRoot).
1151
+ const { scanner, outside, leftOut } = withinRoot(scanned, (url) => relWithin(fileURLToPath(url)) !== null)
1152
+ for (const url of outside) toRel(fileURLToPath(url))
1153
+ reportScanIssues({ ...analyzeScanner(scanner, { baseDir }), leftOut }, { baseDir, label: platform ?? 'mainFields', root: ' at .' })
1154
+ leftOutEdges.push(...leftOut)
1002
1155
 
1003
1156
  const platformKey = platform ?? '*' // '*' is a private placeholder for the single mainFields pass; it never unflattens
1004
1157
  for (const [url, info] of scanner.files) {
@@ -1006,11 +1159,13 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
1006
1159
  const rel = toRel(abs)
1007
1160
  reached.add(abs)
1008
1161
  if (info.resource) resourceRels.add(rel)
1009
- formatsByRel.set(rel, info.format)
1162
+ // Under --metro a code file has no format, as the Metro plugin records it: Metro transforms
1163
+ // it from source, and Node's module/commonjs isn't what it runs.
1164
+ formatsByRel.set(rel, metro && !info.resource ? undefined : info.format)
1010
1165
  for (const e of info.edges) {
1011
1166
  if (e.builtin || e.dynamic) continue
1012
1167
  let target
1013
- if (e.empty) { usesEmpty = true; target = EMPTY_MODULE_PATH }
1168
+ if (e.empty) { usesEmpty = true; target = emptyTarget }
1014
1169
  else if (e.child) target = toRel(fileURLToPath(e.child))
1015
1170
  else continue // unresolved (already warned/thrown by reportScanIssues)
1016
1171
  if (!edges.has(rel)) edges.set(rel, new Map())
@@ -1021,6 +1176,10 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
1021
1176
  }
1022
1177
  }
1023
1178
 
1179
+ // One platform leaving out an edge another resolves within the root is a split too: collapsed
1180
+ // below, the edge would serve that platform the other's file in its place.
1181
+ refuseSplit(leftOutEdges.filter((e) => edges.get(toRel(fileURLToPath(e.parentURL)))?.has(e.spec)), baseDir)
1182
+
1024
1183
  // Read each reached file once: bytes for the bundle, integrity for the lockfile. Source is
1025
1184
  // stored as UTF-8 text, so non-UTF-8 bytes would diverge from the hashed bytes -- reject them.
1026
1185
  const sources = new Map()
@@ -1035,6 +1194,8 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
1035
1194
  // byte-derived format (here and in the --metro native capture below).
1036
1195
  const putResource = (rel, buf) => (isUtf8(buf) ? put(rel, buf.toString('utf8'), 'resource', buf) : put(rel, buf.toString('base64'), 'resource:base64', buf))
1037
1196
  const realBase = host.realpath(baseDir)
1197
+ // Metro's empty module is carried as the file it is, a code file of Metro's (no format).
1198
+ if (usesEmpty && metroEmpty !== null) reached.add(metroEmpty)
1038
1199
  for (const abs of reached) {
1039
1200
  const rel = toRel(abs)
1040
1201
  // Security: a resolved file arrives by its real path, which toRel already holds to the root,
@@ -1051,21 +1212,21 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
1051
1212
  put(rel, buf.toString('utf8'), formatsByRel.get(rel), buf)
1052
1213
  }
1053
1214
  }
1054
- if (usesEmpty) {
1215
+ if (usesEmpty && metroEmpty === null) {
1055
1216
  // Refuse to shadow a real reached file sitting at the reserved empty-module path.
1056
1217
  if (formatsByRel.has(EMPTY_MODULE_PATH)) {
1057
1218
  throw new Error(`Bundle needs the reserved empty-module path ${EMPTY_MODULE_PATH}, but the project has a real file there`)
1058
1219
  }
1059
- put(EMPTY_MODULE_PATH, '', 'commonjs', Buffer.alloc(0))
1220
+ put(EMPTY_MODULE_PATH, '', metro ? undefined : 'commonjs', Buffer.alloc(0))
1060
1221
  }
1061
1222
 
1062
1223
  // The package a bundled file is in (findPackageMetadata: its pkgDir and identity, null where no
1063
1224
  // manifest names one), memoized per directory so a package's many files don't each re-walk to it.
1064
1225
  const packageOf = packageLookup(baseDir, { host })
1065
1226
 
1066
- // --metro also carries each bundled dependency's native build-input surface (ios/android
1067
- // sources + podspecs), scoped to the packages in the bundle installed or linked into
1068
- // node_modules. Native source is stored as code under a language tag; other assets as
1227
+ // --metro also carries the native build inputs of each native package the app links, as the Metro
1228
+ // plugin does: the bundled packages installed or linked into node_modules, and those React Native
1229
+ // links unimported. Native source is stored as code under a language tag; other assets as
1069
1230
  // 'resource'/'resource:base64'.
1070
1231
  if (metro) {
1071
1232
  const pkgDirs = new Map() // package dir -> its package's name
@@ -1136,30 +1297,40 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
1136
1297
  }
1137
1298
  }
1138
1299
  }
1300
+ // And the app's packages React Native links whether JS imports them or not (`react-native config`'s
1301
+ // list, read as data), by their real path, but one above the root, which the plugin passes over too.
1302
+ for (const dir of linkedNativePackages(baseDir, host)) {
1303
+ let rel
1304
+ try {
1305
+ rel = toRel(host.realpath(dir))
1306
+ } catch {
1307
+ continue
1308
+ }
1309
+ if (!pkgDirs.has(rel)) pkgDirs.set(rel, readPackageJson(baseDir, `${rel}/package.json`, { host })?.name)
1310
+ }
1311
+ // Each one's native build inputs, walked whole (nativeInputs, shared with the plugin), read only
1312
+ // once its real path is held to the root.
1313
+ const nativeFs = {
1314
+ readdir: (abs) => host.readdir(abs),
1315
+ stat: (abs) => host.stat(abs),
1316
+ readFile(abs) {
1317
+ assertRealPathWithinBase(realBase, baseDir, toRel(abs), host)
1318
+ return host.readFile(abs)
1319
+ },
1320
+ }
1139
1321
  for (const [pkgDir, name] of [...pkgDirs].toSorted(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
1140
1322
  const pkgAbs = join(baseDir, pkgDir)
1141
1323
  // react-native core isn't a Pod (config reports it via reactNativePath, not `dependencies`),
1142
- // so walk its whole tree for native source (React/, ReactCommon/, ReactAndroid/, ...) the same
1143
- // way a native dep's ios/android surface is walked; every other dep gets its ios/android + podspecs.
1324
+ // but its native source (React/, ReactCommon/, ReactAndroid/, ...) is walked all the same.
1144
1325
  const isRnCore = name === 'react-native'
1145
- const files = isRnCore ? [] : nativeModuleFiles(pkgAbs, host)
1146
- if (isRnCore) walkNative(pkgAbs, files, host, isNativeSource)
1147
- for (const abs of files) {
1148
- const rel = toRel(abs)
1149
- if (sources.has(rel)) continue
1150
- assertRealPathWithinBase(realBase, baseDir, rel, host)
1151
- // classifyNativeCapture (shared with the StasisMetro plugin) returns action skip/code/resource with a format tag.
1152
- const byName = classifyNativeCapture(rel)
1153
- if (byName.action === 'skip') continue
1154
- const buf = host.readFile(abs)
1155
- // Byte-level rules (prebuilt binaries, binary plists) -- see refineNativeCapture.
1156
- const { action, format } = refineNativeCapture(byName, rel, buf, resourceSet)
1157
- if (action === 'skip') continue
1326
+ if (!isRnCore && !looksNative(pkgAbs, nativeFs)) continue
1327
+ for (const { file, source, action, format } of nativeInputs(pkgAbs, nativeFs, { resources: resourceSet, skip: (abs) => sources.has(toRel(abs)) })) {
1328
+ const rel = toRel(file)
1158
1329
  if (action === 'code') {
1159
- if (!isUtf8(buf)) throw new Error(`native source is not valid UTF-8: ${rel}`)
1160
- put(rel, buf.toString('utf8'), format, buf)
1330
+ if (!isUtf8(source)) throw new Error(`native source is not valid UTF-8: ${rel}`)
1331
+ put(rel, source.toString('utf8'), format, source)
1161
1332
  } else {
1162
- putResource(rel, buf)
1333
+ putResource(rel, source)
1163
1334
  }
1164
1335
  }
1165
1336
  // RN core's `.js` build scripts the classify loop skips (Metro-owned by extension, but never in
@@ -1179,12 +1350,12 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
1179
1350
  }
1180
1351
  }
1181
1352
 
1182
- // --package-json: fold each bundled module's package.json into `sources` (and its integrity into
1183
- // the companion lockfile) even when the scan never reached it. Buckets are the ones
1184
- // assembleCodeBundle derives, from the same `packageOf` (its pkgDir, else the '.' workspace
1185
- // bucket). readModuleManifest applies the read/validate rules shared with the State path
1186
- // (containment, UTF-8-aborts); no identity check here -- these buckets are all fresh from disk.
1187
- if (packageJSON) {
1353
+ // --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.
1355
+ // Buckets are the ones assembleCodeBundle derives, from the same `packageOf` (its pkgDir, else the
1356
+ // '.' workspace bucket). readModuleManifest applies the read/validate rules shared with the State
1357
+ // path (containment, UTF-8-aborts); no identity check here -- these buckets are all fresh from disk.
1358
+ if (withManifests) {
1188
1359
  const pkgDirs = new Set()
1189
1360
  for (const abs of reached) {
1190
1361
  const rel = toRel(abs)
@@ -1228,6 +1399,7 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
1228
1399
  conditionKey: '*',
1229
1400
  host,
1230
1401
  packageOf,
1402
+ consumer: metro ? 'bundle:metro' : 'bundle',
1231
1403
  })
1232
1404
 
1233
1405
  // The companion lockfile mirrors the bundle, swapping file content for its integrity.
@@ -1252,7 +1424,7 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
1252
1424
 
1253
1425
  // Classify entries into their single shared language and check option applicability; `name` prefixes
1254
1426
  // errors. A directory entry (resolved against `cwd`, on `host`) stands for the .sol files under it: Solidity only.
1255
- function classifyEntries(name, { cwd = process.cwd(), entries, mappingFile, manifests, scope, lockfile, conditions, mainFields, platforms, metro, metroResolver, jsx, flow, typescript, tsconfig, resources, packageJSON, cargo, cargoFeatures, cargoNoDefaultFeatures, cargoAllFeatures, cargoTarget, cargoManifests, host = diskHost, fetched }) {
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 }) {
1256
1428
  if (!Array.isArray(entries) || entries.length === 0) {
1257
1429
  throw new Error(`${name}: at least one entry file is required`)
1258
1430
  }
@@ -1318,6 +1490,10 @@ function classifyEntries(name, { cwd = process.cwd(), entries, mappingFile, mani
1318
1490
  if (jsx && kind !== 'js') {
1319
1491
  throw new Error(`${name}: --jsx is only valid for JS bundles`)
1320
1492
  }
1493
+ // --define folds the globals it gives in the JS scan's branch tests; no other language is scanned for them.
1494
+ if (parseDefine(name, define).size > 0 && kind !== 'js') {
1495
+ throw new Error(`${name}: --define is only valid for JS bundles`)
1496
+ }
1321
1497
  // --package-json folds each bundled module's npm package.json in; JS-only (the sol/php/bash/rust
1322
1498
  // bucketizers group by their own ecosystems' manifests, not an npm package.json).
1323
1499
  if (packageJSON && kind !== 'js') {
@@ -1352,41 +1528,84 @@ function classifyEntries(name, { cwd = process.cwd(), entries, mappingFile, mani
1352
1528
  if (metroResolver && !metro) {
1353
1529
  throw new Error(`${name}: --metro-resolver is only valid with --metro`)
1354
1530
  }
1531
+ // --babel takes the import aliases of the project's Babel config, which Metro runs; not otherwise.
1532
+ if (babel && !metro) {
1533
+ throw new Error(`${name}: --babel is only valid with --metro`)
1534
+ }
1535
+ // --babel-aliases takes the same aliases from a JSON file instead, so the two don't combine.
1536
+ if (babelAliases !== undefined) {
1537
+ 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`)
1539
+ if (babel) throw new Error(`${name}: --babel-aliases can't be combined with --babel (both set the import aliases)`)
1540
+ }
1355
1541
  // metro-resolver has no TS extension substitution, so --typescript would silently not apply -- reject it.
1356
1542
  if (typescript && metroResolver) {
1357
1543
  throw new Error(`${name}: --typescript is not supported with --metro-resolver (the project's metro-resolver doesn't substitute .js -> .ts)`)
1358
1544
  }
1359
- // The field resolver always emits full-scope, so --scope with --mainFields/--metro would be silently ignored -- reject it.
1360
- if (scope !== undefined && (mainFields !== undefined || metro)) {
1361
- throw new Error(`${name}: --scope is not supported with --mainFields or --metro`)
1362
- }
1545
+ // The field resolver always emits full-scope: a narrower --scope, or one from stasis.config.json,
1546
+ // would be silently ignored -- reject it here, before anything is built (or fetched).
1547
+ if (mainFields !== undefined || metro) fieldBuildOptions(name, { cwd, scope, resources, host })
1363
1548
  return kind
1364
1549
  }
1365
1550
 
1366
1551
  // A JS bundle as `stasis bundle` builds it: by the legacy-field resolver with `mainFields` or
1367
1552
  // `metro`, whose per-platform edges and synthetic empty module a State can't hold, else through a
1368
1553
  // State, which detects the bundle's repo itself. `root` is the directory the bundle's paths are
1369
- // relative to: cwd for the resolver's, the State's root for the State's.
1554
+ // relative to: cwd for the resolver's, the State's root for the State's. `extra` and `outputsAt` are
1555
+ // buildJsBundle's, for the State's alone (see withExtra).
1370
1556
  // -> { bundle, lockfile: () => Lockfile, stateBuilt, root }
1371
- async function buildJs({ mainFields, platforms, metro, metroResolver, innermostRoot, ...options }) {
1557
+ async function buildJs({ mainFields, platforms, metro, metroResolver, babel, babelAliases, innermostRoot, extra, outputsAt, ...options }) {
1372
1558
  if (metro || mainFields !== undefined) {
1373
- const built = await buildResolvedJsBundle({ ...options, mainFields: metro ? METRO_MAIN_FIELDS : mainFields, platforms: metro ? platforms : [null], metro: Boolean(metro), metroResolver: Boolean(metroResolver) })
1559
+ const built = await buildResolvedJsBundle({ ...options, mainFields: metro ? METRO_MAIN_FIELDS : mainFields, platforms: metro ? platforms : [null], metro: Boolean(metro), metroResolver: Boolean(metroResolver), babel: Boolean(babel), babelAliases })
1374
1560
  return { bundle: built.bundle, lockfile: () => built.lockfile, stateBuilt: false, root: resolve(options.cwd) }
1375
1561
  }
1376
- const state = await buildJsBundle({ ...options, innermostRoot })
1377
- // Stamp the `bundle` consumer (the static build carries none).
1378
- return { bundle: state.sourceBundle.withReason('bundle'), lockfile: () => state.lockfile, stateBuilt: true, root: state.root }
1562
+ const state = await buildJsBundle({ ...options, innermostRoot, extra, outputsAt })
1563
+ const bundle = state.sourceBundle
1564
+ // Stamp the `bundle` consumer (the static build carries none), unless `extra` added files: then
1565
+ // the State attributes each file, to `bundle` or `extra`.
1566
+ return { bundle: bundle.reason === undefined ? bundle.withReason('bundle') : bundle, lockfile: () => state.lockfile, stateBuilt: true, root: state.root }
1567
+ }
1568
+
1569
+ // `built` (buildOfKind's, built in `cwd` without a State, or the union of bundleCommand's `builds` rooted there) with the files the stasis.config.json
1570
+ // there names in `extra`, as `stasis add` adds them (extraArtifacts), into its bundle and its
1571
+ // lockfile; never one of `outputs` (the absolute paths the build writes), and resources by the
1572
+ // build's `resources` where given, else by the config's. A State-built bundle takes them in its
1573
+ // State instead, as `stasis run` does (State#includeExtra).
1574
+ function withExtra(built, cwd, outputs, resources) {
1575
+ const config = readConfigFile('bundle', cwd)
1576
+ const patterns = parseExtraOption(CONFIG_FILE, config?.extra)
1577
+ if (patterns.length === 0) return built
1578
+ // The union of `builds` (see bundleCommand) may be State-built in node_modules scope, which the
1579
+ // full-scope files `extra` adds can't join.
1580
+ if (built.bundle.config.scope !== 'full') throw new Error(`bundle: ${CONFIG_FILE}'s extra can't be added to a ${built.bundle.config.scope}-scope bundle of its entries`)
1581
+ const baseDir = resolve(cwd)
1582
+ const written = new Set(outputs.map((file) => toPosix(relative(baseDir, file))))
1583
+ const allowlist = resources === undefined ? parseResourcesOption(CONFIG_FILE, config.resources) : parseResourcesOption('--resources', resources)
1584
+ const added = extraArtifacts({ baseDir, patterns, resources: allowlist, bundle: built.bundle, outputs: written })
1585
+ if (added.bundle === null && added.carried.length === 0) return built
1586
+ // Each file attributed: to the build's own consumer (`bundle`, or `bundle:metro`, as codeBundle
1587
+ // stamps it), `extra`, or both, for one `extra` names that the build carries itself.
1588
+ const merged = added.bundle === null ? built.bundle : built.bundle.merge(added.bundle)
1589
+ const bundle = added.carried.length === 0 ? merged : merged.withReason('extra', added.carried)
1590
+ const { lockfile } = built
1591
+ return { ...built, bundle, ...(lockfile && added.lockfile && { lockfile: () => lockfile().merge(added.lockfile) }) }
1379
1592
  }
1380
1593
 
1381
- // The bundle of `kind` (classifyEntries') built from buildBundle's options, from disk: a JS bundle's
1382
- // git dependencies at the commits their package managers' records name (pinInstalledCommits).
1594
+ // The bundle of `kind` (classifyEntries') built from buildBundle's options, from disk, with the files
1595
+ // stasis.config.json's `extra` names: a JS bundle's git dependencies at the commits their package
1596
+ // managers' records name (pinInstalledCommits). `outputsAt(root)` are the absolute paths the build
1597
+ // writes, given the root its paths are relative to.
1383
1598
  // -> { bundle, lockfile: () => Lockfile, stateBuilt } (the last two of a JS bundle alone)
1384
- async function buildOfKind(kind, { cwd, env, entries, mappingFile, manifests, scope, conditions, mainFields, platforms, metro, metroResolver, jsx, flow, typescript, tsconfig, resources, packageJSON, cargo, cargoFeatures, cargoNoDefaultFeatures, cargoAllFeatures, cargoTarget, cargoManifests }) {
1385
- if (kind === 'sol') return { bundle: await buildSolidityBundle({ cwd, env, entries, mappingFile, manifests }) }
1386
- if (kind === 'php') return { bundle: await buildPhpBundle({ cwd, entries }) }
1387
- if (kind === 'bash') return { bundle: await buildBashBundle({ cwd, entries }) }
1388
- if (kind === 'rust') return { bundle: await buildRustBundle({ cwd, entries, cargo, cargoFeatures, cargoNoDefaultFeatures, cargoAllFeatures, cargoTarget, cargoManifests }) }
1389
- const built = await buildJs({ cwd, env, entries, scope, conditions, mainFields, platforms, metro, metroResolver, jsx, flow, typescript, tsconfig, resources, packageJSON })
1599
+ async function buildOfKind(kind, { cwd, env, entries, mappingFile, manifests, scope, conditions, mainFields, platforms, metro, metroResolver, babel, babelAliases, jsx, flow, typescript, tsconfig, resources, define, packageJSON, cargo, cargoFeatures, cargoNoDefaultFeatures, cargoAllFeatures, cargoTarget, cargoManifests, outputsAt = () => [], extra = true }) {
1600
+ const outputs = outputsAt(resolve(cwd))
1601
+ // Without `extra`, built as if the config named none (one of several builds of a bundle, see bundleCommand).
1602
+ const withExtraOf = (built, buildResources) => (extra ? withExtra(built, cwd, outputs, buildResources) : built)
1603
+ if (kind === 'sol') return withExtraOf({ bundle: await buildSolidityBundle({ cwd, env, entries, mappingFile, manifests }) })
1604
+ if (kind === 'php') return withExtraOf({ bundle: await buildPhpBundle({ cwd, entries }) })
1605
+ if (kind === 'bash') return withExtraOf({ bundle: await buildBashBundle({ cwd, entries }) })
1606
+ if (kind === 'rust') return withExtraOf({ bundle: await buildRustBundle({ cwd, entries, cargo, cargoFeatures, cargoNoDefaultFeatures, cargoAllFeatures, cargoTarget, cargoManifests }) })
1607
+ let built = await buildJs({ cwd, env, entries, scope, conditions, mainFields, platforms, metro, metroResolver, babel, babelAliases, jsx, flow, typescript, tsconfig, resources, define, packageJSON, extra, outputsAt })
1608
+ if (!built.stateBuilt) built = withExtraOf(built, resources)
1390
1609
  pinInstalledCommits(built.bundle, built.root)
1391
1610
  return built
1392
1611
  }
@@ -1398,6 +1617,8 @@ async function buildOfKind(kind, { cwd, env, entries, mappingFile, manifests, sc
1398
1617
  export function checkVfsOptions(name, options) {
1399
1618
  const kind = classifyEntries(name, options)
1400
1619
  if (options.metroResolver) throw new Error(`${name}: metroResolver is not supported`)
1620
+ // The project's Babel config is code, run from the disk.
1621
+ if (options.babel) throw new Error(`${name}: babel is not supported`)
1401
1622
  const { generate = [] } = options
1402
1623
  if (!Array.isArray(generate) || generate.some((step) => step !== 'prisma')) throw new TypeError(`${name}: generate must be an array of 'prisma'`)
1403
1624
  if (generate.length > 0 && kind !== 'js') throw new Error(`${name}: --generate is only valid for JS bundles`)
@@ -1459,10 +1680,13 @@ export async function buildVfsBundle({ vfs, packageManager, cwd = '/', packageMa
1459
1680
  }
1460
1681
 
1461
1682
  // Programmatic equivalent of `stasis bundle`: build and return an in-memory Bundle without
1462
- // writing to disk. Files are attributed to the `bundle` consumer. Option applicability
1463
- // (--mapping|--manifests/.sol, --scope|--conditions|--mainFields|--metro|--jsx|--flow|--typescript/JS) is enforced by classifyEntries.
1464
- export async function buildBundle({ cwd = process.cwd(), env = process.env, entries, mappingFile, manifests = false, scope, conditions, mainFields, platforms, metro, metroResolver, jsx = false, flow = false, typescript = false, tsconfig, resources = [], packageJSON = false, cargo = false, cargoFeatures = [], cargoNoDefaultFeatures = false, cargoAllFeatures = false, cargoTarget = null, cargoManifests = false } = {}) {
1465
- const options = { cwd, env, entries, mappingFile, manifests, scope, conditions, mainFields, platforms, metro, metroResolver, jsx, flow, typescript, tsconfig, resources, packageJSON, cargo, cargoFeatures, cargoNoDefaultFeatures, cargoAllFeatures, cargoTarget, cargoManifests }
1683
+ // writing to disk. Files are attributed to the `bundle` consumer (`bundle:metro` with `metro`).
1684
+ // Option applicability (--mapping|--manifests/.sol, --scope|--conditions|--mainFields|--metro|--jsx|
1685
+ // --flow|--typescript|--define/JS) is enforced by classifyEntries. `define` gives globals their
1686
+ // values (`{ __DEV__: false, 'process.env.NODE_ENV': 'production' }`), whose dead branches' imports
1687
+ // are left out (see define.js).
1688
+ export async function buildBundle({ cwd = process.cwd(), env = process.env, entries, mappingFile, manifests = false, scope, conditions, mainFields, platforms, metro, metroResolver, babel = false, babelAliases, jsx = false, flow = false, typescript = false, tsconfig, resources, define, packageJSON = false, cargo = false, cargoFeatures = [], cargoNoDefaultFeatures = false, cargoAllFeatures = false, cargoTarget = null, cargoManifests = false } = {}) {
1689
+ const options = { cwd, env, entries, mappingFile, manifests, scope, conditions, mainFields, platforms, metro, metroResolver, babel, babelAliases, jsx, flow, typescript, tsconfig, resources, define, packageJSON, cargo, cargoFeatures, cargoNoDefaultFeatures, cargoAllFeatures, cargoTarget, cargoManifests }
1466
1690
  return (await buildOfKind(classifyEntries('buildBundle', options), options)).bundle
1467
1691
  }
1468
1692
 
@@ -1472,30 +1696,64 @@ export async function buildBundle({ cwd = process.cwd(), env = process.env, entr
1472
1696
  // with `--conditions` it attests the conditions-selected graph, so a plain
1473
1697
  // `stasis run --lock=frozen` (which doesn't replay them) fails closed -- pair it with
1474
1698
  // `--bundle=load` or replay the conditions. `add` unions the fresh build into the bundle
1475
- // already on disk (strict; a conflicting file throws) and can't target stdout.
1476
- export async function bundleCommand({ cwd = process.cwd(), env = process.env, entries, mappingFile, manifests = false, output, scope, lockfile, conditions, mainFields, platforms, metro, metroResolver, jsx = false, flow = false, typescript = false, tsconfig, resources = [], packageJSON = false, cargo = false, cargoFeatures = [], cargoNoDefaultFeatures = false, cargoAllFeatures = false, cargoTarget = null, cargoManifests = false, brotliQuality, add = false } = {}) {
1477
- const options = { cwd, env, entries, mappingFile, manifests, scope, conditions, mainFields, platforms, metro, metroResolver, jsx, flow, typescript, tsconfig, resources, packageJSON, cargo, cargoFeatures, cargoNoDefaultFeatures, cargoAllFeatures, cargoTarget, cargoManifests }
1478
- const kind = classifyEntries('bundleCommand', { ...options, lockfile })
1699
+ // already on disk (strict; a conflicting file throws) and can't target stdout. `builds`, in place
1700
+ // of `entries` and the options building them, is several builds' (each `{ entries, ...options }`,
1701
+ // as stasis.config.json's `bundle` gives an entry its own, see bundle-options.js), whose bundles
1702
+ // (and lockfiles) are one's: their strict union, rooted where every one of them is.
1703
+ export async function bundleCommand({ cwd = process.cwd(), env = process.env, entries, mappingFile, manifests = false, output, scope, lockfile, conditions, mainFields, platforms, metro, metroResolver, babel = false, babelAliases, jsx = false, flow = false, typescript = false, tsconfig, resources, define, packageJSON = false, cargo = false, cargoFeatures = [], cargoNoDefaultFeatures = false, cargoAllFeatures = false, cargoTarget = null, cargoManifests = false, brotliQuality, add = false, builds } = {}) {
1704
+ const options = { cwd, env, entries, mappingFile, manifests, scope, conditions, mainFields, platforms, metro, metroResolver, babel, babelAliases, jsx, flow, typescript, tsconfig, resources, define, packageJSON, cargo, cargoFeatures, cargoNoDefaultFeatures, cargoAllFeatures, cargoTarget, cargoManifests }
1705
+ if (builds !== undefined) {
1706
+ if (!Array.isArray(builds) || builds.length === 0) throw new TypeError('bundleCommand: builds must be a non-empty array')
1707
+ const given = Object.entries(options).find(([key, value]) => !['cwd', 'env'].includes(key) && value !== undefined && value !== false && value !== null && !(Array.isArray(value) && value.length === 0))
1708
+ if (given) throw new TypeError(`bundleCommand: ${given[0]} can't be combined with builds (each build sets its own)`)
1709
+ }
1710
+ // Each build's options, the defaults above where it leaves one out.
1711
+ const defaults = { manifests, babel, jsx, flow, typescript, packageJSON, cargo, cargoFeatures, cargoNoDefaultFeatures, cargoAllFeatures, cargoTarget, cargoManifests }
1712
+ const plans = (builds ?? [{}]).map((build) => ({ ...options, ...defaults, ...build, cwd, env }))
1713
+ const kinds = plans.map((plan) => classifyEntries('bundleCommand', { ...plan, lockfile }))
1479
1714
 
1480
1715
  // --add has nothing to merge into on stdout (write-only).
1481
1716
  if (add && output === '-') {
1482
1717
  throw new Error('bundleCommand: --add cannot be combined with --output=- (nothing to merge into on stdout)')
1483
1718
  }
1484
1719
 
1485
- const built = await buildOfKind(kind, options)
1486
- let { bundle } = built
1720
+ // The files this build writes, never taken into `extra`, given the root its paths are relative to:
1721
+ // the bundle (by default at that root, see `target` below) and the lockfile.
1722
+ const outputsAt = (root) => [output ?? join(root, DEFAULT_BUNDLE_FILE), lockfile].filter((file) => file !== undefined && file !== '-').map((file) => resolve(cwd, file))
1723
+ // With `builds` (stasis.config.json's entries, however many builds they make), `extra` is the
1724
+ // bundle's, not any build's: added to their union below.
1725
+ const bundleExtra = builds !== undefined
1726
+ const builts = []
1727
+ for (const [i, plan] of plans.entries()) {
1728
+ // eslint-disable-next-line no-await-in-loop -- one build at a time, in the order its warnings read
1729
+ builts.push(await buildOfKind(kinds[i], { ...plan, outputsAt, extra: !bundleExtra }))
1730
+ }
1487
1731
  // The directory the bundle's paths are relative to: a State-built JS bundle's root, which is the
1488
1732
  // project's at or above cwd (a workspace package's is the workspace root's), else cwd.
1489
- const root = built.root ?? resolve(cwd)
1733
+ const roots = builts.map((built) => built.root ?? resolve(cwd))
1734
+ const root = roots[0]
1735
+ const other = roots.findIndex((r) => r !== root)
1736
+ if (other !== -1) {
1737
+ throw new Error(`bundleCommand: ${plans[0].entries[0]} and ${plans[other].entries[0]} can't be bundled together: their bundles' paths are relative to different roots (${root} and ${roots[other]})`)
1738
+ }
1490
1739
  // By default the bundle goes there, where `stasis run --bundle=load` discovers it. In cwd below
1491
1740
  // the root it would load as rooted at cwd, and root the next `stasis bundle` there too, out of the
1492
1741
  // files above it.
1493
1742
  const target = output ?? relative(resolve(cwd), join(root, DEFAULT_BUNDLE_FILE))
1494
- // Only a JS bundle has a lockfile (classifyEntries refuses one for the others).
1495
- let lockData = lockfile ? built.lockfile().serialize() : undefined
1496
1743
 
1497
1744
  // State-built bundles keep the State root's repo (no cwd fallback: their paths are relative to that root).
1498
- if (!built.stateBuilt) bundle.repo ??= detectRepo(cwd)
1745
+ for (const built of builts) if (!built.stateBuilt) built.bundle.repo ??= detectRepo(cwd)
1746
+ let union = builts.reduce((a, b) => ({ bundle: a.bundle.merge(b.bundle), lockfile: a.lockfile && (() => a.lockfile().merge(b.lockfile())) }))
1747
+ if (bundleExtra) {
1748
+ // Once, whatever the builds' order: to their union, whose own record of a file stands, by the
1749
+ // allowlist of the stasis.config.json at the root, not any one entry's `resources`.
1750
+ const withExtras = withExtra(union, root, outputsAt(root))
1751
+ if (withExtras !== union) pinInstalledCommits(withExtras.bundle, root)
1752
+ union = withExtras
1753
+ }
1754
+ let { bundle } = union
1755
+ // Only a JS bundle has a lockfile (classifyEntries refuses one for the others).
1756
+ let lockData = lockfile ? union.lockfile().serialize() : undefined
1499
1757
 
1500
1758
  // --add: union the fresh build into the existing on-disk bundle; a conflicting file throws. Skipped when nothing is on disk.
1501
1759
  const outAbs = target === '-' ? undefined : resolve(cwd, target)