@exodus/stasis 1.0.0-beta.13 → 1.0.0-beta.15
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 +5 -1
- package/bin/stasis.js +191 -149
- package/package.json +31 -7
- package/src/audit.js +224 -90
- package/src/babel.js +44 -37
- package/src/bundle-reader.js +24 -4
- package/src/cmd/build.js +218 -8
- package/src/cmd/bundle-options.js +31 -25
- package/src/cmd/bundle.js +1147 -311
- package/src/cmd/github-bundle.js +17 -9
- package/src/cmd/output.js +10 -3
- package/src/cmd/tokens.js +73 -0
- package/src/define.js +5 -0
- package/src/diff.js +2 -2
- package/src/flow.js +42 -0
- package/src/installed-commits.js +4 -2
- package/src/loaders/bash.js +2 -27
- package/src/loaders/cargo.js +6 -6
- package/src/loaders/foundry.js +4 -6
- package/src/loaders/paths.js +4 -15
- package/src/loaders/php.js +3 -5
- package/src/loaders/rust.js +19 -39
- package/src/loaders/solidity-ownership.js +4 -15
- package/src/loaders/solidity.js +4 -67
- package/src/metro-assets.js +65 -0
- package/src/metro-resolver.js +76 -123
- package/src/parse.js +7 -3
- package/src/resolve-fields.js +133 -366
- package/src/resolve-node.js +9 -7
- package/src/resolve-typescript.js +102 -30
- package/src/scan.js +154 -54
- package/src/sixel.js +333 -0
- package/src/table.js +116 -0
- package/src/validate-notes.d.ts +18 -0
- package/src/validate-notes.js +66 -0
- package/src/validate.d.ts +132 -0
- package/src/validate.js +1349 -0
- package/src/vfs-bundle/entries.js +5 -2
- package/src/vfs-bundle/github.js +68 -19
- package/src/vfs-bundle/glob.js +420 -0
- package/src/vfs-bundle/lazy.js +128 -0
- package/src/vfs-bundle/prisma.js +102 -29
- package/src/vfs-bundle/tree.js +238 -75
- package/src/vfs-bundle/yarnclean.js +100 -0
- package/src/vfs-bundle.js +16 -7
- package/src/why.js +9 -7
|
@@ -8,9 +8,9 @@ import { isAbsolute, join, parse, posix, relative, resolve, sep } from 'node:pat
|
|
|
8
8
|
|
|
9
9
|
import { utf8toString } from '@exodus/bytes/utf8.js'
|
|
10
10
|
import { LockfileError, parseGitmodules } from '@preventive/lockfile/foundry.js'
|
|
11
|
-
import { NO_ENTRY, readRegularFileOrNull } from '@exodus/stasis-core/bundle-util'
|
|
11
|
+
import { NO_ENTRY, lexists, readRegularFileOrNull } from '@exodus/stasis-core/bundle-util'
|
|
12
12
|
import { diskHost } from '@exodus/stasis-core/host'
|
|
13
|
-
import { hasNodeModulesSegment } from '@exodus/stasis-core/util'
|
|
13
|
+
import { hasNodeModulesSegment, nestedMap, relativeEscapes } from '@exodus/stasis-core/util'
|
|
14
14
|
import { isDir } from '../resolve-typescript.js'
|
|
15
15
|
|
|
16
16
|
// `/`-separated, as the loader's paths are: only Windows' separator is converted (on POSIX a `\\` is
|
|
@@ -33,7 +33,7 @@ export function realpathOrNull(p, host = diskHost) {
|
|
|
33
33
|
}
|
|
34
34
|
|
|
35
35
|
// A path relative to a dir (slashes) that stays inside it.
|
|
36
|
-
const inRoot = (rel) =>
|
|
36
|
+
const inRoot = (rel) => !relativeEscapes(rel)
|
|
37
37
|
|
|
38
38
|
// `abs`, a file the resolution read, relative to the project `root` (slashes): as spelled when that
|
|
39
39
|
// lies inside it with no `..` to resolve (a linked lib's files keep the lib's path), else by real
|
|
@@ -72,17 +72,6 @@ function osRealpath(p, host) {
|
|
|
72
72
|
}
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
-
// Whether anything is at `p` itself, a link not followed (`host.readlink` throws when nothing is).
|
|
76
|
-
function lexists(p, host) {
|
|
77
|
-
try {
|
|
78
|
-
host.readlink(p)
|
|
79
|
-
return true
|
|
80
|
-
} catch (err) {
|
|
81
|
-
if (NO_ENTRY.has(err.code)) return false
|
|
82
|
-
throw err
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
|
|
86
75
|
// `bytes` as UTF-8 text, a byte-order mark kept. Bytes that aren't UTF-8 throw, naming them
|
|
87
76
|
// `label`, rather than read with U+FFFD in their place: forge, solc and git refuse such a file, and
|
|
88
77
|
// the text bundled or read must be the file's own.
|
|
@@ -147,7 +136,7 @@ function gitmodulesLeniently(text) {
|
|
|
147
136
|
if (!variable?.startsWith('submodule.')) continue
|
|
148
137
|
const name = variable.slice('submodule.'.length)
|
|
149
138
|
if (section !== 'submodule') notes.push(`${header}, a section git reads as [submodule "${name}"]; reading it as that`)
|
|
150
|
-
const kept =
|
|
139
|
+
const kept = nestedMap(sections, name)
|
|
151
140
|
const given = paths.get(name) ?? paths.set(name, []).get(name)
|
|
152
141
|
for (const entry of keys) {
|
|
153
142
|
if (!SUBMODULE_KEYS.has(entry.key)) continue
|
package/src/loaders/solidity.js
CHANGED
|
@@ -9,8 +9,7 @@
|
|
|
9
9
|
// is read through a link a dependency planted out of itself (solidityOwnership). The project is read
|
|
10
10
|
// through a `host` (@exodus/stasis-core/host), the disk's by default.
|
|
11
11
|
|
|
12
|
-
import {
|
|
13
|
-
import { dirname, isAbsolute, join, posix, relative, resolve } from 'node:path'
|
|
12
|
+
import { isAbsolute, join, posix, relative, resolve } from 'node:path'
|
|
14
13
|
|
|
15
14
|
import { diskHost } from '@exodus/stasis-core/host'
|
|
16
15
|
import { assertRealPathWithinBase, relativeEscapes, toPosix } from '@exodus/stasis-core/util'
|
|
@@ -21,14 +20,13 @@ import {
|
|
|
21
20
|
foundryLibs,
|
|
22
21
|
foundryProfile,
|
|
23
22
|
foundryProject,
|
|
24
|
-
foundryTomlRemappings,
|
|
25
23
|
parseRemappingLines,
|
|
26
24
|
readFoundryTomlRemappings,
|
|
27
25
|
shownFrom,
|
|
28
26
|
toSolcRemapping,
|
|
29
27
|
} from './foundry.js'
|
|
28
|
+
import { applyToDir, isDotRelative } from './paths.js'
|
|
30
29
|
import { decodeUtf8, projectOwnership, projectRelative, readUtf8OrNull, realpathOrNull, solidityOwnership } from './solidity-ownership.js'
|
|
31
|
-
import { assertWithinBase } from './paths.js'
|
|
32
30
|
|
|
33
31
|
// --- Import scan ------------------------------------------------------------------------------
|
|
34
32
|
|
|
@@ -135,18 +133,6 @@ export function extractSolImports(content) {
|
|
|
135
133
|
// Loader-side shape: `{ context, prefix, target }` (context null = global).
|
|
136
134
|
const toLoaderRemapping = ({ context, name, path }) => ({ context, prefix: name, target: path })
|
|
137
135
|
|
|
138
|
-
// remappings.txt text -> remappings as written, one `[context:]prefix=target` per line (lines
|
|
139
|
-
// trimmed, blank ones skipped; an empty target is solc's, valid). A line that isn't one throws.
|
|
140
|
-
export function parseRemappings(content) {
|
|
141
|
-
return parseRemappingLines(content, { emptyPath: true }).map(toLoaderRemapping)
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
// foundry.toml text -> the `remappings` of `[profile.default]`, overlaid by the selected profile's
|
|
145
|
-
// (FOUNDRY_PROFILE in `env`) when it sets them.
|
|
146
|
-
export function parseRemappingsFromToml(tomlContent, { env = process.env } = {}) {
|
|
147
|
-
return foundryTomlRemappings(tomlContent, foundryProfile(env)).map(toLoaderRemapping)
|
|
148
|
-
}
|
|
149
|
-
|
|
150
136
|
// Read a mapping file -> its remappings as listed (no discovery around it) and the files read. A
|
|
151
137
|
// foundry.toml (its selected profile, with its `extends` base) is forge's, and so is a
|
|
152
138
|
// remappings.txt when `forge` says forge reads it: slash-terminated the way forge reads them.
|
|
@@ -164,12 +150,6 @@ function readMapping(mappingFile, { env, forge, host, show = (f) => f }) {
|
|
|
164
150
|
return { remappings: listed.map(forge ? toSolcRemapping : toLoaderRemapping), files: [mappingFile] }
|
|
165
151
|
}
|
|
166
152
|
|
|
167
|
-
// Read a foundry.toml/remappings.txt mapping file -> its remappings (see readMapping; `forge`
|
|
168
|
-
// defaults to a remappings.txt applying as written). The file itself is not added to sources.
|
|
169
|
-
export function readRemappingsFile(mappingFile, { env = process.env, forge = false, host = diskHost } = {}) {
|
|
170
|
-
return readMapping(mappingFile, { env, forge, host }).remappings
|
|
171
|
-
}
|
|
172
|
-
|
|
173
153
|
// --- Resolution ---------------------------------------------------------------------------------
|
|
174
154
|
|
|
175
155
|
// What resolves the imports of the project at `baseDir`:
|
|
@@ -222,24 +202,7 @@ export function applyRemappings(name, fromFile, remappings) {
|
|
|
222
202
|
// A relative import (first segment `.` or `..`) as solc resolves it: against the importing file's
|
|
223
203
|
// directory. Null when it climbs above the root: solc clamps there (`../../B.sol` from `src/A.sol`
|
|
224
204
|
// is `B.sol`), but an import reaching out of the project is refused rather than redirected.
|
|
225
|
-
|
|
226
|
-
const resolved = fromFile.includes('/') ? fromFile.slice(0, fromFile.lastIndexOf('/')).split('/') : []
|
|
227
|
-
for (const part of specifier.split('/')) {
|
|
228
|
-
if (part === '.' || part === '') continue
|
|
229
|
-
if (part === '..') {
|
|
230
|
-
if (resolved.length === 0) return null
|
|
231
|
-
resolved.pop()
|
|
232
|
-
} else {
|
|
233
|
-
resolved.push(part)
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
return resolved.join('/')
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
const isRelativeImport = (specifier) => {
|
|
240
|
-
const first = specifier.split('/')[0]
|
|
241
|
-
return first === '.' || first === '..'
|
|
242
|
-
}
|
|
205
|
+
const resolveRelativeImport = (specifier, fromFile) => applyToDir(fromFile, specifier.split('/'))
|
|
243
206
|
|
|
244
207
|
// `<baseDir>/<spec>` when a real file sits there, as a clean project-relative path.
|
|
245
208
|
function projectFile(baseDir, spec, host) {
|
|
@@ -284,7 +247,7 @@ function nodeModulesFile(baseDir, spec, fromFile, host) {
|
|
|
284
247
|
// Where an import resolves, as `{ path }`, or `{ reason }` when it may not be read (`reason: null`:
|
|
285
248
|
// it names no file). See resolveSolImport.
|
|
286
249
|
function resolveImport(specifier, fromFile, { remappings = [], baseDir, libs = [], ownership, host = diskHost } = {}) {
|
|
287
|
-
const relativeImport =
|
|
250
|
+
const relativeImport = isDotRelative(specifier)
|
|
288
251
|
const name = relativeImport ? resolveRelativeImport(specifier, fromFile) : specifier
|
|
289
252
|
if (name === null) return { reason: 'it climbs above the project root' }
|
|
290
253
|
let path = applyRemappings(name, fromFile, remappings)
|
|
@@ -457,29 +420,3 @@ export function expandSolidityEntries(baseDir, entries, host = diskHost) {
|
|
|
457
420
|
}
|
|
458
421
|
return [...out]
|
|
459
422
|
}
|
|
460
|
-
|
|
461
|
-
// High-level entry: a `.sol.txt` listing whose optional first line is a `*.toml`/`remappings.txt`
|
|
462
|
-
// mapping file (resolved relative to the listing); the remaining lines are `*.sol` files. Without
|
|
463
|
-
// a mapping line, the remappings are discovered as for `stasis bundle` (discoverSolidityConfig).
|
|
464
|
-
export async function loadSolidity(solTxtFile, { env = process.env } = {}) {
|
|
465
|
-
const baseDir = dirname(resolve(solTxtFile))
|
|
466
|
-
const listing = decodeUtf8(await readFile(solTxtFile), solTxtFile)
|
|
467
|
-
const lines = listing.split('\n').map((l) => l.trim()).filter(Boolean)
|
|
468
|
-
if (lines.length === 0) throw new Error(`Empty Solidity listing: ${solTxtFile}`)
|
|
469
|
-
|
|
470
|
-
let mappingFile
|
|
471
|
-
if (lines[0].endsWith('.toml') || lines[0].endsWith('remappings.txt')) {
|
|
472
|
-
mappingFile = lines.shift()
|
|
473
|
-
assertWithinBase(baseDir, mappingFile, 'Mapping path')
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
if (!lines.every((line) => line.endsWith('.sol'))) {
|
|
477
|
-
throw new Error(`Solidity listing must only contain .sol files: ${solTxtFile}`)
|
|
478
|
-
}
|
|
479
|
-
|
|
480
|
-
const entries = lines.map((l) => l.replace(/^\.\//u, ''))
|
|
481
|
-
for (const e of entries) assertWithinBase(baseDir, e, 'Entry path')
|
|
482
|
-
const { remappings, libs, ownership } = discoverSolidityConfig(baseDir, { mappingFile, env })
|
|
483
|
-
const sources = collectSolidityFilesFromDisk(baseDir, entries, remappings, { libs, ownership })
|
|
484
|
-
return buildSolidityTree(sources, { remappings, baseDir, libs, ownership })
|
|
485
|
-
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// `stasis build --metro=PLATFORM`: a Metro asset (a resource a --metro bundle reaches through an import)
|
|
2
|
+
// built into the module Metro builds of it, and copied out as `react-native bundle --assets-dest` copies
|
|
3
|
+
// it, from the bytes the artifact carries -- never from disk.
|
|
4
|
+
//
|
|
5
|
+
// Metro builds `require('./img/logo.png')` into (metro-transform-worker's assetTransformer, Metro's
|
|
6
|
+
// getAssetData and generateAssetCodeFileAst):
|
|
7
|
+
//
|
|
8
|
+
// module.exports = require('react-native/Libraries/Image/AssetRegistry').registerAsset({
|
|
9
|
+
// __packager_asset: true, httpServerLocation: '/assets/img', width, height,
|
|
10
|
+
// scales: [1, 2, 3], hash, name: 'logo', type: 'png' })
|
|
11
|
+
//
|
|
12
|
+
// from every file of the asset in its directory (each scale, `logo@2x.png`; those for the platform,
|
|
13
|
+
// `logo.ios.png`, where it has any): their scales, an md5 over their bytes, and the first one's image
|
|
14
|
+
// dimensions over its scale. That reading of an asset and the module built of it are @preventive/rn's
|
|
15
|
+
// (assetData, assetModule), as is where --assets-dest copies its files (assetsDestFiles). What stays
|
|
16
|
+
// here is the asset registry the module requires: React Native's Metro config's `assetRegistryPath`
|
|
17
|
+
// (@react-native/metro-config's), the one `stasis bundle --metro` carries for an asset. A project's
|
|
18
|
+
// own `assetRegistryPath`, `publicPath` (Metro's default `/assets` here) and `assetPlugins` are read off
|
|
19
|
+
// its Metro config, which is code, and aren't.
|
|
20
|
+
import { posix } from 'node:path'
|
|
21
|
+
|
|
22
|
+
import { METRO_SOURCE_EXTS } from './resolve-fields.js'
|
|
23
|
+
|
|
24
|
+
// The asset registry the module Metro builds of an asset requires: React Native's Metro config's
|
|
25
|
+
// `assetRegistryPath` (@react-native/metro-config's), where a project's own isn't read, being code.
|
|
26
|
+
// `stasis bundle --metro` carries the file it resolves to for each asset.
|
|
27
|
+
export const ASSET_REGISTRY = 'react-native/Libraries/Image/AssetRegistry'
|
|
28
|
+
|
|
29
|
+
// The resolver of `ASSET_REGISTRY` from an asset for `platform`, as Metro resolves it, among `carried`
|
|
30
|
+
// (the code files the artifact carries: a Map or Set keyed by their paths from the project root): the
|
|
31
|
+
// copy of react-native in the nearest node_modules up from the asset's directory, else the only copy
|
|
32
|
+
// (pnpm's, linked in from node_modules/.pnpm); in it, the file Metro probes first -- each of its
|
|
33
|
+
// sourceExts, the platform's file, then the .native one, then the plain one. The copies are found once.
|
|
34
|
+
// -> (rel) => its path, throwing where the artifact carries none, or several none of them nearest
|
|
35
|
+
const REGISTRY_ROOT = /^((?:.*\/)?node_modules\/react-native)\/Libraries\/Image\/AssetRegistry\./u
|
|
36
|
+
export function assetRegistryResolver(platform, carried) {
|
|
37
|
+
const pick = (root) => {
|
|
38
|
+
for (const ext of METRO_SOURCE_EXTS) {
|
|
39
|
+
for (const suffix of [`.${platform}`, '.native', '']) {
|
|
40
|
+
const file = `${root}/Libraries/Image/AssetRegistry${suffix}.${ext}`
|
|
41
|
+
if (carried.has(file)) return file
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return undefined
|
|
45
|
+
}
|
|
46
|
+
const roots = new Set([...carried.keys()].map((file) => REGISTRY_ROOT.exec(file)?.[1]).filter((root) => root !== undefined && pick(root) !== undefined))
|
|
47
|
+
const nearest = (rel) => {
|
|
48
|
+
for (let dir = posix.dirname(rel); ; dir = posix.dirname(dir)) {
|
|
49
|
+
const root = posix.join(dir, 'node_modules', 'react-native')
|
|
50
|
+
if (posix.basename(dir) !== 'node_modules' && roots.has(root)) return root
|
|
51
|
+
if (dir === '.' || dir === '/' || dir.startsWith('..')) return undefined
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return (rel) => {
|
|
55
|
+
const root = roots.size === 1 ? [...roots][0] : nearest(rel)
|
|
56
|
+
if (root !== undefined) return pick(root)
|
|
57
|
+
if (roots.size === 0) {
|
|
58
|
+
throw new Error(
|
|
59
|
+
`stasis build: --metro builds '${rel}' into a module requiring ${ASSET_REGISTRY}, which the artifact doesn't carry; ` +
|
|
60
|
+
'bundle it with `stasis bundle --metro --resources=...` from a project with react-native installed'
|
|
61
|
+
)
|
|
62
|
+
}
|
|
63
|
+
throw new Error(`stasis build: --metro found several ${ASSET_REGISTRY} for '${rel}', none of them nearest: ${[...roots].join(', ')}`)
|
|
64
|
+
}
|
|
65
|
+
}
|
package/src/metro-resolver.js
CHANGED
|
@@ -1,83 +1,79 @@
|
|
|
1
1
|
import { createRequire, isBuiltin } from 'node:module'
|
|
2
|
-
import {
|
|
2
|
+
import { basename, join } from 'node:path'
|
|
3
3
|
import { pathToFileURL } from 'node:url'
|
|
4
4
|
|
|
5
|
+
import { createMetroResolver as createRnMetroResolver, defaults } from '@preventive/rn/metro-resolver.js'
|
|
5
6
|
import { diskHost } from '@exodus/stasis-core/host'
|
|
6
|
-
import { isTypeDeclaration } from '@exodus/stasis-core/util'
|
|
7
|
-
import { readJson } from './resolve-typescript.js'
|
|
8
|
-
import { METRO_ASSET_EXTS, lowestPath, metroAssetCandidates } from './resolve-fields.js'
|
|
7
|
+
import { isTypeDeclaration, stripTypeDeclaration } from '@exodus/stasis-core/util'
|
|
9
8
|
|
|
10
|
-
//
|
|
11
|
-
// `stasis bundle --metro --metro-resolver`
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
// filesystem callbacks and does no I/O of its own), so we load whichever copy the project
|
|
15
|
-
// already ships and feed it a synchronous, disk-backed ResolutionContext.
|
|
16
|
-
//
|
|
17
|
-
// Returns, for each specifier, the same shape scan.js expects from a custom resolver:
|
|
18
|
-
// { url } resolved to a real file (file: URL string)
|
|
19
|
-
// { empty } a browser/react-native field mapped it to `false` (empty module)
|
|
20
|
-
// { builtin } a Node builtin (Metro itself has none; we classify a bare-name miss)
|
|
21
|
-
// null unresolved
|
|
22
|
-
//
|
|
23
|
-
// It is deliberately version-agnostic: it never imports metro-resolver internals (the
|
|
24
|
-
// `./private/*` subpath), only the public `resolve`. `resolve` applies the browser-field
|
|
25
|
-
// redirect via its own bundled helper, so the `redirectModulePath` we place on the context is
|
|
26
|
-
// an inert placeholder that satisfies the type but is never consulted for base resolution.
|
|
9
|
+
// Metro's module resolution is @preventive/rn's (metro-resolver's own steps, over a host), for both
|
|
10
|
+
// `stasis bundle --metro` (resolve-fields.js) and `--metro --metro-resolver` (createMetroResolver
|
|
11
|
+
// below). What stays stasis's: no `.d.ts` is a module to it (metroHost), a Node builtin Metro misses
|
|
12
|
+
// is a builtin, and its answers take the shape scan.js expects of a custom resolver (scanResolution).
|
|
27
13
|
|
|
28
|
-
//
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
14
|
+
// A manifest as stasis has Metro read it: an entry field (one of `mainFields`) naming a `.d.ts` names
|
|
15
|
+
// its declaration-free stem instead, so the package's entry lands on the real module beside it
|
|
16
|
+
// (`dist/index.d.ts` -> `dist/index`, then `dist/index.js`). Any other manifest, or one that is no
|
|
17
|
+
// JSON object (which the resolver refuses), is read as it is.
|
|
18
|
+
const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
|
|
19
|
+
const DECLARATION = /\.d\.[cm]?ts\b/iu
|
|
20
|
+
function manifestStems(bytes, mainFields) {
|
|
21
|
+
let manifest
|
|
22
|
+
try {
|
|
23
|
+
const text = utf8.decode(bytes)
|
|
24
|
+
if (!DECLARATION.test(text)) return bytes
|
|
25
|
+
manifest = JSON.parse(text)
|
|
26
|
+
} catch {
|
|
27
|
+
return bytes
|
|
28
|
+
}
|
|
29
|
+
if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)) return bytes
|
|
30
|
+
const typed = mainFields.filter((field) => typeof manifest[field] === 'string' && isTypeDeclaration(manifest[field]))
|
|
31
|
+
if (typed.length === 0) return bytes
|
|
32
|
+
for (const field of typed) manifest[field] = stripTypeDeclaration(manifest[field])
|
|
33
|
+
return Buffer.from(JSON.stringify(manifest))
|
|
32
34
|
}
|
|
33
35
|
|
|
34
|
-
//
|
|
35
|
-
//
|
|
36
|
-
//
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
// is '' when the candidate IS the package root -- Metro's exports resolver maps '' to the '.' subpath,
|
|
44
|
-
// and a stray '.' there would mismatch the exports key.
|
|
45
|
-
function getPackageForModule(absModulePath) {
|
|
46
|
-
let dir = pathType(absModulePath) === 'd' ? absModulePath : dirname(absModulePath)
|
|
47
|
-
while (true) {
|
|
48
|
-
const pkg = readJson(join(dir, 'package.json'))
|
|
49
|
-
if (pkg) {
|
|
50
|
-
const rel = dir === absModulePath ? '' : absModulePath.slice(dir.length + 1)
|
|
51
|
-
return { rootPath: dir, packageJson: pkg, packageRelativePath: rel }
|
|
52
|
-
}
|
|
53
|
-
const parent = dirname(dir)
|
|
54
|
-
if (parent === dir) return null
|
|
55
|
-
dir = parent
|
|
36
|
+
// `host` (@exodus/stasis-core/host) as @preventive/rn reads one, for Metro's `mainFields`. A `.d.ts`
|
|
37
|
+
// is types-only, erased at runtime, so the resolver never lands on one: no `.d.ts` is a file, and a
|
|
38
|
+
// manifest's entry naming one names its stem (manifestStems).
|
|
39
|
+
export function metroHost(host, mainFields = defaults.mainFields) {
|
|
40
|
+
return {
|
|
41
|
+
isFile: (path) => !isTypeDeclaration(path) && (host.stat(path)?.isFile() ?? false),
|
|
42
|
+
isDirectory: (path) => host.stat(path)?.isDirectory() ?? false,
|
|
43
|
+
realpath: (path) => host.realpath(path),
|
|
44
|
+
readFile: (path) => (basename(path) === 'package.json' ? manifestStems(host.readFile(path), mainFields) : host.readFile(path)),
|
|
56
45
|
}
|
|
57
46
|
}
|
|
58
47
|
|
|
59
|
-
//
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
//
|
|
63
|
-
//
|
|
64
|
-
//
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
48
|
+
// The file Metro builds an asset of several into the module of (getArrayLowestItem): the lowest path.
|
|
49
|
+
const lowestPath = (paths) => paths.reduce((lowest, path) => (path < lowest ? path : lowest))
|
|
50
|
+
|
|
51
|
+
// @preventive/rn's Resolution of `specifier` (null where Metro fails it) as scan.js takes a custom
|
|
52
|
+
// resolver's answer:
|
|
53
|
+
// { url } resolved to a file, by its real path (file: URL string)
|
|
54
|
+
// { empty } a browser/react-native field mapped it to `false` (empty module)
|
|
55
|
+
// { builtin } a Node builtin Metro failed to resolve, where `builtin` says it is one
|
|
56
|
+
// null unresolved
|
|
57
|
+
export function scanResolution(resolution, builtin) {
|
|
58
|
+
if (resolution === null) return builtin ? { builtin: true } : null
|
|
59
|
+
if (resolution.type === 'empty') return { empty: true }
|
|
60
|
+
const file = resolution.type === 'sourceFile' ? resolution.filePath : lowestPath(resolution.filePaths)
|
|
61
|
+
return { url: pathToFileURL(file).toString() }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// `stasis bundle --metro --metro-resolver`: resolve through the PROJECT's own `metro-resolver`, so
|
|
65
|
+
// modules resolve exactly the way that project's installed Metro does. `metro-resolver` is a leaf of
|
|
66
|
+
// the Metro toolchain (it takes a context of filesystem callbacks and does no I/O of its own), so
|
|
67
|
+
// whichever copy the project ships is loaded and given the context Metro's DependencyGraph builds,
|
|
68
|
+
// over the disk (@preventive/rn's `metroResolver`). The options are Metro's resolver config, React
|
|
69
|
+
// Native's defaults where left out; Metro only prefers native suffixes off web. Metro carries no Node
|
|
70
|
+
// builtins, so a builtin it fails to resolve (one no browser map remaps) is reported as one.
|
|
71
|
+
export function createMetroResolver({ projectDir, platform, sourceExts, mainFields, conditionNames, conditionsByPlatform, assetExts, assetResolutions, host = diskHost } = {}) {
|
|
75
72
|
// It loads the project's metro-resolver, which reads the disk: never off it.
|
|
76
73
|
if (host !== diskHost) throw new Error('createMetroResolver: metro-resolver reads the disk, so it is not supported off disk')
|
|
77
|
-
|
|
78
|
-
let resolve
|
|
74
|
+
let metroResolver
|
|
79
75
|
try {
|
|
80
|
-
|
|
76
|
+
metroResolver = createRequire(join(projectDir, 'noop.js'))('metro-resolver')
|
|
81
77
|
} catch (cause) {
|
|
82
78
|
throw new Error(
|
|
83
79
|
`StasisMetroResolver: couldn't load 'metro-resolver' from ${projectDir}. --metro-resolver ` +
|
|
@@ -86,64 +82,21 @@ export function createMetroResolver({
|
|
|
86
82
|
{ cause }
|
|
87
83
|
)
|
|
88
84
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
assetExts: METRO_ASSET_EXTS,
|
|
95
|
-
customResolverOptions: {},
|
|
96
|
-
disableHierarchicalLookup: false,
|
|
97
|
-
doesFileExist: (p) => resolvableType(p) === 'f',
|
|
98
|
-
extraNodeModules: null,
|
|
99
|
-
dev: false,
|
|
100
|
-
getPackage: (packageJsonPath) => readJson(packageJsonPath),
|
|
101
|
-
getPackageForModule,
|
|
102
|
-
fileSystemLookup: (p) => {
|
|
103
|
-
const abs = isAbsolute(p) ? p : join(projectDir, p)
|
|
104
|
-
const type = resolvableType(abs)
|
|
105
|
-
if (!type) return { exists: false }
|
|
106
|
-
let realPath = abs
|
|
107
|
-
try {
|
|
108
|
-
realPath = diskHost.realpath(abs)
|
|
109
|
-
} catch { /* keep the lexical path when realpath fails (e.g. a broken symlink) */ }
|
|
110
|
-
return { exists: true, type, realPath }
|
|
111
|
-
},
|
|
85
|
+
const resolve = createRnMetroResolver({
|
|
86
|
+
host: metroHost(host, mainFields),
|
|
87
|
+
sourceExts,
|
|
88
|
+
assetExts,
|
|
89
|
+
assetResolutions,
|
|
112
90
|
mainFields,
|
|
113
|
-
|
|
91
|
+
conditionNames,
|
|
92
|
+
conditionsByPlatform,
|
|
114
93
|
preferNativePlatform: platform !== 'web',
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
unstable_conditionsByPlatform: conditionsByPlatform,
|
|
123
|
-
unstable_enablePackageExports: enablePackageExports,
|
|
124
|
-
unstable_incrementalResolution: false,
|
|
125
|
-
unstable_logWarning: () => {}, // a static build must not spam on exports fallbacks
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
return function resolveOne(parentFile, specifier, callConditions) {
|
|
129
|
-
// Metro splits `exports` on whether the edge was an ESM import vs a CJS require. scan.js hands
|
|
130
|
-
// us the parent's format-derived condition set, so 'import' membership is that signal.
|
|
131
|
-
const isESMImport = callConditions instanceof Set ? callConditions.has('import') : false
|
|
132
|
-
const context = { ...base, originModulePath: parentFile, isESMImport }
|
|
133
|
-
let res
|
|
134
|
-
try {
|
|
135
|
-
res = resolve(context, specifier, platform)
|
|
136
|
-
} catch {
|
|
137
|
-
// Metro carries no Node builtins: an unmapped builtin fails to resolve here. The browser-field
|
|
138
|
-
// remap of a builtin (`{"crypto": false}` / a shim) is handled inside resolve() before this.
|
|
139
|
-
if (isBuiltin(specifier)) return { builtin: true }
|
|
140
|
-
return null
|
|
141
|
-
}
|
|
142
|
-
if (!res) return null
|
|
143
|
-
if (res.type === 'empty') return { empty: true }
|
|
144
|
-
if (res.type === 'sourceFile') return { url: pathToFileURL(res.filePath).toString() }
|
|
145
|
-
// An asset's files are it and its scale variants: Metro's graph takes the lowest path for the module.
|
|
146
|
-
if (res.type === 'assetFiles' && res.filePaths?.length) return { url: pathToFileURL(lowestPath(res.filePaths)).toString() }
|
|
147
|
-
return null
|
|
94
|
+
metroResolver,
|
|
95
|
+
})
|
|
96
|
+
// Metro splits `exports` on whether the edge was an ESM import or a CJS require: scan.js hands over
|
|
97
|
+
// the parent's format-derived condition set, so `import` in it is that signal.
|
|
98
|
+
return (parentFile, specifier, callConditions) => {
|
|
99
|
+
const isESMImport = callConditions instanceof Set && callConditions.has('import')
|
|
100
|
+
return scanResolution(resolve(parentFile, specifier, { platform, isESMImport }), isBuiltin(specifier))
|
|
148
101
|
}
|
|
149
102
|
}
|
package/src/parse.js
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
import { readFileSync } from 'node:fs'
|
|
2
|
-
import { brotliDecompressSync } from 'node:zlib'
|
|
3
2
|
|
|
3
|
+
import { brotliDecompressStrict } from '@exodus/stasis-core/brotli'
|
|
4
4
|
import { Bundle } from '@exodus/stasis-core/bundle'
|
|
5
5
|
import { Lockfile } from '@exodus/stasis-core/lockfile'
|
|
6
6
|
|
|
7
7
|
// Read a stasis artifact and parse it into a Lockfile or Bundle, reporting its `kind`
|
|
8
8
|
// ('lockfile' | 'bundle'). Lockfiles are JSON starting with `{`; bundles are brotli-compressed
|
|
9
9
|
// JSON — sniff the leading byte to route to the right parser so its diagnostic surfaces on failure.
|
|
10
|
+
// A Lockfile or Bundle in place of the path (one built in memory) is taken as it is.
|
|
10
11
|
export function parseFileWithKind(file) {
|
|
12
|
+
if (file instanceof Lockfile) return { kind: 'lockfile', artifact: file }
|
|
13
|
+
if (file instanceof Bundle) return { kind: 'bundle', artifact: file }
|
|
11
14
|
let buf
|
|
12
15
|
try {
|
|
13
16
|
buf = readFileSync(file)
|
|
@@ -24,9 +27,10 @@ export function parseFileWithKind(file) {
|
|
|
24
27
|
}
|
|
25
28
|
let text
|
|
26
29
|
try {
|
|
27
|
-
text =
|
|
30
|
+
text = brotliDecompressStrict(buf).toString('utf8')
|
|
28
31
|
} catch (cause) {
|
|
29
|
-
|
|
32
|
+
const why = cause.code === 'ERR_TRAILING_JUNK_AFTER_STREAM_END' ? 'bytes after its brotli stream' : 'not brotli'
|
|
33
|
+
throw new Error(`Failed to read ${file} as a stasis bundle (${why})`, { cause })
|
|
30
34
|
}
|
|
31
35
|
try {
|
|
32
36
|
return { kind: 'bundle', artifact: Bundle.parse(text) }
|