@exodus/stasis 1.0.0-beta.14 → 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.
@@ -1,84 +1,79 @@
1
1
  import { createRequire, isBuiltin } from 'node:module'
2
- import { dirname, isAbsolute, join } from 'node:path'
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
- // Adapter that drives the PROJECT's own `metro-resolver` from stasis's static scanner, so
11
- // `stasis bundle --metro --metro-resolver` resolves modules EXACTLY the way that project's
12
- // installed Metro does -- rather than the hand-rolled Metro/RN approximation in
13
- // resolve-fields.js. `metro-resolver` is a leaf of the Metro toolchain (it takes a context of
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
- // 'f' | 'd' | null for a path, without throwing.
29
- function pathType(p) {
30
- const s = diskHost.stat(p)
31
- return s?.isFile() ? 'f' : s?.isDirectory() ? 'd' : null
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
- // A `.d.ts` is types-only, erased at runtime, so the resolver must never land on one: report it as
35
- // non-existent to Metro's filesystem hooks and a package whose entry points at a declaration falls
36
- // through to its real `.js`. Only the RESOLUTION hooks use this -- getPackageForModule's own
37
- // dir-vs-file probe stays on raw pathType (it locates package scopes, never a module target).
38
- const resolvableType = (p) => (isTypeDeclaration(p) ? null : pathType(p))
39
-
40
- // Metro's `getPackageForModule`: the closest package scope for an absolute candidate path
41
- // (which need not exist). The candidate can be a package DIRECTORY (a bare import lands on
42
- // `<node_modules>/<pkg>`), so probing starts at the path itself, then walks up. `packageRelativePath`
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
- // Build a resolver bound to a platform. `metro-resolver` is required from `projectDir` so we
60
- // honour the version the project's Metro uses; a missing package throws with actionable guidance.
61
- // `sourceExts` are the extensions Metro probes (kept to what a source bundle can carry, so the
62
- // resolver never lands on a file the bundle would reject). `mainFields` drives the browser-field
63
- // spec; `conditionNames` are the extra `exports`/`imports` conditions on top of the ones Metro
64
- // derives itself (default + require|import + platform); `assetExts` the extensions it takes as assets.
65
- export function createMetroResolver({
66
- projectDir,
67
- platform,
68
- sourceExts = ['js', 'jsx', 'json', 'ts', 'tsx'],
69
- mainFields = ['react-native', 'browser', 'main'],
70
- conditionNames = ['react-native'],
71
- conditionsByPlatform = { web: ['browser'] },
72
- enablePackageExports = true,
73
- assetExts = METRO_ASSET_EXTS,
74
- host = diskHost,
75
- } = {}) {
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 } = {}) {
76
72
  // It loads the project's metro-resolver, which reads the disk: never off it.
77
73
  if (host !== diskHost) throw new Error('createMetroResolver: metro-resolver reads the disk, so it is not supported off disk')
78
- const require = createRequire(join(projectDir, 'noop.js'))
79
- let resolve
74
+ let metroResolver
80
75
  try {
81
- ;({ resolve } = require('metro-resolver'))
76
+ metroResolver = createRequire(join(projectDir, 'noop.js'))('metro-resolver')
82
77
  } catch (cause) {
83
78
  throw new Error(
84
79
  `StasisMetroResolver: couldn't load 'metro-resolver' from ${projectDir}. --metro-resolver ` +
@@ -87,65 +82,21 @@ export function createMetroResolver({
87
82
  { cause }
88
83
  )
89
84
  }
90
-
91
- // A React Native app has no Node builtins by default; Metro only prefers native suffixes off web.
92
- const base = {
93
- allowHaste: false,
94
- // The asset extensions (Metro's defaults, else the project's), resolved as Metro's DependencyGraph
95
- // resolves them.
85
+ const resolve = createRnMetroResolver({
86
+ host: metroHost(host, mainFields),
87
+ sourceExts,
96
88
  assetExts,
97
- customResolverOptions: {},
98
- disableHierarchicalLookup: false,
99
- doesFileExist: (p) => resolvableType(p) === 'f',
100
- extraNodeModules: null,
101
- dev: false,
102
- getPackage: (packageJsonPath) => readJson(packageJsonPath),
103
- getPackageForModule,
104
- fileSystemLookup: (p) => {
105
- const abs = isAbsolute(p) ? p : join(projectDir, p)
106
- const type = resolvableType(abs)
107
- if (!type) return { exists: false }
108
- let realPath = abs
109
- try {
110
- realPath = diskHost.realpath(abs)
111
- } catch { /* keep the lexical path when realpath fails (e.g. a broken symlink) */ }
112
- return { exists: true, type, realPath }
113
- },
89
+ assetResolutions,
114
90
  mainFields,
115
- nodeModulesPaths: [],
91
+ conditionNames,
92
+ conditionsByPlatform,
116
93
  preferNativePlatform: platform !== 'web',
117
- resolveAsset: (dirPath, assetName, ext) => metroAssetCandidates(dirPath, assetName, ext),
118
- resolveHasteModule: () => null,
119
- resolveHastePackage: () => null,
120
- // Inert placeholder: `resolve` redirects via its own bundled helper, never this (see header).
121
- redirectModulePath: (modulePath) => modulePath,
122
- sourceExts,
123
- unstable_conditionNames: conditionNames,
124
- unstable_conditionsByPlatform: conditionsByPlatform,
125
- unstable_enablePackageExports: enablePackageExports,
126
- unstable_incrementalResolution: false,
127
- unstable_logWarning: () => {}, // a static build must not spam on exports fallbacks
128
- }
129
-
130
- return function resolveOne(parentFile, specifier, callConditions) {
131
- // Metro splits `exports` on whether the edge was an ESM import vs a CJS require. scan.js hands
132
- // us the parent's format-derived condition set, so 'import' membership is that signal.
133
- const isESMImport = callConditions instanceof Set ? callConditions.has('import') : false
134
- const context = { ...base, originModulePath: parentFile, isESMImport }
135
- let res
136
- try {
137
- res = resolve(context, specifier, platform)
138
- } catch {
139
- // Metro carries no Node builtins: an unmapped builtin fails to resolve here. The browser-field
140
- // remap of a builtin (`{"crypto": false}` / a shim) is handled inside resolve() before this.
141
- if (isBuiltin(specifier)) return { builtin: true }
142
- return null
143
- }
144
- if (!res) return null
145
- if (res.type === 'empty') return { empty: true }
146
- if (res.type === 'sourceFile') return { url: pathToFileURL(res.filePath).toString() }
147
- // An asset's files are it and its scale variants: Metro's graph takes the lowest path for the module.
148
- if (res.type === 'assetFiles' && res.filePaths?.length) return { url: pathToFileURL(lowestPath(res.filePaths)).toString() }
149
- 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))
150
101
  }
151
102
  }
package/src/parse.js CHANGED
@@ -7,7 +7,10 @@ import { Lockfile } from '@exodus/stasis-core/lockfile'
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)