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

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.
@@ -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 { readFile } from 'node:fs/promises'
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
- function resolveRelativeImport(specifier, fromFile) {
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 = isRelativeImport(specifier)
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,415 @@
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'
24
+
25
+ import { parseMetroAssetName } from '@exodus/stasis-plugins/metro-native'
26
+ import { METRO_SOURCE_EXTS } from './resolve-fields.js'
27
+
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.
31
+ export const ASSET_REGISTRY = 'react-native/Libraries/Image/AssetRegistry'
32
+ const PUBLIC_PATH = '/assets'
33
+
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
+ const REGISTRY_ROOT = /^((?:.*\/)?node_modules\/react-native)\/Libraries\/Image\/AssetRegistry\./u
322
+ export function assetRegistryResolver(platform, carried) {
323
+ const pick = (root) => {
324
+ for (const ext of METRO_SOURCE_EXTS) {
325
+ for (const suffix of [`.${platform}`, '.native', '']) {
326
+ const file = `${root}/Libraries/Image/AssetRegistry${suffix}.${ext}`
327
+ if (carried.has(file)) return file
328
+ }
329
+ }
330
+ return undefined
331
+ }
332
+ const roots = new Set([...carried.keys()].map((file) => REGISTRY_ROOT.exec(file)?.[1]).filter((root) => root !== undefined && pick(root) !== undefined))
333
+ const nearest = (rel) => {
334
+ for (let dir = posix.dirname(rel); ; dir = posix.dirname(dir)) {
335
+ const root = posix.join(dir, 'node_modules', 'react-native')
336
+ if (posix.basename(dir) !== 'node_modules' && roots.has(root)) return root
337
+ if (dir === '.' || dir === '/' || dir.startsWith('..')) return undefined
338
+ }
339
+ }
340
+ return (rel) => {
341
+ const root = roots.size === 1 ? [...roots][0] : nearest(rel)
342
+ if (root !== undefined) return pick(root)
343
+ 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
+ )
348
+ }
349
+ throw new Error(`stasis build: --metro found several ${ASSET_REGISTRY} for '${rel}', none of them nearest: ${[...roots].join(', ')}`)
350
+ }
351
+ }
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
+ }
@@ -61,7 +61,7 @@ function getPackageForModule(absModulePath) {
61
61
  // `sourceExts` are the extensions Metro probes (kept to what a source bundle can carry, so the
62
62
  // resolver never lands on a file the bundle would reject). `mainFields` drives the browser-field
63
63
  // spec; `conditionNames` are the extra `exports`/`imports` conditions on top of the ones Metro
64
- // derives itself (default + require|import + platform).
64
+ // derives itself (default + require|import + platform); `assetExts` the extensions it takes as assets.
65
65
  export function createMetroResolver({
66
66
  projectDir,
67
67
  platform,
@@ -70,6 +70,7 @@ export function createMetroResolver({
70
70
  conditionNames = ['react-native'],
71
71
  conditionsByPlatform = { web: ['browser'] },
72
72
  enablePackageExports = true,
73
+ assetExts = METRO_ASSET_EXTS,
73
74
  host = diskHost,
74
75
  } = {}) {
75
76
  // It loads the project's metro-resolver, which reads the disk: never off it.
@@ -90,8 +91,9 @@ export function createMetroResolver({
90
91
  // A React Native app has no Node builtins by default; Metro only prefers native suffixes off web.
91
92
  const base = {
92
93
  allowHaste: false,
93
- // Metro's default asset extensions, resolved as Metro's DependencyGraph resolves them.
94
- assetExts: METRO_ASSET_EXTS,
94
+ // The asset extensions (Metro's defaults, else the project's), resolved as Metro's DependencyGraph
95
+ // resolves them.
96
+ assetExts,
95
97
  customResolverOptions: {},
96
98
  disableHierarchicalLookup: false,
97
99
  doesFileExist: (p) => resolvableType(p) === 'f',
package/src/parse.js CHANGED
@@ -1,6 +1,6 @@
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
 
@@ -24,9 +24,10 @@ export function parseFileWithKind(file) {
24
24
  }
25
25
  let text
26
26
  try {
27
- text = brotliDecompressSync(buf).toString('utf8')
27
+ text = brotliDecompressStrict(buf).toString('utf8')
28
28
  } catch (cause) {
29
- throw new Error(`Failed to read ${file} as a stasis bundle (not brotli)`, { cause })
29
+ const why = cause.code === 'ERR_TRAILING_JUNK_AFTER_STREAM_END' ? 'bytes after its brotli stream' : 'not brotli'
30
+ throw new Error(`Failed to read ${file} as a stasis bundle (${why})`, { cause })
30
31
  }
31
32
  try {
32
33
  return { kind: 'bundle', artifact: Bundle.parse(text) }