@exodus/stasis 1.0.0-beta.14 → 1.0.0-beta.16

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.
Files changed (67) hide show
  1. package/README.md +2 -1
  2. package/bin/stasis.js +99 -16
  3. package/package.json +22 -9
  4. package/src/audit-corrections.js +11 -42
  5. package/src/audit.js +241 -190
  6. package/src/babel.js +39 -122
  7. package/src/bundle-from-lockfile.js +9 -21
  8. package/src/bundle-reader.js +5 -9
  9. package/src/bundle.js +0 -3
  10. package/src/cmd/build.js +82 -174
  11. package/src/cmd/bundle-options.js +113 -167
  12. package/src/cmd/bundle.js +942 -1294
  13. package/src/cmd/diff.js +1 -4
  14. package/src/cmd/github-bundle.js +21 -26
  15. package/src/cmd/output.js +15 -12
  16. package/src/cmd/sbom.js +3 -8
  17. package/src/cmd/tokens.js +16 -23
  18. package/src/define.js +36 -94
  19. package/src/diff.js +72 -128
  20. package/src/esbuild.js +0 -4
  21. package/src/flow.js +18 -13
  22. package/src/installed.js +265 -0
  23. package/src/json-stream.js +4 -9
  24. package/src/loader-mock.js +3 -8
  25. package/src/loader.js +1 -5
  26. package/src/loaders/bash.js +41 -93
  27. package/src/loaders/cargo.js +298 -805
  28. package/src/loaders/foundry.js +109 -285
  29. package/src/loaders/paths.js +13 -13
  30. package/src/loaders/php.js +210 -489
  31. package/src/loaders/rust.js +507 -1430
  32. package/src/loaders/solidity-ownership.js +48 -128
  33. package/src/loaders/solidity.js +39 -122
  34. package/src/loaders/toml.js +7 -17
  35. package/src/lockfile.js +0 -3
  36. package/src/metro-assets.js +10 -384
  37. package/src/metro-resolver.js +58 -134
  38. package/src/metro-transformer.js +0 -5
  39. package/src/metro.js +0 -4
  40. package/src/mock.js +32 -80
  41. package/src/parse.js +4 -4
  42. package/src/prune.js +0 -3
  43. package/src/resolve-fields.js +137 -532
  44. package/src/resolve-node.js +27 -45
  45. package/src/resolve-typescript.js +166 -298
  46. package/src/rollup.js +0 -4
  47. package/src/run-installed.js +10 -0
  48. package/src/sbom.js +52 -128
  49. package/src/scan.js +142 -284
  50. package/src/sixel.js +310 -0
  51. package/src/table.js +63 -31
  52. package/src/validate-notes.d.ts +19 -0
  53. package/src/validate-notes.js +72 -0
  54. package/src/validate.d.ts +159 -0
  55. package/src/validate.js +596 -522
  56. package/src/vfs-bundle/entries.js +40 -57
  57. package/src/vfs-bundle/github.js +80 -122
  58. package/src/vfs-bundle/glob.js +4 -45
  59. package/src/vfs-bundle/lazy.js +27 -56
  60. package/src/vfs-bundle/prisma.js +235 -105
  61. package/src/vfs-bundle/soldeer.js +28 -49
  62. package/src/vfs-bundle/tree.js +295 -318
  63. package/src/vfs-bundle/yarnclean.js +10 -31
  64. package/src/vfs-bundle.js +23 -64
  65. package/src/webpack.js +0 -4
  66. package/src/why.js +78 -232
  67. package/src/installed-commits.js +0 -184
@@ -1,324 +1,16 @@
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. The asset registry is React Native's Metro config's `assetRegistryPath`
15
- // (@react-native/metro-config's), the one `stasis bundle --metro` carries for an asset. A project's
16
- // own `assetRegistryPath`, `publicPath` (Metro's default `/assets` here) and `assetPlugins` are read off
17
- // its Metro config, which is code, and aren't.
18
- //
19
- // Mirrors Metro 0.83 (src/Assets.js, src/lib/imageSize.js, src/node-haste/lib/AssetPaths.js) and
20
- // @react-native/community-cli-plugin 0.81 (commands/bundle/saveAssets.js and its helpers), both MIT
21
- // licensed, Copyright (c) Meta Platforms, Inc. and affiliates.
22
- import { createHash } from 'node:crypto'
23
- import { join, posix } from 'node:path'
1
+ // `stasis build --metro=PLATFORM`: a Metro asset built into the module Metro builds of it and copied out as
2
+ // `--assets-dest` copies it, from the artifact's bytes, never disk: @preventive/rn's, but for the registry it requires.
3
+ import { posix } from 'node:path'
24
4
 
25
- import { parseMetroAssetName } from '@exodus/stasis-plugins/metro-native'
26
5
  import { METRO_SOURCE_EXTS } from './resolve-fields.js'
27
6
 
28
- // The asset registry the module Metro builds of an asset requires: React Native's Metro config's
29
- // `assetRegistryPath` (@react-native/metro-config's), where a project's own isn't read, being code.
30
- // `stasis bundle --metro` carries the file it resolves to for each asset.
7
+ // React Native's Metro config's `assetRegistryPath`: a project's own would be read off its Metro config, which is code.
31
8
  export const ASSET_REGISTRY = 'react-native/Libraries/Image/AssetRegistry'
32
- const PUBLIC_PATH = '/assets'
33
9
 
34
- // --- image dimensions: Metro's getImageDimensions (src/lib/imageSize.js) ------------------------
35
- //
36
- // The parser for the asset's type, else the first of the others that reads the bytes; an image none
37
- // reads, or whose dimensions aren't positive and finite, is an invalid asset.
38
-
39
- const MAX_SVG_HEADER_LENGTH = 64 * 1024
40
- const KTX1_IDENTIFIER = Buffer.from([0xab, 0x4b, 0x54, 0x58, 0x20, 0x31, 0x31, 0xbb, 0x0d, 0x0a, 0x1a, 0x0a])
41
- const KTX2_IDENTIFIER = Buffer.from([0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb, 0x0d, 0x0a, 0x1a, 0x0a])
42
- const PNG_IDENTIFIER = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
43
-
44
- const hasBytes = (content, offset, length) =>
45
- Number.isSafeInteger(offset) && Number.isSafeInteger(length) && offset >= 0 && length >= 0 &&
46
- offset <= content.length && length <= content.length - offset
47
- const startsWith = (content, prefix) => hasBytes(content, 0, prefix.length) && content.subarray(0, prefix.length).equals(prefix)
48
- const readAscii = (content, start, end) => content.toString('ascii', start, end)
49
- const readUInt24LE = (content, offset) => content[offset] + content[offset + 1] * 256 + content[offset + 2] * 65536
50
-
51
- function parseBmp(content) {
52
- if (!hasBytes(content, 0, 26) || readAscii(content, 0, 2) !== 'BM') return null
53
- const dibHeaderSize = content.readUInt32LE(14)
54
- if (dibHeaderSize === 12) return { width: content.readUInt16LE(18), height: content.readUInt16LE(20) }
55
- if (dibHeaderSize < 40) return null
56
- return { width: Math.abs(content.readInt32LE(18)), height: Math.abs(content.readInt32LE(22)) }
57
- }
58
-
59
- function parseGif(content) {
60
- if (!hasBytes(content, 0, 10) || !/^GIF8[79]a$/u.test(readAscii(content, 0, 6))) return null
61
- return { width: content.readUInt16LE(6), height: content.readUInt16LE(8) }
62
- }
63
-
64
- const isStandaloneJpegMarker = (marker) => marker === 0x01 || (marker >= 0xd0 && marker <= 0xd9)
65
- const isJpegStartOfFrame = (marker) => marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc
66
-
67
- function parseJpeg(content) {
68
- if (!hasBytes(content, 0, 4) || content[0] !== 0xff || content[1] !== 0xd8) return null
69
- let offset = 2
70
- while (offset < content.length) {
71
- while (offset < content.length && content[offset] === 0xff) offset++
72
- if (offset >= content.length) return null
73
- const marker = content[offset++]
74
- if (marker === 0x00) return null
75
- if (isStandaloneJpegMarker(marker)) {
76
- if (marker === 0xd9) return null
77
- continue
78
- }
79
- if (!hasBytes(content, offset, 2)) return null
80
- const segmentLength = content.readUInt16BE(offset)
81
- if (segmentLength < 2) return null
82
- const segmentEnd = offset + segmentLength
83
- if (segmentEnd <= offset || segmentEnd > content.length) return null
84
- if (isJpegStartOfFrame(marker)) {
85
- if (segmentLength < 7) return null
86
- return { height: content.readUInt16BE(offset + 3), width: content.readUInt16BE(offset + 5) }
87
- }
88
- if (marker === 0xda) return null
89
- offset = segmentEnd
90
- }
91
- return null
92
- }
93
-
94
- function parseKtx(content) {
95
- if (hasBytes(content, 0, 64) && startsWith(content, KTX1_IDENTIFIER)) {
96
- const endianness = content.subarray(12, 16)
97
- if (endianness.equals(Buffer.from([0x01, 0x02, 0x03, 0x04]))) return { width: content.readUInt32LE(36), height: content.readUInt32LE(40) }
98
- if (endianness.equals(Buffer.from([0x04, 0x03, 0x02, 0x01]))) return { width: content.readUInt32BE(36), height: content.readUInt32BE(40) }
99
- return null
100
- }
101
- if (hasBytes(content, 0, 80) && startsWith(content, KTX2_IDENTIFIER)) return { width: content.readUInt32LE(20), height: content.readUInt32LE(24) }
102
- return null
103
- }
104
-
105
- function parsePng(content) {
106
- if (!hasBytes(content, 0, 24) || !startsWith(content, PNG_IDENTIFIER)) return null
107
- const firstChunkLength = content.readUInt32BE(8)
108
- const firstChunkType = readAscii(content, 12, 16)
109
- if (firstChunkType === 'IHDR') {
110
- if (firstChunkLength !== 13) return null
111
- return { width: content.readUInt32BE(16), height: content.readUInt32BE(20) }
112
- }
113
- // Apple's CgBI PNG: its IHDR follows the CgBI chunk.
114
- if (firstChunkType !== 'CgBI') return null
115
- const ihdrOffset = 8 + 12 + firstChunkLength
116
- if (!hasBytes(content, ihdrOffset, 24) || content.readUInt32BE(ihdrOffset) !== 13 || readAscii(content, ihdrOffset + 4, ihdrOffset + 8) !== 'IHDR') return null
117
- return { width: content.readUInt32BE(ihdrOffset + 8), height: content.readUInt32BE(ihdrOffset + 12) }
118
- }
119
-
120
- function parsePsd(content) {
121
- if (!hasBytes(content, 0, 22) || readAscii(content, 0, 4) !== '8BPS' || (content.readUInt16BE(4) !== 1 && content.readUInt16BE(4) !== 2)) return null
122
- return { height: content.readUInt32BE(14), width: content.readUInt32BE(18) }
123
- }
124
-
125
- const SVG_UNIT_FACTORS = { in: 96, cm: 96 / 2.54, em: 16, ex: 8, mm: 96 / 2.54 / 10, pc: (96 / 72) * 12, pt: 96 / 72, px: 1 }
126
-
127
- // The index of the `>` closing the tag starting at `start`, past quoted attribute values.
128
- function findTagEnd(input, start) {
129
- let quote = null
130
- for (let index = start; index < input.length; index++) {
131
- const character = input[index]
132
- if (quote !== null) {
133
- if (character === quote) quote = null
134
- } else if (character === '"' || character === "'") {
135
- quote = character
136
- } else if (character === '>') {
137
- return index
138
- }
139
- }
140
- return null
141
- }
142
-
143
- function parseSvgLength(value) {
144
- if (value === undefined || value.endsWith('%')) return null
145
- const match = /^([+]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)([a-z]*)$/iu.exec(value.trim())
146
- if (match === null) return null
147
- const unit = match[2].toLowerCase()
148
- const factor = unit === '' ? 1 : SVG_UNIT_FACTORS[unit]
149
- if (factor === undefined) return null
150
- return Math.round(Number(match[1]) * factor)
151
- }
152
-
153
- function parseSvgViewBox(value) {
154
- if (value === undefined) return null
155
- const values = value.trim().split(/[\s,]+/u).map(Number)
156
- if (values.length !== 4 || !values.every((v) => Number.isFinite(v)) || values[2] <= 0 || values[3] <= 0) return null
157
- return { width: values[2], height: values[3] }
158
- }
159
-
160
- function parseSvg(content) {
161
- const header = content.subarray(0, Math.min(content.length, MAX_SVG_HEADER_LENGTH)).toString('utf8')
162
- const rootStartMatch = /<svg(?:\s|>)/u.exec(header)
163
- if (rootStartMatch === null) return null
164
- const rootStart = rootStartMatch.index
165
- const rootEnd = findTagEnd(header, rootStart)
166
- if (rootEnd === null) return null
167
- const root = header.slice(rootStart, rootEnd + 1)
168
- const attributes = {}
169
- for (const match of root.matchAll(/\b(width|height|viewBox)\s*=\s*(?:"([^"]*)"|'([^']*)')/giu)) {
170
- attributes[match[1].toLowerCase()] = match[2] ?? match[3]
171
- }
172
- const width = parseSvgLength(attributes.width)
173
- const height = parseSvgLength(attributes.height)
174
- if (width !== null && height !== null) return { width, height }
175
- const viewBox = parseSvgViewBox(attributes.viewbox)
176
- if (viewBox === null) return null
177
- if (width !== null) return { width, height: Math.floor(width / (viewBox.width / viewBox.height)) }
178
- if (height !== null) return { width: Math.floor(height * (viewBox.width / viewBox.height)), height }
179
- return viewBox
180
- }
181
-
182
- const readTiffUInt16 = (content, offset, isBigEndian) => (isBigEndian ? content.readUInt16BE(offset) : content.readUInt16LE(offset))
183
- const readTiffUInt32 = (content, offset, isBigEndian) => (isBigEndian ? content.readUInt32BE(offset) : content.readUInt32LE(offset))
184
-
185
- function readTiffDimension(content, entryOffset, isBigEndian) {
186
- const type = readTiffUInt16(content, entryOffset + 2, isBigEndian)
187
- const count = readTiffUInt32(content, entryOffset + 4, isBigEndian)
188
- if (count !== 1) return null
189
- if (type === 3) return readTiffUInt16(content, entryOffset + 8, isBigEndian)
190
- if (type === 4) return readTiffUInt32(content, entryOffset + 8, isBigEndian)
191
- return null
192
- }
193
-
194
- function parseTiff(content) {
195
- if (!hasBytes(content, 0, 8)) return null
196
- const byteOrder = readAscii(content, 0, 2)
197
- const isBigEndian = byteOrder === 'MM'
198
- if ((!isBigEndian && byteOrder !== 'II') || readTiffUInt16(content, 2, isBigEndian) !== 42) return null
199
- const ifdOffset = readTiffUInt32(content, 4, isBigEndian)
200
- if (!hasBytes(content, ifdOffset, 2)) return null
201
- const entryCount = readTiffUInt16(content, ifdOffset, isBigEndian)
202
- const entriesOffset = ifdOffset + 2
203
- if (entryCount > Math.floor((content.length - entriesOffset) / 12)) return null
204
- let width
205
- let height
206
- for (let index = 0; index < entryCount; index++) {
207
- const entryOffset = entriesOffset + index * 12
208
- const tag = readTiffUInt16(content, entryOffset, isBigEndian)
209
- if (tag !== 256 && tag !== 257) continue
210
- const value = readTiffDimension(content, entryOffset, isBigEndian)
211
- if (value === null) return null
212
- if (tag === 256) width = value
213
- else height = value
214
- }
215
- return width !== undefined && height !== undefined ? { width, height } : null
216
- }
217
-
218
- function parseWebp(content) {
219
- if (!hasBytes(content, 0, 20) || readAscii(content, 0, 4) !== 'RIFF' || readAscii(content, 8, 12) !== 'WEBP') return null
220
- let offset = 12
221
- while (hasBytes(content, offset, 8)) {
222
- const chunkType = readAscii(content, offset, offset + 4)
223
- const chunkLength = content.readUInt32LE(offset + 4)
224
- const dataOffset = offset + 8
225
- if (!hasBytes(content, dataOffset, chunkLength)) return null
226
- if (chunkType === 'VP8X' && chunkLength >= 10) {
227
- return { width: 1 + readUInt24LE(content, dataOffset + 4), height: 1 + readUInt24LE(content, dataOffset + 7) }
228
- }
229
- if (chunkType === 'VP8L' && chunkLength >= 5 && content[dataOffset] === 0x2f) {
230
- return {
231
- width: 1 + (((content[dataOffset + 2] & 0x3f) << 8) | content[dataOffset + 1]),
232
- height: 1 + (((content[dataOffset + 4] & 0x0f) << 10) | (content[dataOffset + 3] << 2) | ((content[dataOffset + 2] & 0xc0) >> 6)),
233
- }
234
- }
235
- if (chunkType === 'VP8 ' && chunkLength >= 10 && content[dataOffset + 3] === 0x9d && content[dataOffset + 4] === 0x01 && content[dataOffset + 5] === 0x2a) {
236
- return { width: content.readUInt16LE(dataOffset + 6) & 0x3fff, height: content.readUInt16LE(dataOffset + 8) & 0x3fff }
237
- }
238
- const nextOffset = dataOffset + chunkLength + (chunkLength % 2)
239
- if (nextOffset <= offset) return null
240
- offset = nextOffset
241
- }
242
- return null
243
- }
244
-
245
- // Its keys are Metro's image types (isAssetTypeAnImage); its parsers, in order, its fallbacks.
246
- const IMAGE_PARSERS = { bmp: parseBmp, gif: parseGif, jpeg: parseJpeg, jpg: parseJpeg, ktx: parseKtx, png: parsePng, psd: parsePsd, svg: parseSvg, tiff: parseTiff, webp: parseWebp }
247
- const FALLBACK_PARSERS = [...new Set(Object.values(IMAGE_PARSERS))]
248
-
249
- const tryParse = (parser, content) => {
250
- try {
251
- return parser?.(content) ?? null
252
- } catch {
253
- return null
254
- }
255
- }
256
-
257
- // The image `content` of an asset of `type` (`file` naming it in errors) is: its width and height.
258
- export function imageDimensions(type, content, file) {
259
- const parser = IMAGE_PARSERS[type]
260
- let dimensions = null
261
- for (const candidate of [parser, ...FALLBACK_PARSERS.filter((fallback) => fallback !== parser)]) {
262
- dimensions = tryParse(candidate, content)
263
- if (dimensions !== null) break
264
- }
265
- if (dimensions === null || !Number.isFinite(dimensions.width) || !Number.isFinite(dimensions.height) || dimensions.width <= 0 || dimensions.height <= 0) {
266
- throw new Error(`Invalid ${type} image asset: ${file}`)
267
- }
268
- return dimensions
269
- }
270
-
271
- // --- the asset module ---------------------------------------------------------------------------
272
-
273
- // Metro's descriptor of the asset module `rel` (its path from the project root, posix) for `platform`,
274
- // of `files` (its files, metroAssetFiles' set: their paths from the project root), whose bytes
275
- // `read(rel)` gives (a Buffer): getAssetData, less the keys generateAssetCodeFileAst drops (`files`,
276
- // `fileSystemLocation`). The files in scale order are `files` in the order Metro reads them, as
277
- // fs.promises.readdir lists them (libuv sorts the names bytewise), each inserted after those of a
278
- // scale it doesn't exceed. -> { descriptor, files }, `files` in scale order
279
- export function metroAssetDescriptor(rel, { platform, files, read }) {
280
- const own = parseMetroAssetName(posix.basename(rel), platform)
281
- if (own === null || files.length === 0) throw new Error(`Asset not found: ${rel} for platform: ${platform}`)
282
- const byScale = files
283
- .map((file) => ({ file, name: Buffer.from(posix.basename(file)), resolution: parseMetroAssetName(posix.basename(file), platform).resolution }))
284
- .toSorted((a, b) => a.resolution - b.resolution || Buffer.compare(a.name, b.name))
285
- const contents = byScale.map(({ file }) => read(file))
286
- const hasher = createHash('md5')
287
- for (const content of contents) hasher.update(content)
288
- const scales = byScale.map(({ resolution }) => resolution)
289
- let dimensions = null
290
- if (Object.hasOwn(IMAGE_PARSERS, own.type)) {
291
- if (contents[0].length === 0) throw new Error(`Image asset \`${byScale[0].file}\` cannot be an empty file.`)
292
- dimensions = imageDimensions(own.type, contents[0], byScale[0].file)
293
- }
294
- // An asset outside the project root takes its `..` path verbatim, as Metro joins none.
295
- const dir = posix.dirname(rel)
296
- const httpServerLocation = rel.startsWith('..') ? `${PUBLIC_PATH.replace(/\/$/u, '')}/${dir}` : posix.join(PUBLIC_PATH, dir)
297
- const descriptor = {
298
- __packager_asset: true,
299
- httpServerLocation,
300
- width: dimensions ? dimensions.width / scales[0] : undefined,
301
- height: dimensions ? dimensions.height / scales[0] : undefined,
302
- scales,
303
- hash: hasher.digest('hex'),
304
- name: own.name,
305
- type: own.type,
306
- }
307
- return { descriptor, files: byScale.map(({ file }) => file) }
308
- }
309
-
310
- // The module Metro builds of an asset of `descriptor`. Plain ES5: Metro builds it past Babel, and it
311
- // needs no downleveling for Hermes.
312
- export const metroAssetModule = (descriptor) =>
313
- `module.exports = require(${JSON.stringify(ASSET_REGISTRY)}).registerAsset(${JSON.stringify(descriptor)});\n`
314
-
315
- // The resolver of `ASSET_REGISTRY` from an asset for `platform`, as Metro resolves it, among `carried`
316
- // (the code files the artifact carries: a Map or Set keyed by their paths from the project root): the
317
- // copy of react-native in the nearest node_modules up from the asset's directory, else the only copy
318
- // (pnpm's, linked in from node_modules/.pnpm); in it, the file Metro probes first -- each of its
319
- // sourceExts, the platform's file, then the .native one, then the plain one. The copies are found once.
320
- // -> (rel) => its path, throwing where the artifact carries none, or several none of them nearest
321
10
  const REGISTRY_ROOT = /^((?:.*\/)?node_modules\/react-native)\/Libraries\/Image\/AssetRegistry\./u
11
+
12
+ // Resolved as Metro resolves it among the code files `carried` (by project path): in the react-native nearest up
13
+ // from the asset, else the only one (pnpm's). Throws where the artifact carries none, or several none of them nearest.
322
14
  export function assetRegistryResolver(platform, carried) {
323
15
  const pick = (root) => {
324
16
  for (const ext of METRO_SOURCE_EXTS) {
@@ -329,7 +21,7 @@ export function assetRegistryResolver(platform, carried) {
329
21
  }
330
22
  return undefined
331
23
  }
332
- const roots = new Set([...carried.keys()].map((file) => REGISTRY_ROOT.exec(file)?.[1]).filter((root) => root !== undefined && pick(root) !== undefined))
24
+ const roots = new Set(carried.keys().map((file) => REGISTRY_ROOT.exec(file)?.[1]).filter((root) => root !== undefined && pick(root) !== undefined))
333
25
  const nearest = (rel) => {
334
26
  for (let dir = posix.dirname(rel); ; dir = posix.dirname(dir)) {
335
27
  const root = posix.join(dir, 'node_modules', 'react-native')
@@ -341,75 +33,9 @@ export function assetRegistryResolver(platform, carried) {
341
33
  const root = roots.size === 1 ? [...roots][0] : nearest(rel)
342
34
  if (root !== undefined) return pick(root)
343
35
  if (roots.size === 0) {
344
- throw new Error(
345
- `stasis build: --metro builds '${rel}' into a module requiring ${ASSET_REGISTRY}, which the artifact doesn't carry; ` +
346
- 'bundle it with `stasis bundle --metro --resources=...` from a project with react-native installed'
347
- )
36
+ throw new Error(`stasis build: --metro builds '${rel}' into a module requiring ${ASSET_REGISTRY}, which the artifact `
37
+ + 'doesn\'t carry; bundle it with `stasis bundle --metro --resources=...` from a project with react-native installed')
348
38
  }
349
39
  throw new Error(`stasis build: --metro found several ${ASSET_REGISTRY} for '${rel}', none of them nearest: ${[...roots].join(', ')}`)
350
40
  }
351
41
  }
352
-
353
- // --- --assets-dest: @react-native/community-cli-plugin's saveAssets -----------------------------
354
-
355
- // The scales of an asset's files copied out for `platform` (filterPlatformAssetScales): iOS takes
356
- // 1x-3x, else the next one above, else the largest.
357
- const ALLOWED_SCALES = { ios: [1, 2, 3] }
358
- export function filterPlatformAssetScales(platform, scales) {
359
- const allowed = ALLOWED_SCALES[platform]
360
- if (!allowed) return scales
361
- const result = scales.filter((scale) => allowed.includes(scale))
362
- if (result.length === 0 && scales.length > 0) {
363
- const maxScale = allowed[allowed.length - 1]
364
- const above = scales.find((scale) => scale > maxScale)
365
- result.push(above ?? scales[scales.length - 1])
366
- }
367
- return result
368
- }
369
-
370
- const DRAWABLE_TYPES = new Set(['gif', 'jpeg', 'jpg', 'png', 'webp', 'xml'])
371
- const ANDROID_SUFFIXES = new Map([[0.75, 'ldpi'], [1, 'mdpi'], [1.5, 'hdpi'], [2, 'xhdpi'], [3, 'xxhdpi'], [4, 'xxxhdpi']])
372
-
373
- // An asset's Android resource name: its path, folded into one lowercase identifier.
374
- const androidResourceIdentifier = (descriptor) =>
375
- `${descriptor.httpServerLocation.replace(/^\//u, '')}/${descriptor.name}`
376
- .toLowerCase()
377
- .replace(/\//gu, '_')
378
- .replace(/([^a-z0-9_])/gu, '')
379
- .replace(/^(?:assets|assetsunstable_path)_/u, '')
380
-
381
- // Where the file of `descriptor` at `scale` is copied to under --assets-dest for `platform`: Android's
382
- // res/ layout (drawable-<density>/, raw/ for a type no drawable), else iOS' (the generic one).
383
- function assetDestPath(platform, descriptor, scale) {
384
- if (platform === 'android') {
385
- let folder = 'raw'
386
- if (DRAWABLE_TYPES.has(descriptor.type)) {
387
- const suffix = ANDROID_SUFFIXES.get(scale)
388
- if (suffix === undefined) throw new Error(`Don't know which android drawable suffix to use for asset: ${JSON.stringify(descriptor)}`)
389
- folder = `drawable-${suffix}`
390
- }
391
- return join(folder, `${androidResourceIdentifier(descriptor)}.${descriptor.type}`)
392
- }
393
- const suffix = scale === 1 ? '' : `@${scale}x`
394
- return join(descriptor.httpServerLocation.slice(1).replace(/\.\.\//gu, '_'), `${descriptor.name}${suffix}.${descriptor.type}`)
395
- }
396
-
397
- // What --assets-dest writes for `platform` of `assets` ({ descriptor, files }, files in scale order):
398
- // each file of a scale filterPlatformAssetScales keeps at its assetDestPath, and on Android raw/keep.xml,
399
- // keeping every asset's resource from shrinking. -> [{ dest, file } | { dest, contents }], `dest` from
400
- // the assets directory, `file` an asset's file (its path from the project root)
401
- export function metroAssetCopies(platform, assets) {
402
- const copies = new Map()
403
- for (const { descriptor, files } of assets) {
404
- const kept = new Set(filterPlatformAssetScales(platform, descriptor.scales))
405
- descriptor.scales.forEach((scale, i) => {
406
- if (kept.has(scale)) copies.set(files[i], assetDestPath(platform, descriptor, scale))
407
- })
408
- }
409
- const out = [...copies].map(([file, dest]) => ({ dest, file }))
410
- if (platform === 'android' && assets.length > 0) {
411
- const keep = assets.map(({ descriptor }) => `@${DRAWABLE_TYPES.has(descriptor.type) ? 'drawable' : 'raw'}/${androidResourceIdentifier(descriptor)}`)
412
- out.push({ dest: join('raw', 'keep.xml'), contents: `<resources xmlns:tools="http://schemas.android.com/tools" tools:keep="${keep.join(',')}" />\n` })
413
- }
414
- return out
415
- }
@@ -1,151 +1,75 @@
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 { isPlainObject, isTypeDeclaration } from '@exodus/stasis-core/util'
8
+ import { isDir, isSourceFile } from './resolve-typescript.js'
9
9
 
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.
10
+ // Metro's module resolution is @preventive/rn's. What stays stasis's: no `.d.ts` is a module (metroHost), a builtin
11
+ // Metro misses is a builtin, and answers take the shape scan.js expects (scanResolution).
27
12
 
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
32
- }
13
+ export const stripTypeDeclaration = (name) => name.replace(/\.d\.[mc]?ts$/iu, '')
14
+
15
+ const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
16
+ const DECLARATION = /\.d\.[cm]?ts\b/iu
33
17
 
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))
18
+ // An entry field naming a `.d.ts` names its stem, so the entry lands on the real module beside it.
19
+ function manifestStems(bytes, mainFields) {
20
+ let manifest
21
+ try {
22
+ const text = utf8.decode(bytes)
23
+ if (!DECLARATION.test(text)) return bytes
24
+ manifest = JSON.parse(text)
25
+ } catch {
26
+ return bytes
27
+ }
28
+ if (!isPlainObject(manifest)) return bytes
29
+ const typed = mainFields.filter((field) => typeof manifest[field] === 'string' && isTypeDeclaration(manifest[field]))
30
+ if (typed.length === 0) return bytes
31
+ for (const field of typed) manifest[field] = stripTypeDeclaration(manifest[field])
32
+ return Buffer.from(JSON.stringify(manifest))
33
+ }
39
34
 
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
35
+ // A `.d.ts` is types-only, erased at runtime, so the resolver never lands on one.
36
+ export function metroHost(host, mainFields = defaults.mainFields) {
37
+ return {
38
+ isFile: (path) => isSourceFile(path, host),
39
+ isDirectory: (path) => isDir(path, host),
40
+ realpath: (path) => host.realpath(path),
41
+ readFile: (path) => (basename(path) === 'package.json' ? manifestStems(host.readFile(path), mainFields) : host.readFile(path)),
56
42
  }
57
43
  }
58
44
 
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
- } = {}) {
76
- // It loads the project's metro-resolver, which reads the disk: never off it.
45
+ // Metro builds an asset of several files into the module of the lowest path (getArrayLowestItem).
46
+ const lowestPath = (paths) => paths.reduce((lowest, path) => (path < lowest ? path : lowest))
47
+
48
+ // `builtin`: whether a specifier Metro failed (null) is a Node builtin.
49
+ export function scanResolution(resolution, builtin) {
50
+ if (resolution === null) return builtin ? { builtin: true } : null
51
+ if (resolution.type === 'empty') return { empty: true }
52
+ const file = resolution.type === 'sourceFile' ? resolution.filePath : lowestPath(resolution.filePaths)
53
+ return { url: pathToFileURL(file).toString() }
54
+ }
55
+
56
+ // `--metro-resolver`: through the project's own `metro-resolver`, given the context Metro's DependencyGraph builds.
57
+ export function createMetroResolver({ projectDir, platform, sourceExts, mainFields, conditionNames, conditionsByPlatform, assetExts, assetResolutions, host = diskHost } = {}) {
77
58
  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
59
+ let metroResolver
80
60
  try {
81
- ;({ resolve } = require('metro-resolver'))
61
+ metroResolver = createRequire(join(projectDir, 'noop.js'))('metro-resolver')
82
62
  } catch (cause) {
83
- throw new Error(
84
- `StasisMetroResolver: couldn't load 'metro-resolver' from ${projectDir}. --metro-resolver ` +
85
- 'resolves through the project\'s own Metro; install it (it ships with react-native/metro) ' +
86
- 'or drop --metro-resolver to use the built-in resolver.',
87
- { cause }
88
- )
63
+ throw new Error(`StasisMetroResolver: couldn't load 'metro-resolver' from ${projectDir}. --metro-resolver resolves through the `
64
+ + 'project\'s own Metro; install it (it ships with react-native/metro) or drop --metro-resolver to use the built-in resolver.', { cause })
89
65
  }
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.
96
- 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
- },
114
- mainFields,
115
- nodeModulesPaths: [],
116
- 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
66
+ const resolve = createRnMetroResolver({
67
+ host: metroHost(host, mainFields), sourceExts, assetExts, assetResolutions, mainFields, conditionNames, conditionsByPlatform,
68
+ preferNativePlatform: platform !== 'web', metroResolver,
69
+ })
70
+ // Metro splits `exports` on whether the edge is an ESM import: `import` in scan.js's format-derived conditions.
71
+ return (parentFile, specifier, callConditions) => {
72
+ const isESMImport = callConditions instanceof Set && callConditions.has('import')
73
+ return scanResolution(resolve(parentFile, specifier, { platform, isESMImport }), isBuiltin(specifier))
150
74
  }
151
75
  }
@@ -1,6 +1 @@
1
- // Public-export adapter: backs `@exodus/stasis/metro-transformer`. The transformer
2
- // lives in @exodus/stasis-plugins (which depends on @exodus/stasis-core for State; it
3
- // drives load-mode getFile directly). withStasis() wires it as Metro's `transformerPath`;
4
- // wire it yourself only alongside a hand-wired serializer. See the source for the load
5
- // asymmetry that lets this run per-worker without cross-worker state sync.
6
1
  export * from '@exodus/stasis-plugins/metro-transformer'
package/src/metro.js CHANGED
@@ -1,5 +1 @@
1
- // Public-export adapter: backs `@exodus/stasis/metro`. The plugin lives in
2
- // @exodus/stasis-plugins (which depends on @exodus/stasis-core for State /
3
- // resolvePluginState). Internal code uses `@exodus/stasis-plugins/metro` directly;
4
- // this file exists only to back the package's `exports` map.
5
1
  export * from '@exodus/stasis-plugins/metro'