@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/src/scan.js CHANGED
@@ -5,10 +5,12 @@ import assert from 'node:assert/strict'
5
5
  import { packageType } from '@exodus/stasis-core/bundle-util'
6
6
  import { classifyExtension, classifyFormat, isTypeDeclaration, relativeEscapes } from '@exodus/stasis-core/util'
7
7
  import { inNodeModules, resolveTypescriptFallback, typescriptSiblings } from './resolve-typescript.js'
8
+ import { branchFolder, parseDefine } from './define.js'
8
9
  import { diskHost } from '@exodus/stasis-core/host'
9
10
 
10
11
  // Static require/import graph walker: parses source, never loads or executes user code.
11
- // Dynamic specifiers (`require(name)`, `import('./'+x)`) are recorded as unresolved.
12
+ // Dynamic specifiers (`require(name)`, `import('./'+x)`) are recorded as unresolved. With
13
+ // `define`, a branch the defined values keep from running is not walked (see define.js).
12
14
 
13
15
  // .jsx/.tsx need no flag: oxc parses them as JSX/TSX purely from the filename, so a reached one
14
16
  // -- e.g. a package whose React Native entry is src/index.tsx -- is parsed and carried like any .ts.
@@ -33,20 +35,12 @@ export function getParser() {
33
35
  return _parser
34
36
  }
35
37
 
36
- // flow-remove-types is an optional dependency, loaded lazily and only under --flow: it strips
37
- // Flow type syntax down to plain JS before oxc (which parses JS/TS, not Flow) sees it. A missing
38
- // dep is an env error, so surface it with an actionable install hint rather than a bare resolve throw.
38
+ // flow-remove-types is stasis's own dependency, resolved from stasis itself (never from the project
39
+ // being bundled) and loaded lazily, only under --flow: it strips Flow type syntax down to plain JS
40
+ // before oxc (which parses JS/TS, not Flow) sees it.
39
41
  let _flowRemoveTypes
40
42
  function getFlowRemoveTypes() {
41
- if (_flowRemoveTypes) return _flowRemoveTypes
42
- try {
43
- _flowRemoveTypes = createRequire(import.meta.url)('flow-remove-types')
44
- } catch (cause) {
45
- throw new Error(
46
- "--flow needs the optional 'flow-remove-types' dependency; install it (e.g. `npm i flow-remove-types`)",
47
- { cause }
48
- )
49
- }
43
+ _flowRemoveTypes ??= createRequire(import.meta.url)('flow-remove-types')
50
44
  return _flowRemoveTypes
51
45
  }
52
46
 
@@ -74,7 +68,9 @@ export function literalSpec(node) {
74
68
  }
75
69
 
76
70
  // Walks require()/import() calls only; ESM static imports/re-exports come from oxc module records.
77
- function findCallSpecifiers(ast, push) {
71
+ // `fold` (define.js's branchFolder, or null) names the children of a branch whose test folds: the
72
+ // side that can't run is never walked.
73
+ function findCallSpecifiers(ast, push, fold = null) {
78
74
  const visit = (node) => {
79
75
  if (!node || typeof node !== 'object') return
80
76
  if (Array.isArray(node)) {
@@ -82,6 +78,11 @@ function findCallSpecifiers(ast, push) {
82
78
  return
83
79
  }
84
80
  if (typeof node.type !== 'string') return
81
+ const live = fold?.(node)
82
+ if (live !== undefined) {
83
+ for (const c of live) visit(c)
84
+ return
85
+ }
85
86
 
86
87
  if (node.type === 'CallExpression') {
87
88
  const { callee, arguments: args } = node
@@ -120,8 +121,9 @@ function findCallSpecifiers(ast, push) {
120
121
  // -- still loads its module, so its edge is real. oxc's module records can't draw that line
121
122
  // (`import type { A }` and `import { type A }` yield identical all-isType entries, and
122
123
  // `export {} from` yields no entry at all), so the statements are read off the AST, where
123
- // importKind/exportKind carry it.
124
- function collectSpecifiers(program) {
124
+ // importKind/exportKind carry it. `defines` (parseDefine's) leave out the calls in branches they
125
+ // keep from running; static import statements are never in one.
126
+ function collectSpecifiers(program, defines = new Map()) {
125
127
  const specs = []
126
128
  for (const node of program.body) {
127
129
  if (node.type === 'ImportDeclaration') {
@@ -132,7 +134,7 @@ function collectSpecifiers(program) {
132
134
  if (node.exportKind !== 'type') specs.push({ kind: 'export-from', spec: node.source.value })
133
135
  }
134
136
  }
135
- findCallSpecifiers(program, (s) => specs.push(s))
137
+ findCallSpecifiers(program, (s) => specs.push(s), branchFolder(defines, program))
136
138
  return specs
137
139
  }
138
140
 
@@ -200,7 +202,9 @@ export class Scan {
200
202
  // are carried as opaque resources (bytes only) rather than rejected as un-carryable -- for graphs
201
203
  // that aren't fully loadable in JS (e.g. Metro consuming .png/.svg assets).
202
204
  // `host`: the filesystem the walk reads and resolves through (@exodus/stasis-core/host).
203
- constructor({ conditions = [], resolve = null, jsx = false, flow = false, typescript = false, typescriptPaths = null, typescriptResolve = null, resources = new Set(), host = diskHost } = {}) {
205
+ // `define` (each global name -> its value, see define.js): a require()/import() in a branch they
206
+ // keep from running (`if (__DEV__)` under `{ __DEV__: false }`) is no edge.
207
+ constructor({ conditions = [], resolve = null, jsx = false, flow = false, typescript = false, typescriptPaths = null, typescriptResolve = null, resources = new Set(), define, host = diskHost } = {}) {
204
208
  this.extraConditions = [...conditions]
205
209
  this.customResolve = resolve
206
210
  this.typescriptResolve = typescriptResolve
@@ -209,6 +213,7 @@ export class Scan {
209
213
  this.typescript = typescript
210
214
  this.typescriptPaths = typescriptPaths
211
215
  this.resources = resources
216
+ this.defines = parseDefine('scan', define)
212
217
  this.host = host
213
218
  }
214
219
 
@@ -289,10 +294,10 @@ export class Scan {
289
294
  return hit == null ? null : pathToFileURL(hit).toString()
290
295
  }
291
296
 
292
- // Strip Flow type syntax to plain JS via the optional flow-remove-types dep (resolved lazily; a
293
- // missing dep is an env error and propagates). Only invoked as a parse fallback (see #scanFile),
294
- // so plain-JS files never reach it. Returns the rewritten source, or null when the transform
295
- // itself fails on this file -- the caller then keeps oxc's original parse error.
297
+ // Strip Flow type syntax to plain JS via stasis's flow-remove-types (loaded lazily). Only invoked
298
+ // as a parse fallback (see #scanFile), so plain-JS files never reach it. Returns the rewritten
299
+ // source, or null when the transform itself fails on this file -- the caller then keeps oxc's
300
+ // original parse error.
296
301
  #stripFlow(src, file) {
297
302
  const flowRemoveTypes = getFlowRemoveTypes()
298
303
  try {
@@ -434,7 +439,7 @@ export class Scan {
434
439
  this.parseErrors.push({ url, format, message: parseError, recovered: true })
435
440
  }
436
441
 
437
- const specs = collectSpecifiers(parsed.program)
442
+ const specs = collectSpecifiers(parsed.program, this.defines)
438
443
 
439
444
  // The edge KIND picks the resolution context, not the parent's format: createRequire()d
440
445
  // require() inside ESM resolves under REQUIRE conditions, literal import() inside CJS under
@@ -5,6 +5,7 @@ import { readJson } from '@exodus/stasis-core/bundle-util'
5
5
  import { isAutoExcludedDir, isPlainObject, posixPathEscapes, relativeEscapes } from '@exodus/stasis-core/util'
6
6
  import { Vfs } from '@preventive/vfs'
7
7
  import { checkVfsOptions, fieldResolverFor } from '../cmd/bundle.js'
8
+ import { configuredBuilds } from '../cmd/bundle-options.js'
8
9
  import { foundrySourceDir } from '../loaders/foundry.js'
9
10
  import { resolveConditions } from '../resolve-fields.js'
10
11
  import { resolveTypescriptFallback, typescriptExportsTarget } from '../resolve-typescript.js'
@@ -124,15 +125,32 @@ export const KINDS = {
124
125
 
125
126
  const EMPTY = vfsHost(new Vfs())
126
127
 
128
+ // What a stasis.config.json's empty `entries` says of the directory holding it.
129
+ const CONFIGURED_NONE = 'has a stasis.config.json whose entries name none'
130
+
131
+ // -> { entries, none }: the entries a build of the project in `dir` (read through `host`) takes
132
+ // where none are given, as paths from `dir`, and what having none says of `dir`. Those its
133
+ // stasis.config.json's `entries` names, checked with `options` as the build checks them
134
+ // (configuredBuilds), where it has `entries`, whatever it names; else those of `kind` (KINDS'),
135
+ // with `options` then checked on their own, as the build checks them, which nothing completes.
136
+ export function defaultEntries(name, host, dir, kind, options) {
137
+ const configured = configuredBuilds(name, { cwd: dir, host, options })
138
+ if (configured !== null) return { entries: configured.entries, none: CONFIGURED_NONE }
139
+ checkVfsOptions(name, { ...options, entries: [kind.standIn], cwd: '/', host: EMPTY, fetched: false })
140
+ return { entries: kind.entries(host, dir, options), none: kind.none }
141
+ }
142
+
127
143
  // The build's checks of `options` before anything is fetched, over an empty tree, which never
128
144
  // decides them: for the package manager given, else for any; over the entries given, else over one
129
- // of the kind the default ones are. -> the PACKAGE_MANAGERS entry of the one given
145
+ // of the kind the default ones are. But for what one of them needs of another, which the options of
146
+ // an entry stasis.config.json names may set (`partial`), left to the build, which knows whether it
147
+ // names it. -> the PACKAGE_MANAGERS entry of the one given
130
148
  export function checkAhead(name, packageManager, options) {
131
149
  checkVersion(name, { packageManager, ...options })
132
150
  const pm = packageManager === undefined ? undefined : packageManagerOf(name, packageManager)
133
151
  const refusal = (entries) => {
134
152
  try {
135
- checkKind(name, checkVfsOptions(name, { ...options, entries, cwd: '/', host: EMPTY, fetched: false }), packageManager === undefined ? undefined : [packageManager])
153
+ checkKind(name, checkVfsOptions(name, { ...options, entries, cwd: '/', host: EMPTY, fetched: false, partial: true }), packageManager === undefined ? undefined : [packageManager])
136
154
  return null
137
155
  } catch (error) {
138
156
  return error
@@ -7,7 +7,7 @@ import { ArchiveError, unpack } from '@preventive/archive/tar.js'
7
7
  import { createClient } from '@preventive/upstream/github.js'
8
8
  import { vfsFromEntries } from '@preventive/vfs'
9
9
  import { buildVfsBundle } from '../cmd/bundle.js'
10
- import { KINDS, checkAhead } from './entries.js'
10
+ import { KINDS, checkAhead, defaultEntries } from './entries.js'
11
11
  import { checkCache, checkTarget, detectPackageManager, installedAlone, lockfileOf, lockfilesListed, noLockfile, packageManagerOf, vfsHost } from './tree.js'
12
12
 
13
13
  // As upstream's tree verification bounds a tarball's unpacked size.
@@ -168,7 +168,8 @@ async function repoTree(name, { github, sha, tag, directory, client, packageMana
168
168
  // A GitHub repo at a full commit, or the one `tag` names, the default branch's head without either,
169
169
  // as buildVfsBundle builds it: `directory` downloaded alone where it stands alone, else the whole
170
170
  // repo, and without a `packageManager`, the one whose lockfile installs it, where only one's does
171
- // (repoTree). Without `entries`, they are the ones suggestedEntries suggests. The bundle's paths are
171
+ // (repoTree). Without `entries`, they are the ones suggestedEntries suggests: those its
172
+ // stasis.config.json's `entries` names, where it has `entries`. The bundle's paths are
172
173
  // relative to `directory`, or for a JS bundle, to the innermost package directory at or above it
173
174
  // holding every file it bundles (buildJsBundle's innermostRoot), which is the project's root where
174
175
  // one is outside the others; `repo` names that directory and the commit. Nothing is read from disk:
@@ -185,8 +186,9 @@ export async function buildGitHubBundle({ github, sha, tag, directory, client, p
185
186
  let { entries } = options
186
187
  if (entries === undefined) {
187
188
  // As suggestedEntries suggests them, from the tree at hand.
188
- entries = tree.kind.entries(tree.host, tree.cwd, options)
189
- if (entries.length === 0) throw new Error(`${tree.where}: no entries given, and ${directory || 'the repo root'} ${tree.kind.none}`)
189
+ const suggested = defaultEntries('buildGitHubBundle', tree.host, tree.cwd, tree.kind, options)
190
+ entries = suggested.entries
191
+ if (entries.length === 0) throw new Error(`${tree.where}: no entries given, and ${directory || 'the repo root'} ${suggested.none}`)
190
192
  }
191
193
  const repo = { github, commit: tree.sha }
192
194
  const built = await buildVfsBundle({ ...options, entries, packageManager: tree.packageManager, vfs: tree.vfs, cwd: tree.cwd, innermostRoot: true, repo, client })
@@ -200,5 +202,5 @@ export async function buildGitHubBundle({ github, sha, tag, directory, client, p
200
202
  // buildGitHubBundle downloads it.
201
203
  export async function suggestedRepoEntries(repo, resolution) {
202
204
  const tree = await repoTree('suggestedEntries', repo, resolution)
203
- return tree.kind.entries(tree.host, tree.cwd, resolution)
205
+ return defaultEntries('suggestedEntries', tree.host, tree.cwd, tree.kind, resolution).entries
204
206
  }
@@ -395,10 +395,10 @@ const githubRoot = (url) => {
395
395
 
396
396
  // Each dependency of `bundle`, its paths from `root`, at the commit the tree (layOutTree's) installs
397
397
  // it from, where deptree names a full one: an npm package at its gitHead, which the registry's
398
- // version document names, a commit of the repository its own package.json names, so taken only
399
- // where the bundle records that one; a Soldeer git dependency at its lockfile's `rev`, the root of
400
- // the repository it is fetched from, where that is a GitHub one. Metadata, as `repo` is: the
401
- // publisher's word, held to no repository.
398
+ // version document names, over the one its package.json may name (packageRepo), a commit of the
399
+ // repository its own package.json names, so taken only where the bundle records that one; a
400
+ // Soldeer git dependency at its lockfile's `rev`, the root of the repository it is fetched from,
401
+ // where that is a GitHub one. Metadata, as `repo` is: the publisher's word, held to no repository.
402
402
  export function pinCommits(bundle, root, { root: from, installed }) {
403
403
  const byDir = new Map(installed.map((pkg) => [posix.relative(root, posix.join(from, pkg.path)), pkg]))
404
404
  for (const [dir, info] of bundle.modules) {
package/src/vfs-bundle.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { posix } from 'node:path'
2
2
 
3
3
  import { Vfs } from '@preventive/vfs'
4
- import { KINDS, checkAhead } from './vfs-bundle/entries.js'
4
+ import { KINDS, checkAhead, defaultEntries } from './vfs-bundle/entries.js'
5
5
  import { suggestedRepoEntries } from './vfs-bundle/github.js'
6
6
  import { NODE_MODULES_MANAGERS, checkCache, checkTarget, checkVfs, detectPackageManager, loadTree, packageManagerFor, vfsHost } from './vfs-bundle/tree.js'
7
7
 
@@ -58,14 +58,15 @@ export async function loadNodeModules({ vfs, packageManager, cwd = '/', packageM
58
58
  }
59
59
 
60
60
  // -> the entries buildGitHubBundle takes where none are given, as paths from the project's
61
- // directory, of the kind its package manager builds: `packageManager` if given, else the one
62
- // detected as the build detects it. For pnpm and yarn 1, the entry points its package.json names,
63
- // resolved as the build resolves them with the same `conditions`, `mainFields`, `metro`,
64
- // `platforms` and `typescript` (packageEntries); for Soldeer, its .sol entry points by name
65
- // and layout (solidityEntries). The options are checked as the build checks them, and `os`, the
66
- // one the build is for, detects the package manager as there. Of the project held in `vfs`, from
67
- // `cwd`; or of a GitHub repo, `{ github, sha, tag, directory, client }` as buildGitHubBundle takes
68
- // them, downloaded as it downloads them.
61
+ // directory: those its stasis.config.json's `entries` names, where it has `entries` (none of an
62
+ // empty one), checked with the options as the build checks them; else of the kind its package
63
+ // manager builds: `packageManager` if given, else the one detected as the build detects it. For
64
+ // pnpm and yarn 1, the entry points its package.json names, resolved as the build resolves them
65
+ // with the same `conditions`, `mainFields`, `metro`, `platforms` and `typescript` (packageEntries);
66
+ // for Soldeer, its .sol entry points by name and layout (solidityEntries). The options are checked
67
+ // as the build checks them, and `os`, the one the build is for, detects the package manager as
68
+ // there. Of the project held in `vfs`, from `cwd`; or of a GitHub repo, `{ github, sha, tag,
69
+ // directory, client }` as buildGitHubBundle takes them, downloaded as it downloads them.
69
70
  export async function suggestedEntries({ vfs, cwd = '/', packageManager, conditions, mainFields, metro, platforms, jsx, typescript, os, ...repo } = {}) {
70
71
  checkTarget('suggestedEntries', { os })
71
72
  const resolution = { conditions, mainFields, metro, platforms, jsx, typescript }
@@ -76,5 +77,5 @@ export async function suggestedEntries({ vfs, cwd = '/', packageManager, conditi
76
77
  const host = vfsHost(vfs)
77
78
  const at = posix.resolve('/', cwd)
78
79
  const pm = checkAhead('suggestedEntries', packageManager ?? detectPackageManager('suggestedEntries', host, at, { os }), resolution)
79
- return KINDS[pm.kind].entries(host, at, resolution)
80
+ return defaultEntries('suggestedEntries', host, at, KINDS[pm.kind], resolution).entries
80
81
  }