@exodus/stasis 1.0.0-beta.9 → 1.0.0-rc.0
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/README.md +6 -2
- package/bin/stasis.js +222 -334
- package/package.json +38 -14
- package/src/audit-corrections.js +11 -42
- package/src/audit.js +256 -212
- package/src/babel.js +119 -82
- package/src/bundle-from-lockfile.js +9 -21
- package/src/bundle-reader.js +24 -8
- package/src/bundle.js +0 -3
- package/src/cmd/build.js +211 -117
- package/src/cmd/bundle-options.js +347 -0
- package/src/cmd/bundle.js +1664 -1001
- package/src/cmd/diff.js +1 -4
- package/src/cmd/github-bundle.js +48 -21
- package/src/cmd/output.js +24 -12
- package/src/cmd/sbom.js +6 -9
- package/src/cmd/tokens.js +60 -0
- package/src/define.js +218 -0
- package/src/diff.js +73 -129
- package/src/esbuild.js +0 -4
- package/src/flow.js +27 -0
- package/src/installed.js +265 -0
- package/src/json-stream.js +4 -9
- package/src/loader-mock.js +3 -8
- package/src/loader.js +1 -5
- package/src/loaders/bash.js +43 -120
- package/src/loaders/cargo.js +301 -808
- package/src/loaders/foundry.js +112 -290
- package/src/loaders/paths.js +15 -26
- package/src/loaders/php.js +211 -492
- package/src/loaders/rust.js +518 -1461
- package/src/loaders/solidity-ownership.js +51 -142
- package/src/loaders/solidity.js +42 -188
- package/src/loaders/toml.js +7 -17
- package/src/lockfile.js +0 -3
- package/src/metro-assets.js +41 -0
- package/src/metro-resolver.js +58 -133
- package/src/metro-transformer.js +0 -6
- package/src/metro.js +0 -4
- package/src/mock.js +32 -80
- package/src/parse.js +8 -7
- package/src/prune.js +0 -3
- package/src/resolve-fields.js +152 -249
- package/src/resolve-node.js +29 -45
- package/src/resolve-typescript.js +166 -298
- package/src/rollup.js +0 -4
- package/src/run-installed.js +10 -0
- package/src/sbom.js +70 -97
- package/src/scan.js +240 -282
- package/src/sixel.js +310 -0
- package/src/table.js +95 -0
- package/src/validate-notes.d.ts +19 -0
- package/src/validate-notes.js +72 -0
- package/src/validate.d.ts +159 -0
- package/src/validate.js +1315 -0
- package/src/vfs-bundle/entries.js +50 -46
- package/src/vfs-bundle/github.js +114 -94
- package/src/vfs-bundle/glob.js +379 -0
- package/src/vfs-bundle/lazy.js +99 -0
- package/src/vfs-bundle/prisma.js +235 -105
- package/src/vfs-bundle/soldeer.js +28 -49
- package/src/vfs-bundle/tree.js +418 -277
- package/src/vfs-bundle/yarnclean.js +79 -0
- package/src/vfs-bundle.js +24 -55
- package/src/webpack.js +0 -4
- package/src/why.js +79 -231
- package/src/installed-commits.js +0 -182
package/src/cmd/build.js
CHANGED
|
@@ -6,34 +6,34 @@ import { spawnSync } from 'node:child_process'
|
|
|
6
6
|
|
|
7
7
|
import { Bundle } from '@exodus/stasis-core/bundle'
|
|
8
8
|
import { State } from '@exodus/stasis-core/state'
|
|
9
|
+
import { CONFIG_FILE, isPlainObject, JS_EXTENSIONS, toPosix } from '@exodus/stasis-core/util'
|
|
9
10
|
import { StasisEsbuild } from '@exodus/stasis-plugins/esbuild'
|
|
11
|
+
import { bundleDirHost } from '@exodus/stasis-plugins/metro-native'
|
|
12
|
+
import { assetsDestFiles } from '@preventive/rn/assets-dest.js'
|
|
13
|
+
import { assetData, assetModule } from '@preventive/rn/metro-assets.js'
|
|
10
14
|
import { HERMES_UNSUPPORTED, createBabelConfigTransform, createHermesTransform } from '../babel.js'
|
|
11
15
|
import { bundleFromLockfile } from '../bundle-from-lockfile.js'
|
|
16
|
+
import { METRO_RELEASE_DEFINE } from '../define.js'
|
|
17
|
+
import { FLOW_EXTS, hasFlowPragma, stripFlowTypes } from '../flow.js'
|
|
18
|
+
import { ASSET_REGISTRY, assetRegistryResolver } from '../metro-assets.js'
|
|
12
19
|
import { parseFileWithKind } from '../parse.js'
|
|
13
20
|
import { writeFile } from './output.js'
|
|
14
21
|
|
|
15
22
|
export { bundleFromLockfile }
|
|
16
23
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
// Allowlist (not blocklist) of per-file formats `stasis build` accepts, so a bundle
|
|
20
|
-
// format added later fails closed here rather than in a cryptic esbuild error.
|
|
24
|
+
// An allowlist, so that a bundle format added later fails closed here rather than in a cryptic esbuild error.
|
|
21
25
|
const BUILDABLE_FORMATS = new Set([
|
|
22
26
|
'module', 'commonjs', 'json', 'module-typescript', 'commonjs-typescript',
|
|
23
27
|
'resource', 'resource:base64', 'directory', 'stat:file', 'stat:directory',
|
|
24
28
|
])
|
|
25
29
|
|
|
26
|
-
// esbuild is an optional peer
|
|
27
|
-
// to a global one.
|
|
30
|
+
// esbuild is an optional peer dependency: the local install's, else a global one.
|
|
28
31
|
async function importEsbuild() {
|
|
29
32
|
let mod
|
|
30
33
|
try {
|
|
31
34
|
mod = await import('esbuild')
|
|
32
35
|
} catch (cause) {
|
|
33
|
-
|
|
34
|
-
if (cause?.code !== 'ERR_MODULE_NOT_FOUND' && cause?.code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED') {
|
|
35
|
-
throw cause
|
|
36
|
-
}
|
|
36
|
+
if (cause?.code !== 'ERR_MODULE_NOT_FOUND' && cause?.code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED') throw cause
|
|
37
37
|
const globalMain = resolveGlobalEsbuild()
|
|
38
38
|
if (!globalMain) {
|
|
39
39
|
throw new Error(
|
|
@@ -45,41 +45,31 @@ async function importEsbuild() {
|
|
|
45
45
|
}
|
|
46
46
|
mod = await import(pathToFileURL(globalMain).href)
|
|
47
47
|
}
|
|
48
|
-
// A globally-imported CJS copy may land its exports on `default
|
|
48
|
+
// A globally-imported CJS copy may land its exports on `default`.
|
|
49
49
|
return typeof mod.build === 'function' ? mod : mod.default
|
|
50
50
|
}
|
|
51
51
|
|
|
52
52
|
function resolveGlobalEsbuild() {
|
|
53
|
-
const
|
|
54
|
-
['npm', ['root', '-g']],
|
|
55
|
-
['pnpm', ['root', '-g']],
|
|
56
|
-
['yarn', ['global', 'dir']],
|
|
57
|
-
]
|
|
58
|
-
for (const [cmd, args] of probes) {
|
|
53
|
+
for (const [cmd, args] of [['npm', ['root', '-g']], ['pnpm', ['root', '-g']], ['yarn', ['global', 'dir']]]) {
|
|
59
54
|
let out
|
|
60
55
|
try {
|
|
61
56
|
out = spawnSync(cmd, args, { encoding: 'utf8' })
|
|
62
57
|
} catch {
|
|
63
58
|
continue
|
|
64
59
|
}
|
|
65
|
-
|
|
66
|
-
const base = out.stdout.trim()
|
|
60
|
+
const base = out?.status === 0 ? out.stdout?.trim() : undefined
|
|
67
61
|
if (!base) continue
|
|
68
|
-
// `npm/pnpm root -g` print the global node_modules
|
|
69
|
-
// dir whose node_modules holds the packages. Try both shapes.
|
|
62
|
+
// `npm/pnpm root -g` print the global node_modules; `yarn global dir` a dir whose node_modules holds them.
|
|
70
63
|
for (const nm of [base, join(base, 'node_modules')]) {
|
|
71
64
|
if (!existsSync(join(nm, 'esbuild', 'package.json'))) continue
|
|
72
65
|
try {
|
|
73
66
|
return createRequire(join(nm, 'noop.js')).resolve('esbuild')
|
|
74
|
-
} catch {
|
|
75
|
-
}
|
|
67
|
+
} catch { /* try the next */ }
|
|
76
68
|
}
|
|
77
69
|
}
|
|
78
70
|
return undefined
|
|
79
71
|
}
|
|
80
72
|
|
|
81
|
-
// Preconditions independent of which entry we build. Per-entry language checks are deferred
|
|
82
|
-
// to assertBuildableEntry, once selectEntry has picked one.
|
|
83
73
|
function assertBuildableArtifact(artifact, label) {
|
|
84
74
|
if (artifact.config.scope !== 'full') {
|
|
85
75
|
throw new Error(
|
|
@@ -87,120 +77,168 @@ function assertBuildableArtifact(artifact, label) {
|
|
|
87
77
|
`node_modules-scope artifacts omit the entry and workspace code, so there is nothing to build.`
|
|
88
78
|
)
|
|
89
79
|
}
|
|
90
|
-
if (artifact.entries.size === 0) {
|
|
91
|
-
throw new Error(`stasis build: ${label} declares no entries to build`)
|
|
92
|
-
}
|
|
80
|
+
if (artifact.entries.size === 0) throw new Error(`stasis build: ${label} declares no entries to build`)
|
|
93
81
|
}
|
|
94
82
|
|
|
95
|
-
//
|
|
96
|
-
// (all conditions buckets; a --metro edge's per-platform targets included).
|
|
83
|
+
// As esbuild loads them: every conditions bucket's edges, every platform's target (a Set visits what is added to it).
|
|
97
84
|
function reachableFiles(entry, imports) {
|
|
98
85
|
const seen = new Set([entry])
|
|
99
|
-
const
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
const specifiers = byParent.get(parent)
|
|
104
|
-
if (specifiers === undefined) continue
|
|
105
|
-
for (const [, target] of specifiers) {
|
|
106
|
-
// A plain edge is a file string; a --metro edge is a {platform: file} Map.
|
|
107
|
-
const targets = typeof target === 'string' ? [target] : [...target.values()]
|
|
108
|
-
for (const file of targets) {
|
|
109
|
-
if (!seen.has(file)) {
|
|
110
|
-
seen.add(file)
|
|
111
|
-
stack.push(file)
|
|
112
|
-
}
|
|
113
|
-
}
|
|
86
|
+
for (const parent of seen) {
|
|
87
|
+
for (const byParent of imports.values()) {
|
|
88
|
+
for (const target of byParent.get(parent)?.values() ?? []) {
|
|
89
|
+
for (const file of typeof target === 'string' ? [target] : target.values()) seen.add(file)
|
|
114
90
|
}
|
|
115
91
|
}
|
|
116
92
|
}
|
|
117
93
|
return seen
|
|
118
94
|
}
|
|
119
95
|
|
|
120
|
-
//
|
|
121
|
-
// it must be buildable. A non-JS file elsewhere (another entry, or a `stasis add` attachment)
|
|
122
|
-
// isn't reached, so it doesn't block the build. imports/formats are null on a legacy lockfile.
|
|
96
|
+
// Only what the entry reaches must be buildable: another entry or a `stasis add` attachment doesn't block it.
|
|
123
97
|
function assertBuildableEntry(artifact, entry, label) {
|
|
124
|
-
if (!
|
|
98
|
+
if (!JS_EXTENSIONS.has(extname(entry))) {
|
|
125
99
|
throw new Error(`stasis build only builds JavaScript/TypeScript entries (esbuild); got non-JS entry '${entry}' in ${label}`)
|
|
126
100
|
}
|
|
127
101
|
const reachable = reachableFiles(entry, artifact.imports ?? new Map())
|
|
128
|
-
// A reachable resource (plugin captures DO record asset edges) stays allowed via BUILDABLE_FORMATS;
|
|
129
|
-
// an entry that imports an unbuildable asset fails later at esbuild, not here.
|
|
130
102
|
for (const [file, format] of artifact.formats ?? new Map()) {
|
|
131
|
-
if (
|
|
132
|
-
if (!BUILDABLE_FORMATS.has(format)) {
|
|
103
|
+
if (reachable.has(file) && !BUILDABLE_FORMATS.has(format)) {
|
|
133
104
|
throw new Error(`stasis build only supports JavaScript/TypeScript bundles (esbuild); ${label} carries a '${format}' file (${file})`)
|
|
134
105
|
}
|
|
135
106
|
}
|
|
136
107
|
}
|
|
137
108
|
|
|
138
|
-
// Pick which recorded entry to build; required only when several are recorded. Matched
|
|
139
|
-
// against the recorded project-relative entries (verbatim, `./`-stripped, or cwd-relative).
|
|
140
109
|
function selectEntry(entryArg, entries, { cwd, root, label }) {
|
|
141
110
|
const recorded = [...entries]
|
|
142
111
|
const list = recorded.map((e) => ` ${e}`).join('\n')
|
|
143
112
|
if (entryArg === undefined) {
|
|
144
113
|
if (recorded.length === 1) return recorded[0]
|
|
145
|
-
// length === 0 is impossible here (assertBuildableArtifact required >= 1 entry).
|
|
146
114
|
throw new Error(`stasis build: ${label} has ${recorded.length} entry points; pass one as the second argument:\n${list}`)
|
|
147
115
|
}
|
|
148
|
-
const candidates = new Set([
|
|
149
|
-
entryArg,
|
|
150
|
-
entryArg.replace(/^\.\//u, ''),
|
|
151
|
-
relative(root, resolve(cwd, entryArg)).split(sep).join('/'),
|
|
152
|
-
])
|
|
116
|
+
const candidates = new Set([entryArg, entryArg.replace(/^\.\//u, ''), relative(root, resolve(cwd, entryArg)).split(sep).join('/')])
|
|
153
117
|
const match = recorded.find((e) => candidates.has(e))
|
|
154
|
-
if (match === undefined) {
|
|
155
|
-
throw new Error(`stasis build: '${entryArg}' is not an entry point of ${label}; available:\n${list}`)
|
|
156
|
-
}
|
|
118
|
+
if (match === undefined) throw new Error(`stasis build: '${entryArg}' is not an entry point of ${label}; available:\n${list}`)
|
|
157
119
|
return match
|
|
158
120
|
}
|
|
159
121
|
|
|
160
|
-
//
|
|
161
|
-
// filesystem discovery (no package.json walk, no on-disk config, no stray stasis.code.br).
|
|
122
|
+
// A bundle-load State serving `bundle`, with no discovery on disk (no package.json, config or stray stasis.code.br).
|
|
162
123
|
function loadStateForBundle(root, bundle) {
|
|
163
124
|
const state = new State(root, { bundle: 'load', lock: 'ignore', scope: bundle.config.scope, skipDiscovery: true })
|
|
164
|
-
|
|
165
|
-
|
|
125
|
+
state.sources = new Map()
|
|
126
|
+
state.resources = new Map()
|
|
166
127
|
for (const [file, content] of bundle.sources) {
|
|
167
|
-
if (Bundle.isResourceFormat(bundle.formats.get(file))) resources.set(file, content)
|
|
168
|
-
else sources.set(file, content)
|
|
128
|
+
if (Bundle.isResourceFormat(bundle.formats.get(file))) state.resources.set(file, content)
|
|
129
|
+
else state.sources.set(file, content)
|
|
169
130
|
}
|
|
170
|
-
state.sources = sources
|
|
171
|
-
state.resources = resources
|
|
172
131
|
state.formats = bundle.formats
|
|
173
132
|
state.imports = bundle.imports
|
|
174
133
|
state.entries = new Set(bundle.entries)
|
|
175
|
-
// Not state.
|
|
176
|
-
// consumer narrows against state.modules -- which is empty here -- so copying it would be inert.
|
|
177
|
-
// Not state.modules: the load path never reads it (only the capture paths write it).
|
|
134
|
+
// Not state.modules or state.executable: the load path reads neither.
|
|
178
135
|
return state
|
|
179
136
|
}
|
|
180
137
|
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
//
|
|
138
|
+
const asBytes = (source) => (Buffer.isBuffer(source) ? source : Buffer.from(source))
|
|
139
|
+
|
|
140
|
+
// The bytes the artifact carries for `file`, verified by getFile.
|
|
141
|
+
const readCarried = (state, file) => asBytes(state.getFile(pathToFileURL(resolve(state.root, file)).toString()).source)
|
|
142
|
+
|
|
143
|
+
// Each Metro asset served as the module Metro builds of it, its require of the registry added as Metro adds it.
|
|
144
|
+
function metroAssetResource(state, platform, built) {
|
|
145
|
+
const listing = bundleDirHost(state)
|
|
146
|
+
const registryFor = assetRegistryResolver(platform, state.sources)
|
|
147
|
+
return (source, { path }) => {
|
|
148
|
+
const rel = toPosix(state.relative(path))
|
|
149
|
+
const host = {
|
|
150
|
+
readdir: (dir) => listing.readdir(dir).map(({ name }) => name),
|
|
151
|
+
readFile: (file) => (file === path ? asBytes(source) : readCarried(state, file)),
|
|
152
|
+
}
|
|
153
|
+
const data = assetData(path, { urlPath: rel, platform, host })
|
|
154
|
+
state.addImport(pathToFileURL(path).href, ASSET_REGISTRY, pathToFileURL(resolve(state.root, registryFor(rel))).href)
|
|
155
|
+
built.set(rel, data)
|
|
156
|
+
return { contents: assetModule(data, ASSET_REGISTRY), loader: 'js' }
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// --flow, as Metro's Babel builds a file: Flow types stripped from a file marked `@flow`, else only where
|
|
161
|
+
// esbuild can't parse it; what still doesn't parse fails the build in esbuild.
|
|
162
|
+
function createFlowTransform(esbuild) {
|
|
163
|
+
return async (source, { path, loader }) => {
|
|
164
|
+
if (!FLOW_EXTS.has(extname(path))) return undefined
|
|
165
|
+
const text = String(source)
|
|
166
|
+
if (!hasFlowPragma(text)) {
|
|
167
|
+
try {
|
|
168
|
+
await esbuild.transform(text, { loader, sourcefile: path, logLevel: 'silent' })
|
|
169
|
+
return undefined
|
|
170
|
+
} catch { /* stripped below */ }
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
return { contents: stripFlowTypes(text, { removeEmptyImports: true }), loader }
|
|
174
|
+
} catch {
|
|
175
|
+
return undefined
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const chainTransforms = (first, second) => async (source, file) => {
|
|
181
|
+
const firstMade = await first(source, file)
|
|
182
|
+
return (await second(firstMade?.contents ?? source, { ...file, loader: firstMade?.loader ?? file.loader })) ?? firstMade
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// `entry`'s options in the stasis.config.json the artifact carries that say how its code is built, or null.
|
|
186
|
+
function configEntryOptions(state, entry) {
|
|
187
|
+
if (!state.sources.has(CONFIG_FILE) && !state.resources.has(CONFIG_FILE)) return null
|
|
188
|
+
let config
|
|
189
|
+
try {
|
|
190
|
+
config = JSON.parse(readCarried(state, CONFIG_FILE).toString('utf8'))
|
|
191
|
+
} catch (cause) {
|
|
192
|
+
throw new Error(`stasis build: the artifact's ${CONFIG_FILE} is not valid JSON`, { cause })
|
|
193
|
+
}
|
|
194
|
+
const entries = config?.entries
|
|
195
|
+
if (entries === undefined) return null
|
|
196
|
+
if (!isPlainObject(entries)) throw new Error(`stasis build: the artifact's ${CONFIG_FILE}: entries must be an object`)
|
|
197
|
+
const name = Object.keys(entries).find((key) => toPosix(relative(state.root, resolve(state.root, key))) === entry)
|
|
198
|
+
if (name === undefined) return null
|
|
199
|
+
const what = `the artifact's ${CONFIG_FILE}: entries ${JSON.stringify(name)}`
|
|
200
|
+
const options = entries[name]
|
|
201
|
+
if (!isPlainObject(options)) throw new Error(`stasis build: ${what} must be an object of options`)
|
|
202
|
+
for (const flag of ['jsx', 'flow', 'metro']) {
|
|
203
|
+
if (options[flag] !== undefined && typeof options[flag] !== 'boolean') throw new Error(`stasis build: ${what}: ${flag} must be true or false`)
|
|
204
|
+
}
|
|
205
|
+
const strings = (flag) => {
|
|
206
|
+
const value = options[flag] ?? []
|
|
207
|
+
if (typeof value !== 'string' && !(Array.isArray(value) && value.every((v) => typeof v === 'string'))) {
|
|
208
|
+
throw new Error(`stasis build: ${what}: ${flag} must be a string or an array of strings`)
|
|
209
|
+
}
|
|
210
|
+
return [value].flat()
|
|
211
|
+
}
|
|
212
|
+
const define = {}
|
|
213
|
+
for (const pair of strings('define')) {
|
|
214
|
+
const eq = pair.indexOf('=')
|
|
215
|
+
if (eq <= 0) throw new Error(`stasis build: ${what}: define must be KEY=VALUE (got '${pair}')`)
|
|
216
|
+
define[pair.slice(0, eq)] = pair.slice(eq + 1)
|
|
217
|
+
}
|
|
218
|
+
let platforms
|
|
219
|
+
if (options.metro === true) {
|
|
220
|
+
platforms = [...new Set(strings('platforms').flatMap((v) => v.split(',')).map((v) => v.trim()).filter(Boolean))]
|
|
221
|
+
if (platforms.length === 0) throw new Error(`stasis build: ${what} sets metro but names no platforms`)
|
|
222
|
+
}
|
|
223
|
+
return { name, jsx: options.jsx === true, flow: options.flow === true, define, platforms }
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// Run `stasis build`: esbuild over one recorded entry, following the artifact's recorded import graph exactly,
|
|
227
|
+
// not esbuild's resolver: `external` only steers the specifiers it doesn't record.
|
|
184
228
|
export async function buildCommand({
|
|
185
|
-
cwd = process.cwd(),
|
|
186
|
-
|
|
187
|
-
entry,
|
|
188
|
-
output,
|
|
189
|
-
format,
|
|
190
|
-
platform = 'node',
|
|
191
|
-
babel = false,
|
|
192
|
-
minify = false,
|
|
193
|
-
sourcemap = false,
|
|
194
|
-
define = {},
|
|
195
|
-
external = [],
|
|
196
|
-
loader = {},
|
|
229
|
+
cwd = process.cwd(), artifact, entry, output, format, platform = 'node', babel = false, flow = false, minify = false,
|
|
230
|
+
sourcemap = false, define = {}, external = [], loader = {}, metro, assetsDest,
|
|
197
231
|
} = {}) {
|
|
198
232
|
if (!artifact) throw new Error('stasis build: an artifact (bundle or lockfile) is required')
|
|
199
233
|
if (!output) throw new Error('stasis build: --output is required (a .js/.cjs/.mjs file, or a directory)')
|
|
200
234
|
if (!Array.isArray(external)) throw new Error('stasis build: external must be an array of esbuild patterns')
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
235
|
+
if (metro !== undefined && (typeof metro !== 'string' || !/^[^/,]+$/u.test(metro))) {
|
|
236
|
+
throw new Error(`stasis build: --metro takes the platform to build for, e.g. --metro=ios (got '${metro}')`)
|
|
237
|
+
}
|
|
238
|
+
if (flow && babel) {
|
|
239
|
+
throw new Error('stasis build: --babel hands the project\'s Babel config each file as it is, Flow included, for it to compile; --flow strips Flow before esbuild without it -- pass one')
|
|
240
|
+
}
|
|
241
|
+
// --platform=hermes is stasis's target, esbuild's 'neutral': code downleveled to Hermes' dialect, and no ESM.
|
|
204
242
|
const hermes = platform === 'hermes'
|
|
205
243
|
format ??= hermes ? 'iife' : 'esm'
|
|
206
244
|
if (hermes && format === 'esm') {
|
|
@@ -210,31 +248,70 @@ export async function buildCommand({
|
|
|
210
248
|
const { kind, artifact: parsed } = parseFileWithKind(artifactAbs)
|
|
211
249
|
assertBuildableArtifact(parsed, artifact)
|
|
212
250
|
|
|
213
|
-
//
|
|
214
|
-
// are read + verified from there.
|
|
251
|
+
// Paths are the artifact's directory's, where a lockfile's sources are read and verified.
|
|
215
252
|
const root = dirname(artifactAbs)
|
|
216
253
|
const selectedEntry = selectEntry(entry, parsed.entries, { cwd, root, label: artifact })
|
|
217
254
|
assertBuildableEntry(parsed, selectedEntry, artifact)
|
|
218
255
|
|
|
219
256
|
const bundle = kind === 'lockfile' ? bundleFromLockfile(parsed, { root }) : parsed
|
|
220
257
|
const state = loadStateForBundle(root, bundle)
|
|
221
|
-
// Make the entry absolute against the State's root so resolution is independent of process cwd.
|
|
222
258
|
const entryPoint = resolve(state.root, selectedEntry)
|
|
223
259
|
|
|
260
|
+
// The config's options for the entry, under the flags given (flow not under --babel, whose config compiles it).
|
|
261
|
+
const configured = configEntryOptions(state, selectedEntry)
|
|
262
|
+
if (configured !== null) {
|
|
263
|
+
const taken = []
|
|
264
|
+
if (configured.jsx && loader['.js'] === undefined) {
|
|
265
|
+
loader = { ...loader, '.js': 'jsx' }
|
|
266
|
+
taken.push('--loader=.js:jsx')
|
|
267
|
+
}
|
|
268
|
+
if (configured.flow && !flow && !babel) {
|
|
269
|
+
flow = true
|
|
270
|
+
taken.push('--flow')
|
|
271
|
+
}
|
|
272
|
+
for (const [key, value] of Object.entries(configured.define)) {
|
|
273
|
+
if (Object.hasOwn(define, key)) continue
|
|
274
|
+
define = { ...define, [key]: value }
|
|
275
|
+
taken.push(`--define=${key}=${value}`)
|
|
276
|
+
}
|
|
277
|
+
const { platforms } = configured
|
|
278
|
+
if (platforms !== undefined) {
|
|
279
|
+
const choices = platforms.map((name) => `--metro=${name}`).join(' or ')
|
|
280
|
+
const what = `${CONFIG_FILE} bundles ${selectedEntry} for ${platforms.join(', ')}`
|
|
281
|
+
if (metro === undefined && platforms.length > 1) throw new Error(`stasis build: ${what}: pass ${choices}`)
|
|
282
|
+
if (metro !== undefined && !platforms.includes(metro)) throw new Error(`stasis build: --metro=${metro}, but ${what} alone: pass ${choices}`)
|
|
283
|
+
if (metro === undefined) {
|
|
284
|
+
metro = platforms[0]
|
|
285
|
+
taken.push(`--metro=${metro}`)
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
if (taken.length > 0) console.warn(`[stasis] ${selectedEntry}: ${taken.join(' ')}, as ${CONFIG_FILE}'s entries ${JSON.stringify(configured.name)} sets`)
|
|
289
|
+
}
|
|
290
|
+
// As `stasis bundle --metro` reads the files; METRO_RELEASE_DEFINE's names too, since outside Metro's
|
|
291
|
+
// prelude `__DEV__` is no global at all.
|
|
292
|
+
if (metro !== undefined) {
|
|
293
|
+
if (loader['.js'] === undefined) loader = { ...loader, '.js': 'jsx' }
|
|
294
|
+
if (!babel) flow = true
|
|
295
|
+
for (const [key, value] of Object.entries(METRO_RELEASE_DEFINE)) {
|
|
296
|
+
if (!Object.hasOwn(define, key)) define = { ...define, [key]: JSON.stringify(value) }
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
if (assetsDest !== undefined && metro === undefined) {
|
|
300
|
+
throw new Error('stasis build: --assets-dest copies the assets --metro builds; pass --metro=PLATFORM with it')
|
|
301
|
+
}
|
|
302
|
+
|
|
224
303
|
const esbuild = await importEsbuild()
|
|
225
|
-
// Per-file code rewrites the plugin applies before esbuild parses a served file:
|
|
226
|
-
// --babel runs the project's own babel.config.* over the original source (no esbuild
|
|
227
|
-
// pre-transform), and otherwise --platform=hermes uses the built-in downlevel pipeline.
|
|
228
|
-
// Both resolve Babel from the project (cwd), never from stasis's own dependencies.
|
|
229
304
|
let transform
|
|
230
305
|
if (babel) transform = createBabelConfigTransform({ projectDir: cwd })
|
|
231
306
|
else if (hermes) transform = createHermesTransform({ projectDir: cwd, esbuild })
|
|
307
|
+
if (flow) transform = transform === undefined ? createFlowTransform(esbuild) : chainTransforms(createFlowTransform(esbuild), transform)
|
|
308
|
+
const builtAssets = new Map()
|
|
309
|
+
const resource = metro === undefined ? undefined : metroAssetResource(state, metro, builtAssets)
|
|
232
310
|
|
|
233
311
|
const outAbs = resolve(cwd, output)
|
|
234
312
|
const asFile = /\.[cm]?js$/u.test(output)
|
|
235
|
-
// Never overwrite a file the artifact attests: esbuild's own overwrite check fires only
|
|
236
|
-
//
|
|
237
|
-
// clobber any recorded file before touching disk.
|
|
313
|
+
// Never overwrite a file the artifact attests: esbuild's own overwrite check fires only after writing
|
|
314
|
+
// (corrupting a lockfile's hash), so it builds write:false and each output is checked before any is written.
|
|
238
315
|
const attested = new Set([...state.sources.keys(), ...state.resources.keys()].map((f) => resolve(state.root, f)))
|
|
239
316
|
|
|
240
317
|
let result
|
|
@@ -253,37 +330,54 @@ export async function buildCommand({
|
|
|
253
330
|
...(external.length > 0 ? { external } : {}),
|
|
254
331
|
...(Object.keys(define).length > 0 ? { define } : {}),
|
|
255
332
|
...(asFile ? { outfile: outAbs } : { outdir: outAbs }),
|
|
256
|
-
//
|
|
257
|
-
|
|
258
|
-
plugins: [new StasisEsbuild(state, { loaders: new Map(Object.entries(loader)), transform })],
|
|
333
|
+
// Loaders go through the plugin: it serves every file, so esbuild's own `loader` option never sees them.
|
|
334
|
+
plugins: [new StasisEsbuild(state, { loaders: new Map(Object.entries(loader)), transform, resource, platform: metro })],
|
|
259
335
|
})
|
|
260
336
|
} catch (err) {
|
|
261
|
-
// Under logLevel:'silent' esbuild puts the real errors on err.errors
|
|
337
|
+
// Under logLevel:'silent' esbuild puts the real errors on err.errors.
|
|
262
338
|
if (Array.isArray(err?.errors) && err.errors.length > 0) {
|
|
263
|
-
const
|
|
264
|
-
|
|
339
|
+
for (const line of await esbuild.formatMessages(err.errors, { kind: 'error', color: false })) process.stderr.write(line)
|
|
340
|
+
const unloaded = err.errors.map((e) => /^No loader is configured for "([^"]+)" files/u.exec(e.text)?.[1]).find(Boolean)
|
|
341
|
+
if (unloaded !== undefined) {
|
|
342
|
+
process.stderr.write(
|
|
343
|
+
`[stasis] Build a "${unloaded}" resource with --loader=${unloaded}:NAME (an esbuild loader: dataurl, file, text, ...), ` +
|
|
344
|
+
`or with --metro=PLATFORM as the asset module Metro builds of it\n`
|
|
345
|
+
)
|
|
346
|
+
}
|
|
347
|
+
if (metro === undefined && err.errors.some((e) => e.detail?.code === 'ERR_STASIS_PLATFORM_SPECIFIC')) {
|
|
348
|
+
process.stderr.write('[stasis] A --metro multi-platform bundle builds for one platform at a time: pass --metro=PLATFORM (e.g. --metro=ios)\n')
|
|
349
|
+
}
|
|
265
350
|
throw new Error(`stasis build failed: esbuild reported ${err.errors.length} error(s)`, { cause: err })
|
|
266
351
|
}
|
|
267
352
|
throw err
|
|
268
353
|
}
|
|
269
354
|
|
|
270
|
-
//
|
|
271
|
-
|
|
272
|
-
|
|
355
|
+
// As `react-native bundle --assets-dest` lays them out, in a stable order (esbuild loads in parallel).
|
|
356
|
+
const assetFiles = assetsDest === undefined
|
|
357
|
+
? []
|
|
358
|
+
: assetsDestFiles([...builtAssets.keys()].toSorted().map((rel) => builtAssets.get(rel)), metro)
|
|
359
|
+
.map(({ dest, src, contents }) => ({ path: resolve(cwd, assetsDest, dest), contents: contents ?? readCarried(state, src) }))
|
|
360
|
+
const writes = [...result.outputFiles, ...assetFiles]
|
|
361
|
+
for (const { path } of writes) {
|
|
362
|
+
if (attested.has(path)) {
|
|
273
363
|
throw new Error(
|
|
274
|
-
`stasis build: refusing to write '${relative(cwd,
|
|
275
|
-
`choose an --output path outside the artifact's own files`
|
|
364
|
+
`stasis build: refusing to write '${relative(cwd, path)}' -- it is a source the artifact records; ` +
|
|
365
|
+
`choose an --output${assetsDest === undefined ? '' : '/--assets-dest'} path outside the artifact's own files`
|
|
276
366
|
)
|
|
277
367
|
}
|
|
278
368
|
}
|
|
279
369
|
|
|
280
370
|
if (result.warnings.length > 0) {
|
|
281
|
-
const
|
|
282
|
-
for (const line of formatted) process.stderr.write(line)
|
|
371
|
+
for (const line of await esbuild.formatMessages(result.warnings, { kind: 'warning', color: false })) process.stderr.write(line)
|
|
283
372
|
}
|
|
284
373
|
|
|
285
|
-
for (const
|
|
374
|
+
for (const { path, contents } of writes) writeFile(path, contents)
|
|
286
375
|
|
|
287
376
|
console.warn(`[stasis] Built ${selectedEntry} from ${kind} ${artifact} to ${output}`)
|
|
377
|
+
if (assetsDest !== undefined) {
|
|
378
|
+
console.warn(`[stasis] Copied ${builtAssets.size} asset${builtAssets.size === 1 ? '' : 's'} (${assetFiles.length} file${assetFiles.length === 1 ? '' : 's'}) for ${metro} to ${assetsDest}`)
|
|
379
|
+
} else if (builtAssets.size > 0) {
|
|
380
|
+
console.warn(`[stasis] Built ${builtAssets.size} asset${builtAssets.size === 1 ? '' : 's'} for ${metro}; pass --assets-dest to copy their files out`)
|
|
381
|
+
}
|
|
288
382
|
return { entry: selectedEntry, dir: asFile ? undefined : outAbs, outfile: asFile ? outAbs : undefined }
|
|
289
383
|
}
|