@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.
@@ -4,7 +4,7 @@ import { resolve } from 'node:path'
4
4
  import { createClient } from '@preventive/upstream/github.js'
5
5
  import { buildGitHubBundle } from '../vfs-bundle/github.js'
6
6
  import { debugTimed } from './bundle.js'
7
- import { auditTokens, withNpmToken } from './tokens.js'
7
+ import { githubToken, withNpmToken } from './tokens.js'
8
8
  import { bundledSummary, unpackedSummary, writeBundle, writeFile } from './output.js'
9
9
 
10
10
  // The longest file name ext4, APFS and NTFS take: 255 bytes, or characters, ours being ASCII.
@@ -32,16 +32,15 @@ export function githubBundleFile({ github, directory, commit }) {
32
32
  // brotli-compressed to `output` (githubBundleFile's name for it by default, of the directory
33
33
  // bundled, the one a `path` gives too; `-` for stdout), and a JS bundle's lockfile to `lockfile`
34
34
  // where given; then it says how many packages it unpacked, and what it bundled.
35
- // The tree is fetched with GITHUB_TOKEN from `env` where it is set, else with auditTokens(home)'s
36
- // `token` (tokens.js); nothing else of `env` is read. Where process.env gives the npm client no
37
- // token, it is given auditTokens(home)'s `npmToken`, else the one `<home>/.npmrc` gives npm's
38
- // registry, while the bundle is built (tokens.js's withNpmToken).
35
+ // GitHub is asked with githubToken's token, `env`'s GITHUB_TOKEN where it is set, nothing else of
36
+ // `env` being read; npm, with withNpmToken's (tokens.js).
39
37
  export async function githubBundleCommand({ cwd = process.cwd(), env = process.env, home, output, lockfile, brotliQuality, client, ...options } = {}) {
40
- const audit = auditTokens(home)
41
- const built = await withNpmToken({ home, audit }, () => buildGitHubBundle({ ...options, lockfile, client: client ?? createClient({ token: env.GITHUB_TOKEN || audit.token || null }) }))
38
+ const built = await withNpmToken(home, () => buildGitHubBundle({ ...options, lockfile, client: client ?? createClient({ token: githubToken({ env, home }) }) }))
42
39
  const { directory } = built
40
+ // Built for --lockfile alone, before anything is written, as `stasis bundle` builds it.
41
+ const lockData = lockfile === undefined ? undefined : built.lockfile.serialize()
43
42
  const dest = await debugTimed('Wrote the bundle', () => writeBundle(cwd, output ?? githubBundleFile({ github: options.github, directory, commit: built.bundle.repo.commit }), built.bundle.serialize(), brotliQuality))
44
- if (lockfile !== undefined) writeFile(resolve(cwd, lockfile), built.lockfile.serialize())
43
+ if (lockData !== undefined) writeFile(resolve(cwd, lockfile), lockData)
45
44
  const from = `${options.github}@${built.bundle.repo.commit}${directory ? `/${directory}` : ''}`
46
45
  console.warn(unpackedSummary(built.stats))
47
46
  console.warn(bundledSummary(built.bundle.sources.size, built.bundle.modules, from, dest))
package/src/cmd/tokens.js CHANGED
@@ -24,6 +24,12 @@ export function auditTokens(home) {
24
24
  return config === null ? {} : { token: asToken(config.token), npmToken: asToken(config.npmToken) }
25
25
  }
26
26
 
27
+ // The GitHub token: `env`'s GITHUB_TOKEN where it is set, else, as a fallback, auditTokens(home)'s,
28
+ // only read then. -> it, or null where there is none
29
+ export function githubToken({ env = process.env, home } = {}) {
30
+ return env.GITHUB_TOKEN || auditTokens(home).token || null
31
+ }
32
+
27
33
  // A line of an .npmrc giving npm's own registry an npm token, exactly as npm writes it: no other
28
34
  // registry's, no variable for npm to expand, and nothing else on the line.
29
35
  const NPMRC_LINE = /^\/\/registry\.npmjs\.org\/:_authToken=(npm_[\dA-Za-z]+)\r?$/u
@@ -47,12 +53,12 @@ export function npmrcToken(home) {
47
53
  }
48
54
 
49
55
  // Run `fn`, with a token for the npm client where process.env gives it none (none of
50
- // NPM_TOKEN_VARS set and not empty), as a fallback: auditTokens(home)'s `npmToken` (`audit`, where
51
- // it is read already), else npmrcToken(home)'s, each file only read then. That token is
52
- // STASIS_NPM_TOKEN in process.env while `fn` runs, for the client to read, and process.env is as it
53
- // was after, unless something else set STASIS_NPM_TOKEN meanwhile. -> what `fn` gives
54
- export async function withNpmToken({ home, audit } = {}, fn) {
55
- const token = NPM_TOKEN_VARS.some((name) => process.env[name]) ? undefined : ((audit ?? auditTokens(home)).npmToken ?? npmrcToken(home))
56
+ // NPM_TOKEN_VARS set and not empty), as a fallback: auditTokens(home)'s `npmToken`, else
57
+ // npmrcToken(home)'s, each file only read then. That token is STASIS_NPM_TOKEN in process.env while
58
+ // `fn` runs, for the client to read, and process.env is as it was after, unless something else set
59
+ // STASIS_NPM_TOKEN meanwhile. -> what `fn` gives
60
+ export async function withNpmToken(home, fn) {
61
+ const token = NPM_TOKEN_VARS.some((name) => process.env[name]) ? undefined : (auditTokens(home).npmToken ?? npmrcToken(home))
56
62
  if (token === undefined) return fn()
57
63
  const before = process.env.STASIS_NPM_TOKEN
58
64
  process.env.STASIS_NPM_TOKEN = token
package/src/define.js CHANGED
@@ -9,6 +9,11 @@ import { isPlainObject } from '@exodus/stasis-core/util'
9
9
  // no test Metro wouldn't, after React Native's Babel transforms, so a --metro bundle never lacks a
10
10
  // file Metro's graph holds.
11
11
 
12
+ // The values Metro's release build (`dev: false`, `react-native bundle --dev false`) inlines, and its
13
+ // prelude gives the globals: what `stasis bundle --metro` and `stasis build --metro` define by
14
+ // default, for each name no define given (a flag or the entry's `define`) gives a value of its own.
15
+ export const METRO_RELEASE_DEFINE = Object.freeze({ __DEV__: false, 'process.env.NODE_ENV': 'production' })
16
+
12
17
  // A defined name: an identifier, or a dotted path of them (`process.env.NODE_ENV`).
13
18
  const NAME = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/u
14
19
 
package/src/flow.js CHANGED
@@ -1,6 +1,8 @@
1
1
  // --flow, for `stasis bundle` (the scan) and `stasis build`: Flow type syntax stripped from a JS-family
2
- // file the parser can't read otherwise, by flow-remove-types -- stasis's own dependency, resolved from
3
- // stasis itself (never from the project) and loaded lazily, only under --flow.
2
+ // file, as Metro's Babel strips it (@react-native/babel-preset): one marked `@flow` (hasFlowPragma)
3
+ // whatever else it holds, any other where the parser can't read it as it is. By flow-remove-types --
4
+ // stasis's own dependency, resolved from stasis itself (never from the project) and loaded lazily,
5
+ // only under --flow, which --metro turns on.
4
6
  import { createRequire } from 'node:module'
5
7
 
6
8
  // Flow type syntax lives in the JS (non-TS) family: flow-remove-types over a .ts/.tsx file would
@@ -8,15 +10,33 @@ import { createRequire } from 'node:module'
8
10
  // flow-remove-types preserves JSX.
9
11
  export const FLOW_EXTS = new Set(['.js', '.cjs', '.mjs', '.jsx'])
10
12
 
13
+ // Whether `source` holds `@flow`, the pragma marking a Flow file, anywhere in it, as React Native's
14
+ // Babel preset finds it (/@flow/), to parse the file with hermes-parser, as Flow throughout: --flow
15
+ // strips such a file whether or not it parses as it is.
16
+ export const hasFlowPragma = (source) => source.includes('@flow')
17
+
11
18
  let flowRemoveTypes
19
+ // A comment marking a file `@noflow`, in which flow-remove-types reads syntax both Flow and JS can
20
+ // read (`f<T>(x)`, `a < b > (c)`) as JS (hermes-parser's `flow: 'detect'`), and none other; and
21
+ // what it leaves of it, the pragma blanked.
22
+ const NOFLOW = '\n/* @noflow */'
23
+ const NOFLOW_STRIPPED = `\n/* ${' '.repeat('@noflow'.length)} */`
12
24
 
13
25
  // `source` with its Flow type syntax blanked to whitespace in place, so byte offsets and every import
14
- // specifier are kept. `all: true` ignores the @flow/@noflow pragma (React Native's sources mix both).
26
+ // specifier are kept, read as Metro's Babel reads it: a file marked `@flow` (hasFlowPragma) as Flow
27
+ // throughout (`all: true`), as hermes-parser parses it there, so `f<T>(x)` is a call with a type
28
+ // argument; any other as Babel's own Flow parser reads it (`all: false`), its annotations Flow's and
29
+ // syntax JS can read too JS's (`a < b > (c)`, comparisons). flow-remove-types reads it so only in a
30
+ // file marked `@noflow`, so one not marked yet is, past its end, and cut off again.
15
31
  // Types only: Flow syntax that is code -- `component` and `hook` declarations, `enum`s -- stays. An
16
32
  // import listing types alone (`import { type A } from`) stays as `import {} from`, or with
17
33
  // `removeEmptyImports` goes whole, as Babel's Flow transform drops it. Throws where flow-remove-types
18
34
  // can't parse `source`.
19
35
  export function stripFlowTypes(source, { removeEmptyImports = false } = {}) {
20
36
  flowRemoveTypes ??= createRequire(import.meta.url)('flow-remove-types')
21
- return flowRemoveTypes(source, { all: true, removeEmptyImports }).toString()
37
+ if (hasFlowPragma(source)) return flowRemoveTypes(source, { all: true, removeEmptyImports }).toString()
38
+ if (source.includes('@noflow')) return flowRemoveTypes(source, { removeEmptyImports }).toString()
39
+ const stripped = flowRemoveTypes(source + NOFLOW, { removeEmptyImports }).toString()
40
+ if (!stripped.endsWith(NOFLOW_STRIPPED)) throw new Error('flow-remove-types left the @noflow comment stasis appended')
41
+ return stripped.slice(0, -NOFLOW_STRIPPED.length)
22
42
  }
@@ -11,306 +11,20 @@
11
11
  //
12
12
  // from every file of the asset in its directory (each scale, `logo@2x.png`; those for the platform,
13
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`
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`
15
17
  // (@react-native/metro-config's), the one `stasis bundle --metro` carries for an asset. A project's
16
18
  // own `assetRegistryPath`, `publicPath` (Metro's default `/assets` here) and `assetPlugins` are read off
17
19
  // 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'
20
+ import { posix } from 'node:path'
24
21
 
25
- import { parseMetroAssetName } from '@exodus/stasis-plugins/metro-native'
26
22
  import { METRO_SOURCE_EXTS } from './resolve-fields.js'
27
23
 
28
24
  // The asset registry the module Metro builds of an asset requires: React Native's Metro config's
29
25
  // `assetRegistryPath` (@react-native/metro-config's), where a project's own isn't read, being code.
30
26
  // `stasis bundle --metro` carries the file it resolves to for each asset.
31
27
  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
28
 
315
29
  // The resolver of `ASSET_REGISTRY` from an asset for `platform`, as Metro resolves it, among `carried`
316
30
  // (the code files the artifact carries: a Map or Set keyed by their paths from the project root): the
@@ -349,67 +63,3 @@ export function assetRegistryResolver(platform, carried) {
349
63
  throw new Error(`stasis build: --metro found several ${ASSET_REGISTRY} for '${rel}', none of them nearest: ${[...roots].join(', ')}`)
350
64
  }
351
65
  }
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
- }