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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/stasis.js CHANGED
@@ -7,7 +7,7 @@ import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
7
7
  import { existsSync, realpathSync } from 'node:fs'
8
8
  import { homedir, constants as osConstants } from 'node:os'
9
9
  import assert from 'node:assert/strict'
10
- import { parseBrotliQuality, parseLeadingOptions, parseResourcesOption } from '@exodus/stasis-core/util'
10
+ import { parseBrotliQuality, parseLeadingOptions } from '@exodus/stasis-core/util'
11
11
  import pkg from '../package.json' with { type: 'json' }
12
12
 
13
13
  const argv = [...process.argv]
@@ -20,10 +20,11 @@ assert(basename(jsname) === 'stasis' || pathsEqual(jsname, fileURLToPath(import.
20
20
 
21
21
  const HELP = `Usage:
22
22
  stasis run --lock=(add|replace|frozen|ignore) [--bundle=(add|replace|load|frozen|ignore)] [--bundle-file=path/to/bundle.br] [--resources-bundle-file=path/to/resources.br] [--dependencies] [--child-process] [--package-json] [--mock] [--import=module ...] [--fs=(sync|async)] [--resources=ext,ext] [--brotli-quality=0..11] path/to/file.js ...
23
- stasis bundle [--scope=(node_modules|full)] [--conditions=cond1,cond2] [--mainFields=field1,field2] [--metro [--metro-resolver] --platforms=ios,android] [--jsx] [--flow] [--typescript [--tsconfig=path/to/tsconfig.json]] [--resources=ext,ext] [--package-json] [--lockfile=path/to/stasis.lock.json] [--brotli-quality=0..11] [--add] [--output=(path|-)] path/to/file.(js|ts|jsx|tsx) ...
23
+ stasis bundle [--scope=(node_modules|full)] [--conditions=cond1,cond2] [--mainFields=field1,field2] [--metro [--metro-resolver] [--babel|--babel-aliases=path/to/aliases.json] --platforms=ios,android] [--jsx] [--flow] [--typescript [--tsconfig=path/to/tsconfig.json]] [--resources=ext,ext] [--define=K=V ...] [--package-json] [--lockfile=path/to/stasis.lock.json] [--brotli-quality=0..11] [--add] [--output=(path|-)] path/to/file.(js|ts|jsx|tsx) ...
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] [--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
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) ...]
28
29
  stasis add path/to/(file|dir) ...
29
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]
@@ -189,203 +190,22 @@ if (command === '-v' || command === '--version') {
189
190
  // code is null when the child died from a signal; report 128+signo (shell convention) instead of the implicit 0
190
191
  process.exitCode = code ?? 128 + (osConstants.signals[signal] ?? 0)
191
192
  } else if (command === 'bundle') {
192
- const options = {
193
- mapping: { type: 'string' },
194
- manifests: { type: 'boolean' },
195
- output: { type: 'string', short: 'o' },
196
- scope: { type: 'string' },
197
- lockfile: { type: 'string' },
198
- conditions: { type: 'string' },
199
- mainFields: { type: 'string' },
200
- metro: { type: 'boolean' },
201
- 'metro-resolver': { type: 'boolean' },
202
- platforms: { type: 'string', multiple: true },
203
- jsx: { type: 'boolean' },
204
- flow: { type: 'boolean' },
205
- typescript: { type: 'boolean' },
206
- tsconfig: { type: 'string' },
207
- resources: { type: 'string' },
208
- 'package-json': { type: 'boolean' },
209
- cargo: { type: 'boolean' },
210
- 'cargo-features': { type: 'string', multiple: true },
211
- 'cargo-no-default-features': { type: 'boolean' },
212
- 'cargo-all-features': { type: 'boolean' },
213
- 'cargo-target': { type: 'string' },
214
- 'cargo-manifests': { type: 'boolean' },
215
- 'brotli-quality': { type: 'string' },
216
- add: { type: 'boolean' },
217
- }
218
- const values = parseLeadingOptions(argv, options, {
219
- valueFlags: ['--mapping', '--output', '--scope', '--lockfile', '--conditions', '--mainFields', '--platforms', '--resources', '--tsconfig', '--cargo-features', '--cargo-target', '--brotli-quality', '-o'],
220
- onError: fail,
221
- })
222
- if (argv.length === 0) fail('Nothing to bundle: no entry file given')
223
- // A directory entry stands for the .sol files under it (Solidity only); an extensionless path
224
- // that doesn't exist is a missing one (skipped with a warning).
225
- const { directoryEntryError, isSolidityEntry } = await import('../src/cmd/bundle.js')
226
- const dirError = directoryEntryError(argv)
227
- if (dirError !== null) fail(`Error: ${dirError}`)
228
- const allSol = argv.every((f) => isSolidityEntry(f))
229
- const allPhp = argv.every((f) => f.endsWith('.php'))
230
- const allJs = argv.every((f) => /\.(?:js|cjs|mjs|ts|cts|mts|jsx|tsx)$/u.test(f))
231
- const allBash = argv.every((f) => /\.(?:sh|bash)$/u.test(f))
232
- const allRust = argv.every((f) => f.endsWith('.rs'))
233
- if (!allSol && !allPhp && !allJs && !allBash && !allRust) {
234
- fail('Error: bundle entries must all be .sol, all be .php, all be .js/.cjs/.mjs/.ts/.cts/.mts/.jsx/.tsx, all be .sh/.bash, or all be .rs')
235
- }
236
- if (values.mapping && !allSol) fail('Error: --mapping is only valid for .sol bundles')
237
- // --manifests: carry the Solidity build's description files (foundry.toml, remappings.txt, ...).
238
- const manifests = Boolean(values.manifests)
239
- if (manifests && !allSol) fail('Error: --manifests is only valid for .sol bundles')
240
- // --cargo: take the Rust feature/dependency resolution from `cargo metadata` (runs cargo; opt-in).
241
- const cargo = Boolean(values.cargo)
242
- if (cargo && !allRust) fail('Error: --cargo is only valid for Rust bundles')
243
- // --cargo-features / --cargo-no-default-features / --cargo-all-features: cargo's own feature flags
244
- // for the entries' packages (`pkg/feat` targets one, or a dependency). --cargo-features is
245
- // repeatable and/or comma-separated; parseFeatureList is the one splitter (the resolver reuses it).
246
- const { parseFeatureList } = await import('../src/loaders/cargo.js')
247
- const cargoFeatures = parseFeatureList(values['cargo-features'] ?? [])
248
- if (values['cargo-features'] !== undefined && cargoFeatures.length === 0) {
249
- fail('Error: --cargo-features must list at least one feature (e.g. --cargo-features=serde,app/tls)')
250
- }
251
- const cargoNoDefaultFeatures = Boolean(values['cargo-no-default-features'])
252
- const cargoAllFeatures = Boolean(values['cargo-all-features'])
253
- // --cargo-target=<triple|host>: the build's target, whose cfgs (from `rustc --print cfg`) decide
254
- // `#[cfg(unix)]`-style code. A triple is letters, digits, `-`, `_` and `.` (`x86_64-unknown-linux-gnu`).
255
- const cargoTarget = values['cargo-target'] ?? null
256
- if (cargoTarget !== null && !/^[\w.-]+$/u.test(cargoTarget)) {
257
- fail('Error: --cargo-target must be a target triple or "host" (e.g. --cargo-target=aarch64-apple-darwin)')
258
- }
259
- // --cargo-manifests: carry each bundled package's Cargo.toml and build script, the workspace
260
- // Cargo.toml, Cargo.lock and .cargo/config.toml too (the Rust counterpart of --package-json).
261
- const cargoManifests = Boolean(values['cargo-manifests'])
262
- if (!allRust) {
263
- const given = { 'cargo-features': cargoFeatures.length > 0, 'cargo-no-default-features': cargoNoDefaultFeatures, 'cargo-all-features': cargoAllFeatures, 'cargo-target': cargoTarget !== null, 'cargo-manifests': cargoManifests }
264
- for (const [flag, on] of Object.entries(given)) if (on) fail(`Error: --${flag} is only valid for Rust bundles`)
265
- }
266
- if (values.scope && !allJs) fail('Error: --scope is only valid for JS bundles')
267
- if (values.scope && !['node_modules', 'full'].includes(values.scope)) {
268
- fail('Error: --scope must be node_modules or full')
269
- }
270
- if (values.lockfile && !allJs) fail('Error: --lockfile is only valid for JS bundles')
271
- // --mainFields/--metro always emit a full-scope bundle, so they'd silently ignore --scope.
272
- if (values.scope !== undefined && (values.mainFields !== undefined || values.metro)) {
273
- fail('Error: --scope is not supported with --mainFields or --metro')
274
- }
275
- // --conditions: extra exports/imports resolution conditions merged onto Node's defaults;
276
- // they don't honour legacy `mainFields` or platform suffixes (see --mainFields).
277
- if (values.conditions !== undefined && !allJs) fail('Error: --conditions is only valid for JS bundles')
278
- const conditions = values.conditions === undefined
279
- ? []
280
- : values.conditions.split(',').map((s) => s.trim()).filter(Boolean)
281
- if (values.conditions !== undefined && conditions.length === 0) {
282
- fail('Error: --conditions must list at least one condition name (e.g. --conditions=react-native,browser)')
283
- }
284
- // --flow: strip Flow type syntax (via the optional flow-remove-types dep) before parsing; JS-only.
285
- if (values.flow && !allJs) fail('Error: --flow is only valid for JS bundles')
286
- const flow = Boolean(values.flow)
287
- // --typescript: resolve like tsc -- a specifier naming a missing JS output (./x.js, .mjs, .cjs,
288
- // extensionless) lands on its on-disk TS source (./x.ts, .mts, .cts); an existing .js always wins.
289
- if (values.typescript && !allJs) fail('Error: --typescript is only valid for JS bundles')
290
- const typescript = Boolean(values.typescript)
291
- // --tsconfig: the config whose compilerOptions.paths aliases --typescript honours (default: the
292
- // tsconfig.json beside each importing file's package.json). Meaningless without --typescript.
293
- if (values.tsconfig !== undefined && !typescript) fail('Error: --tsconfig is only valid with --typescript')
294
- // --mainFields: legacy package entry fields (e.g. react-native,browser,main) for the non-exports resolver.
295
- if (values.mainFields !== undefined && !allJs) fail('Error: --mainFields is only valid for JS bundles')
296
- const mainFields = values.mainFields === undefined
297
- ? undefined
298
- : values.mainFields.split(',').map((s) => s.trim()).filter(Boolean)
299
- if (values.mainFields !== undefined && mainFields.length === 0) {
300
- fail('Error: --mainFields must list at least one field (e.g. --mainFields=react-native,browser,main)')
301
- }
302
- // --metro: resolve like Metro/RN (its own conditions + mainFields, platform suffixes per
303
- // --platforms target). --platforms is repeatable and/or comma-separated; the values union.
304
- const metro = Boolean(values.metro)
305
- // --metro-resolver: resolve through the project's own metro-resolver instead of the built-in
306
- // approximation. Only meaningful alongside --metro (enforced below and in classifyEntries).
307
- const metroResolver = Boolean(values['metro-resolver'])
308
- const platforms = [...new Set((values.platforms ?? []).flatMap((p) => p.split(',')).map((s) => s.trim()).filter(Boolean))]
309
- // A platform name becomes an edge key: reject '/' (parsers reject it) and '*' (reserved placeholder).
310
- for (const p of platforms) {
311
- if (p === '*' || p.includes('/')) fail(`Error: invalid --platforms value '${p}' (a platform name can't contain '/' or be '*')`)
312
- }
313
- if ((metro || platforms.length > 0) && !allJs) fail('Error: --metro is only valid for JS bundles')
314
- // --jsx: parse React Native's JSX-in-.js source in the static scanner (off by default; oxc,
315
- // like tsc, auto-enables JSX for .jsx/.tsx only). Orthogonal to the resolver, so it pairs with
316
- // plain/--mainFields/--metro alike -- JS-only, since no other entry language is scanned.
317
- const jsx = Boolean(values.jsx)
318
- if (jsx && !allJs) fail('Error: --jsx is only valid for JS bundles')
319
- // --package-json: fold each bundled module's package.json into the bundle. JS-only (only JS
320
- // modules carry an npm package.json; the sol/php/bash/rust bucketizers have no such manifest).
321
- const packageJSON = Boolean(values['package-json'])
322
- if (packageJSON && !allJs) fail('Error: --package-json is only valid for JS bundles')
323
- // --resources: comma-separated extension/filename allowlist for assets reached through the graph
324
- // (e.g. --resources=png,svg). They're carried as resources instead of failing "can't carry" --
325
- // for graphs that aren't fully loadable in JS (Metro consumes such assets). JS-only.
326
- if (values.resources !== undefined && !allJs) fail('Error: --resources is only valid for JS bundles')
327
- const resources = values.resources === undefined
328
- ? []
329
- : values.resources.split(',').map((s) => s.trim()).filter(Boolean)
330
- if (values.resources !== undefined && resources.length === 0) {
331
- fail('Error: --resources must list at least one extension or filename (e.g. --resources=png,svg)')
332
- }
193
+ const { BUNDLE_FLAGS, BUNDLE_VALUE_FLAGS, bundlePlan, readConfigEntries } = await import('../src/cmd/bundle-options.js')
194
+ const values = parseLeadingOptions(argv, BUNDLE_FLAGS, { valueFlags: BUNDLE_VALUE_FLAGS, onError: fail })
195
+ const cwd = process.cwd()
196
+ let plan
333
197
  try {
334
- parseResourcesOption('--resources', resources) // validate early for a clean usage error (code exts / bad chars rejected)
198
+ // stasis.config.json's `bundle`, where it is an object: its entries' options, and with no entry
199
+ // given, the entries.
200
+ const config = readConfigEntries(cwd)
201
+ const entries = argv.length > 0 ? argv : [...(config?.values() ?? [])].map(({ entry }) => entry)
202
+ if (entries.length === 0) fail('Nothing to bundle: no entry file given')
203
+ plan = bundlePlan({ cwd, entries, values, config })
335
204
  } catch (cause) {
336
205
  fail(`Error: ${cause.message}`)
337
206
  }
338
- if (metro) {
339
- if (conditions.length > 0) fail("Error: --conditions can't be combined with --metro (it sets its own conditions)")
340
- if (mainFields !== undefined) fail("Error: --mainFields can't be combined with --metro (it sets its own mainFields)")
341
- if (platforms.length === 0) fail('Error: --metro requires --platforms (e.g. --platforms=ios,android)')
342
- } else if (platforms.length > 0) {
343
- fail('Error: --platforms is only valid with --metro')
344
- }
345
- if (metroResolver && !metro) fail('Error: --metro-resolver is only valid with --metro')
346
- // metro-resolver can't substitute .js -> .ts, so --typescript would silently not apply -- reject it.
347
- if (typescript && metroResolver) fail("Error: --typescript is not supported with --metro-resolver (the project's metro-resolver doesn't substitute .js -> .ts)")
348
- // --brotli-quality: valid for every entry language (no allJs gate).
349
- let brotliQuality
350
- if (values['brotli-quality'] !== undefined) {
351
- try {
352
- brotliQuality = parseBrotliQuality('--brotli-quality', values['brotli-quality'])
353
- } catch (cause) {
354
- fail(`Error: ${cause.message}`)
355
- }
356
- }
357
- // --add merges into the existing bundle at --output, so it can't target write-only stdout.
358
- const add = Boolean(values.add)
359
- if (add && values.output === '-') fail('Error: --add cannot be combined with --output=-')
360
207
  const { bundleCommand } = await import('../src/cmd/bundle.js')
361
- await bundleCommand({
362
- cwd: process.cwd(),
363
- entries: argv,
364
- mappingFile: values.mapping,
365
- manifests,
366
- output: values.output,
367
- scope: values.scope,
368
- lockfile: values.lockfile,
369
- conditions,
370
- mainFields,
371
- metro,
372
- metroResolver,
373
- platforms,
374
- jsx,
375
- flow,
376
- typescript,
377
- tsconfig: values.tsconfig,
378
- resources,
379
- packageJSON,
380
- cargo,
381
- cargoFeatures,
382
- cargoNoDefaultFeatures,
383
- cargoAllFeatures,
384
- cargoTarget,
385
- cargoManifests,
386
- brotliQuality,
387
- add,
388
- })
208
+ await bundleCommand({ cwd, ...plan })
389
209
  } else if (command === 'github-bundle') {
390
210
  const values = parseLeadingOptions(argv, {
391
211
  github: { type: 'string' },
@@ -408,11 +228,12 @@ if (command === '-v' || command === '--version') {
408
228
  typescript: { type: 'boolean' },
409
229
  tsconfig: { type: 'string' },
410
230
  resources: { type: 'string' },
231
+ define: { type: 'string', multiple: true },
411
232
  'package-json': { type: 'boolean' },
412
233
  'brotli-quality': { type: 'string' },
413
234
  generate: { type: 'string', multiple: true },
414
235
  }, {
415
- valueFlags: ['--github', '--sha', '--tag', '--directory', '--package-manager', '--package-manager-version', '--mapping', '--output', '--scope', '--lockfile', '--conditions', '--mainFields', '--platforms', '--tsconfig', '--resources', '--brotli-quality', '--generate', '-o'],
236
+ valueFlags: ['--github', '--sha', '--tag', '--directory', '--package-manager', '--package-manager-version', '--mapping', '--output', '--scope', '--lockfile', '--conditions', '--mainFields', '--platforms', '--tsconfig', '--resources', '--define', '--brotli-quality', '--generate', '-o'],
416
237
  onError: fail,
417
238
  })
418
239
  if (values.github === undefined) fail('Error: github-bundle requires --github=owner/name, the repo to bundle')
@@ -427,6 +248,15 @@ if (command === '-v' || command === '--version') {
427
248
  fail(`Error: ${cause.message}`)
428
249
  }
429
250
  }
251
+ let define
252
+ if (values.define !== undefined) {
253
+ const { parseDefineFlags } = await import('../src/define.js')
254
+ try {
255
+ define = parseDefineFlags(null, values.define)
256
+ } catch (cause) {
257
+ fail(`Error: ${cause.message}`)
258
+ }
259
+ }
430
260
  // Tarballs, zips and GitHub trees are cached where `stasis audit` caches.
431
261
  const { setCacheDir } = await import('../src/vfs-bundle.js')
432
262
  setCacheDir(userCacheDir())
@@ -452,7 +282,8 @@ if (command === '-v' || command === '--version') {
452
282
  flow: Boolean(values.flow),
453
283
  typescript: Boolean(values.typescript),
454
284
  tsconfig: values.tsconfig,
455
- resources: list(values.resources),
285
+ resources: values.resources === undefined ? undefined : list(values.resources),
286
+ define,
456
287
  packageJSON: Boolean(values['package-json']),
457
288
  generate: list(values.generate),
458
289
  brotliQuality,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@exodus/stasis",
3
- "version": "1.0.0-beta.11",
3
+ "version": "1.0.0-beta.13",
4
4
  "description": "File-level source bundles and lockfiles",
5
5
  "type": "module",
6
6
  "exports": {
@@ -34,11 +34,13 @@
34
34
  "src/bundle-from-lockfile.js",
35
35
  "src/bundle-reader.js",
36
36
  "src/cmd/bundle.js",
37
+ "src/cmd/bundle-options.js",
37
38
  "src/cmd/build.js",
38
39
  "src/cmd/diff.js",
39
40
  "src/cmd/github-bundle.js",
40
41
  "src/cmd/output.js",
41
42
  "src/cmd/sbom.js",
43
+ "src/define.js",
42
44
  "src/diff.js",
43
45
  "src/esbuild.js",
44
46
  "src/installed-commits.js",
@@ -95,19 +97,19 @@
95
97
  "homepage": "https://github.com/PreventiveMeasures/stasis#readme",
96
98
  "dependencies": {
97
99
  "@exodus/bytes": "^1.16.0",
98
- "@exodus/stasis-core": "1.0.0-beta.11",
99
- "@exodus/stasis-plugins": "1.0.0-beta.11",
100
+ "@exodus/stasis-core": "1.0.0-beta.13",
101
+ "@exodus/stasis-plugins": "1.0.0-beta.13",
100
102
  "@preventive/archive": "^1.2.0",
101
103
  "@preventive/deptree": "^1.0.1",
102
104
  "@preventive/lockfile": "^1.2.0",
103
105
  "@preventive/upstream": "^1.3.0",
104
106
  "@preventive/vfs": "1.0.0-beta.4",
107
+ "flow-remove-types": "^2.322.0",
105
108
  "oxc-parser": "^0.152.0"
106
109
  },
107
110
  "peerDependencies": {
108
111
  "@prisma/client-generator-ts": "7.10.0",
109
- "esbuild": "*",
110
- "flow-remove-types": "*"
112
+ "esbuild": "*"
111
113
  },
112
114
  "peerDependenciesMeta": {
113
115
  "@prisma/client-generator-ts": {
@@ -115,9 +117,6 @@
115
117
  },
116
118
  "esbuild": {
117
119
  "optional": true
118
- },
119
- "flow-remove-types": {
120
- "optional": true
121
120
  }
122
121
  }
123
122
  }
package/src/audit.js CHANGED
@@ -176,15 +176,15 @@ export function collectReasons(files) {
176
176
  const SEVERITY_ORDER = { critical: 0, high: 1, moderate: 2, low: 3, info: 4, none: 5 }
177
177
 
178
178
  // Consumer display order: bundler plugins (metro, webpack, esbuild, ...) first,
179
- // then `run`, then `add`. Ties broken alphabetically.
180
- const CONSUMER_RANK = { run: 1, add: 2 }
179
+ // then `run`, then `add`, then `extra` (stasis.config.json's). Ties broken alphabetically.
180
+ const CONSUMER_RANK = { run: 1, add: 2, extra: 3 }
181
181
  const consumerRank = (c) => CONSUMER_RANK[c] ?? 0
182
182
  const byConsumerOrder = (a, b) => consumerRank(a) - consumerRank(b) || a.localeCompare(b)
183
183
 
184
184
  // Build a row's `reason` cell by unioning over exactly the affected versions it
185
185
  // covers. Without `--why` that's the `, `-joined set of bundle consumers; with
186
186
  // `--why` it's the newline-joined `consumer: a -> b -> c` import-path lines
187
- // (which REPLACE the consumer list). Consumers are ordered plugins -> run -> add.
187
+ // (which REPLACE the consumer list). Consumers are ordered plugins -> run -> add -> extra.
188
188
  // `reasonFilter`, when set, narrows the cell to a single consumer: the `--why`
189
189
  // chains are already filtered upstream (see collectWhy), so only the consumer
190
190
  // list needs pruning here. collectWhy follows npm's import graph alone, so an
@@ -197,7 +197,7 @@ function reasonCell({ ecosystem, name, versions: affected }, reasonsByPkg, whyBy
197
197
  for (const p of source.get(keyOf(ecosystem, name, v)) ?? []) parts.add(p)
198
198
  }
199
199
  // --why: group `consumer: path` lines by consumer and order the groups
200
- // plugins -> run -> add (this also re-unites a consumer's lines when they were
200
+ // plugins -> run -> add -> extra (this also re-unites a consumer's lines when they were
201
201
  // split across affected versions); within a group collectWhy's compressed order
202
202
  // is preserved. Otherwise: the `, `-joined consumer set in the same order.
203
203
  if (chains) {
package/src/babel.js CHANGED
@@ -17,12 +17,17 @@
17
17
  // no esbuild pre-transform, Babel sees the original source exactly as the project's own
18
18
  // toolchain (e.g. Metro) would hand it over.
19
19
  //
20
+ // `stasis bundle --metro --babel` takes only the import aliases from that config (see
21
+ // createBabelAliases): the scan still reads each file's own source. `--babel-aliases` takes the same
22
+ // aliases from a JSON file instead, mapped here as the plugin maps them (createAliases), so nothing
23
+ // of the project's runs.
24
+ //
20
25
  // Babel is the PROJECT's dev dependency, not stasis's: @babel/core (and, for hermes, the
21
26
  // two transform plugins) resolve from the project directory, so the project pins its own
22
27
  // Babel toolchain and config semantics.
23
28
  import { existsSync } from 'node:fs'
24
29
  import { createRequire } from 'node:module'
25
- import { join } from 'node:path'
30
+ import { dirname, join, relative, resolve } from 'node:path'
26
31
 
27
32
  const require = createRequire(import.meta.url)
28
33
 
@@ -61,13 +66,13 @@ const TRANSFORMABLE_LOADERS = new Set(['js', 'ts', 'jsx', 'tsx'])
61
66
  // Resolved up front on the main thread so a missing install fails with instructions, not a
62
67
  // worker crash mid-build. Returns absolute paths: the worker loads @babel/core by path, and
63
68
  // plugin paths bypass Babel's own name resolution (which would look in the wrong dir).
64
- function resolveFromProject(projectDir, deps, flag) {
69
+ function resolveFromProject(projectDir, deps, flag, command = 'stasis build') {
65
70
  const projectRequire = createRequire(join(projectDir, 'noop.js'))
66
71
  try {
67
72
  return deps.map((dep) => projectRequire.resolve(dep))
68
73
  } catch (cause) {
69
74
  throw new Error(
70
- `stasis build: ${flag} needs ${deps.join(', ')} installed in the project ` +
75
+ `${command}: ${flag} needs ${deps.join(', ')} installed in the project ` +
71
76
  `(e.g. \`npm i -D ${deps.join(' ')}\`); resolution failed from ${projectDir}`,
72
77
  { cause }
73
78
  )
@@ -108,12 +113,7 @@ export function createHermesTransform({ projectDir, esbuild }) {
108
113
  // the original source. Its output must be esbuild-parseable js -- a config that leaves TS/JSX
109
114
  // in place fails the build in Babel or esbuild, which is the project's config to fix.
110
115
  export function createBabelConfigTransform({ projectDir }) {
111
- const configFile = ['babel.config.js', 'babel.config.cjs', 'babel.config.mjs', 'babel.config.json']
112
- .map((name) => join(projectDir, name))
113
- .find((file) => existsSync(file))
114
- if (!configFile) {
115
- throw new Error(`stasis build: --babel found no babel.config.(js|cjs|mjs|json) in ${projectDir}`)
116
- }
116
+ const configFile = findBabelConfig(projectDir, 'stasis build')
117
117
  const [babelPath] = resolveFromProject(projectDir, ['@babel/core'], '--babel')
118
118
  const { transformAsync } = require('./babel-worker.cjs')
119
119
  return async (source, { path, loader }) => {
@@ -129,3 +129,116 @@ export function createBabelConfigTransform({ projectDir }) {
129
129
  return { contents: result.code, loader: 'js' }
130
130
  }
131
131
  }
132
+
133
+ // The project's babel.config.(js|cjs|mjs|json), the one --babel takes.
134
+ function findBabelConfig(projectDir, command) {
135
+ const configFile = ['babel.config.js', 'babel.config.cjs', 'babel.config.mjs', 'babel.config.json']
136
+ .map((name) => join(projectDir, name))
137
+ .find((file) => existsSync(file))
138
+ if (!configFile) {
139
+ throw new Error(`${command}: --babel found no babel.config.(js|cjs|mjs|json) in ${projectDir}`)
140
+ }
141
+ return configFile
142
+ }
143
+
144
+ // The file a plugin item names babel-plugin-module-resolver by resolves into this.
145
+ const MODULE_RESOLVER = /[\\/]node_modules[\\/]babel-plugin-module-resolver[\\/]/u
146
+
147
+ // --babel for `stasis bundle --metro`: the import aliases babel-plugin-module-resolver applies to
148
+ // each file under the project's babel.config.*, loaded as Metro's transformer loads it (its `metro`
149
+ // caller, for `platform`) -- the config is project code, run here. The plugin's own resolvePath (or
150
+ // the config's custom one) maps each specifier, its `cwd` the project's where the config sets none,
151
+ // as Metro started there has it. Every instance the config lists, by name or as a value (`require`d
152
+ // or imported), counts, in order; one a preset adds doesn't.
153
+ // -> (file, specifier) => the specifier the plugin rewrites it to, else null
154
+ export function createBabelAliases({ projectDir, platform }) {
155
+ const configFile = findBabelConfig(projectDir, 'stasis bundle')
156
+ const [babelPath] = resolveFromProject(projectDir, ['@babel/core'], '--babel', 'stasis bundle')
157
+ const babel = require(babelPath)
158
+ const caller = { name: 'metro', bundler: 'metro', platform }
159
+ // The project's own copy, which a config passing the plugin as a value passes; none where the
160
+ // project installs none.
161
+ let projectPlugin
162
+ try {
163
+ projectPlugin = require(createRequire(join(projectDir, 'noop.js')).resolve('babel-plugin-module-resolver'))
164
+ } catch {
165
+ projectPlugin = null
166
+ }
167
+ // The module of a module-resolver plugin item, else null.
168
+ const moduleOf = (plugin) => {
169
+ const resolved = plugin.file?.resolved
170
+ if (resolved !== undefined) return MODULE_RESOLVER.test(resolved) ? require(resolved) : null
171
+ return plugin.value === projectPlugin?.default ? projectPlugin : null
172
+ }
173
+ // file -> [{ resolvePath, options }] of the module-resolver instances its config applies.
174
+ const byFile = new Map()
175
+ const aliasingOf = (file) => {
176
+ if (byFile.has(file)) return byFile.get(file)
177
+ let partial
178
+ try {
179
+ partial = babel.loadPartialConfig({ cwd: projectDir, root: projectDir, configFile, filename: file, caller })
180
+ } catch (cause) {
181
+ throw new Error(`stasis bundle: --babel could not load ${configFile} for ${file}`, { cause })
182
+ }
183
+ const instances = []
184
+ // No partial config: the config ignores the file.
185
+ for (const plugin of partial?.options.plugins ?? []) {
186
+ const module = moduleOf(plugin)
187
+ if (module === null) continue
188
+ const options = { cwd: projectDir, ...plugin.options }
189
+ instances.push({ resolvePath: typeof options.resolvePath === 'function' ? options.resolvePath : module.resolvePath, options })
190
+ }
191
+ byFile.set(file, instances)
192
+ return instances
193
+ }
194
+ return (file, specifier) => {
195
+ for (const { resolvePath, options } of aliasingOf(file)) {
196
+ const mapped = resolvePath(specifier, file, options)
197
+ // The first instance mapping it wins: the plugin marks the path it writes resolved, which
198
+ // later instances leave as it is.
199
+ if (mapped) return typeof mapped === 'string' && mapped !== specifier ? mapped : null
200
+ }
201
+ return null
202
+ }
203
+ }
204
+
205
+ // babel-plugin-module-resolver's path tests, as it writes them.
206
+ const isRelativePath = (path) => /^\.?\.\//u.test(path)
207
+ const toLocalPath = (path) => {
208
+ const local = path.replace(/\/index$/u, '')
209
+ return isRelativePath(local) ? local : `./${local}`
210
+ }
211
+ const escapeRegExp = (string) => string.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')
212
+
213
+ // --babel-aliases for `stasis bundle --metro`: the import aliases of `alias`, babel-plugin-module-resolver's
214
+ // `alias` option as data (a JSON file's), mapped as the plugin maps them with `cwd` its own, as
215
+ // createBabelAliases has it: a key starting with `^` or ending with `$` is a regular expression whose
216
+ // groups the value's `\N` take, any other matches the specifier it is or one it starts with and `/`,
217
+ // whose rest the value keeps; the first key matching wins. A value starting with `./` or `../` is a
218
+ // path from `cwd`, written relative to the importing file; any other is the specifier as it is.
219
+ // -> (file, specifier) => the specifier it rewrites it to, else null
220
+ export function createAliases(alias, cwd) {
221
+ const matchers = Object.entries(alias).map(([key, value]) => {
222
+ // As the plugin builds them: a key's own pattern, unflagged (`u` would refuse some it takes).
223
+ if (!key.startsWith('^') && !key.endsWith('$')) return [new RegExp(`^${escapeRegExp(key)}(/.*|)$`), ([, rest]) => `${value}${rest}`]
224
+ const parts = value.split('\\\\')
225
+ return [new RegExp(key), (groups) => parts.map((part) => part.replace(/\\\d+/gu, (n) => groups[n.slice(1)] || '')).join('\\')]
226
+ })
227
+ return (file, specifier) => {
228
+ if (isRelativePath(specifier)) return null
229
+ for (const [regExp, substitute] of matchers) {
230
+ const groups = regExp.exec(specifier)
231
+ if (groups === null) continue
232
+ return rewrite(file, specifier, substitute(groups), cwd)
233
+ }
234
+ return null
235
+ }
236
+ }
237
+
238
+ // `mapped`, the alias `specifier` from `file` maps to, as the plugin writes it: none where empty, a
239
+ // relative one (`./`, `../`) a path from `cwd` written relative to `file`, any other as it is.
240
+ function rewrite(file, specifier, mapped, cwd) {
241
+ if (!mapped) return null
242
+ const rewritten = isRelativePath(mapped) ? toLocalPath(relative(dirname(file), resolve(cwd, mapped)).replace(/\\/gu, '/')) : mapped
243
+ return rewritten === specifier ? null : rewritten
244
+ }