@exodus/stasis-plugins 1.0.0-rc.0 → 1.0.0-rc.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/esbuild.js +98 -117
- package/src/metro-babel-transformer.js +3 -2
- package/src/metro-native.js +16 -21
- package/src/metro-transformer.js +4 -5
- package/src/metro.js +120 -175
- package/src/plugins.js +73 -34
- package/src/rollup.js +45 -61
- package/src/webpack.js +44 -68
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@exodus/stasis-plugins",
|
|
3
|
-
"version": "1.0.0-rc.
|
|
3
|
+
"version": "1.0.0-rc.10",
|
|
4
4
|
"description": "Bundler plugins (webpack, esbuild, Rollup, Metro) for @exodus/stasis-core",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -36,6 +36,6 @@
|
|
|
36
36
|
},
|
|
37
37
|
"homepage": "https://github.com/PreventiveMeasures/stasis#readme",
|
|
38
38
|
"dependencies": {
|
|
39
|
-
"@exodus/stasis-core": "1.0.0-rc.
|
|
39
|
+
"@exodus/stasis-core": "1.0.0-rc.10"
|
|
40
40
|
}
|
|
41
41
|
}
|
package/src/esbuild.js
CHANGED
|
@@ -1,19 +1,25 @@
|
|
|
1
1
|
import { dirname, extname, isAbsolute, join, relative, resolve as resolvePath } from 'node:path'
|
|
2
|
-
import { fileURLToPath
|
|
2
|
+
import { fileURLToPath } from 'node:url'
|
|
3
3
|
import assert from 'node:assert/strict'
|
|
4
4
|
|
|
5
5
|
import { Bundle } from '@exodus/stasis-core/bundle'
|
|
6
|
-
import { assertCodeUtf8, assertPersistableAttributes,
|
|
7
|
-
import { State } from '@exodus/stasis-core/state'
|
|
6
|
+
import { PluginState, assertCodeUtf8, assertPersistableAttributes, fileURL, ownOrResolvedState, unsupportedExtension } from './plugins.js'
|
|
8
7
|
// Pre-patch snapshot, not `import { readFile }`: under --fs=async that builtin is patched, and
|
|
9
8
|
// this plugin loads after, so a direct import would route esbuild's reads through the capture hook.
|
|
10
9
|
import { realReadFile } from '@exodus/stasis-core/state-util'
|
|
11
|
-
import { EMPTY_MODULE_PATH, classifyExtension,
|
|
10
|
+
import { EMPTY_MODULE_PATH, classifyExtension, isPlainObject, memoized } from '@exodus/stasis-core/util'
|
|
12
11
|
|
|
13
12
|
// The build options esbuild's resolver reads, replayed into the disabled-import probe.
|
|
14
13
|
const RESOLVE_OPTIONS = ['absWorkingDir', 'alias', 'conditions', 'external', 'mainFields', 'nodePaths',
|
|
15
14
|
'packages', 'platform', 'preserveSymlinks', 'resolveExtensions', 'tsconfig', 'tsconfigRaw']
|
|
16
15
|
|
|
16
|
+
// A stylesheet's imports, whose URL's query and fragment (`./icons.svg#check`) esbuild keeps as the result's suffix.
|
|
17
|
+
const CSS_RESOLVE_KINDS = new Set(['import-rule', 'composes-from', 'url-token'])
|
|
18
|
+
const urlSuffix = (specifier) => {
|
|
19
|
+
const at = specifier.search(/[?#]/u)
|
|
20
|
+
return at === -1 ? '' : specifier.slice(at)
|
|
21
|
+
}
|
|
22
|
+
|
|
17
23
|
// One import of `specifier` as `kind` would issue it, as the probe's stdin.
|
|
18
24
|
function probeSource(specifier, kind) {
|
|
19
25
|
const quoted = JSON.stringify(specifier)
|
|
@@ -28,81 +34,60 @@ function probeSource(specifier, kind) {
|
|
|
28
34
|
// with or without './'): equal loose keys are a SUPERSET of esbuild's matches -- only a probe decides.
|
|
29
35
|
function looseBrowserKey(path) {
|
|
30
36
|
const parts = path.replaceAll('\\', '/').split('/').filter((part) => part !== '' && part !== '.')
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
parts[parts.length - 1] = stem
|
|
35
|
-
break
|
|
36
|
-
}
|
|
37
|
-
parts.pop()
|
|
38
|
-
}
|
|
37
|
+
const stem = (part) => part.replace(/\..*$/su, '')
|
|
38
|
+
while (parts.length > 1 && stem(parts.at(-1)) === 'index') parts.pop()
|
|
39
|
+
if (parts.length > 0) parts[parts.length - 1] = stem(parts.at(-1))
|
|
39
40
|
return parts.join('/')
|
|
40
41
|
}
|
|
41
42
|
|
|
42
43
|
// The loose keys a directory's package.json `browser` map sends to `false` (esbuild's "disabled").
|
|
43
44
|
async function browserFalseKeys(dir) {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
}
|
|
50
|
-
const browser = pkg?.browser
|
|
51
|
-
if (browser === null || typeof browser !== 'object' || Array.isArray(browser)) return new Set()
|
|
52
|
-
return new Set(Object.keys(browser).filter((key) => browser[key] === false).map((key) => looseBrowserKey(key)))
|
|
45
|
+
const browser = await realReadFile(join(dir, 'package.json'), 'utf8')
|
|
46
|
+
.then((text) => JSON.parse(text)?.browser)
|
|
47
|
+
.catch(() => undefined)
|
|
48
|
+
if (!isPlainObject(browser)) return new Set()
|
|
49
|
+
return new Set(Object.keys(browser).filter((key) => browser[key] === false).map(looseBrowserKey))
|
|
53
50
|
}
|
|
54
51
|
|
|
55
52
|
export class StasisEsbuild {
|
|
56
|
-
|
|
57
|
-
#
|
|
58
|
-
#resources
|
|
53
|
+
name = 'stasis'
|
|
54
|
+
#stasis
|
|
59
55
|
#loaders
|
|
60
56
|
#transform
|
|
61
57
|
#resource
|
|
62
58
|
#platform
|
|
63
59
|
#emptyModule // URL of the empty module disabled imports point at, once capture recorded it
|
|
64
|
-
#browserScopes = new Map() // dir -> Promise<[{ dir, keys }]>: `false` keys of it and its ancestors
|
|
65
|
-
#probes = new Map() // [kind, resolveDir, specifier] -> Promise<disabled path | null>
|
|
66
|
-
#captureBuildCount = 0
|
|
67
60
|
|
|
68
61
|
// Only for load mode: `loaders` per-extension overrides (RN's '.js' -> 'jsx'), `transform(source, { path, loader })`
|
|
69
62
|
// a code rewrite (`stasis build --platform=hermes`), `resource(source, { path })` a module for a resource no loader
|
|
70
63
|
// names (`stasis build --metro`'s asset module), `platform` the one a --metro per-platform edge resolves for.
|
|
71
64
|
constructor(options = {}, { loaders, transform, resource, platform } = {}) {
|
|
72
|
-
|
|
73
|
-
this.#state = state
|
|
74
|
-
this.#resources = state?.config.resources ?? new Set()
|
|
65
|
+
this.#stasis = new PluginState('StasisEsbuild', 'esbuild', ownOrResolvedState('StasisEsbuild', options))
|
|
75
66
|
this.#loaders = loaders ?? new Map()
|
|
76
67
|
this.#transform = transform
|
|
77
68
|
this.#resource = resource
|
|
78
69
|
this.#platform = platform
|
|
79
70
|
}
|
|
80
71
|
|
|
81
|
-
// A configured override, else from the extension (.cjs/.mjs/.cts/.mts drop their module letter).
|
|
72
|
+
// A configured override, else from the extension (.cjs/.mjs/.cts/.mts drop their module letter, .css keeps it).
|
|
82
73
|
#loaderFor(path) {
|
|
83
74
|
const ext = extname(path)
|
|
84
|
-
return this.#loaders.get(ext) ?? ext.replace(
|
|
75
|
+
return this.#loaders.get(ext) ?? ext.slice(1).replace(/^[cm](?=[jt]s$)/u, '')
|
|
85
76
|
}
|
|
86
77
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
return upsert(this.#browserScopes, dir, () => {
|
|
95
|
-
const parent = dirname(dir)
|
|
96
|
-
return Promise.all([browserFalseKeys(dir), parent === dir ? [] : this.#browserFalseScopes(parent)])
|
|
97
|
-
.then(([keys, above]) => (keys.size > 0 ? [{ dir, keys }, ...above] : above))
|
|
98
|
-
})
|
|
99
|
-
}
|
|
78
|
+
// dir -> Promise<[{ dir, keys }]>: every directory from `dir` up whose `browser` map disables something, nearest
|
|
79
|
+
// first. A superset, as esbuild consults only the nearest map.
|
|
80
|
+
#browserFalseScopes = memoized((dir) => {
|
|
81
|
+
const parent = dirname(dir)
|
|
82
|
+
return Promise.all([browserFalseKeys(dir), parent === dir ? [] : this.#browserFalseScopes(parent)])
|
|
83
|
+
.then(([keys, above]) => (keys.size > 0 ? [{ dir, keys }, ...above] : above))
|
|
84
|
+
})
|
|
100
85
|
|
|
101
86
|
// Whether some `browser` map `false` entry could match this resolution: the resolved path (and, for a relative
|
|
102
87
|
// specifier, the path it names) under each map's dir, or a bare specifier as is or as './<importer dir>/<specifier>'
|
|
103
88
|
// (a Browserify quirk esbuild keeps).
|
|
104
89
|
async #mayBeDisabled(path, specifier, resolveDir) {
|
|
105
|
-
const isPackagePath = !isAbsolute(specifier) && !/^\.\.?(?:\/|$)/u.test(specifier)
|
|
90
|
+
const isPackagePath = !isAbsolute(specifier) && !/^\.\.?(?:\/|$)/u.test(specifier)
|
|
106
91
|
const paths = isPackagePath ? [path] : [path, resolvePath(resolveDir, specifier)]
|
|
107
92
|
const dirs = new Set([resolveDir, ...paths.map((p) => dirname(p))])
|
|
108
93
|
const scopes = (await Promise.all([...dirs].map((dir) => this.#browserFalseScopes(dir)))).flat()
|
|
@@ -115,25 +100,23 @@ export class StasisEsbuild {
|
|
|
115
100
|
|
|
116
101
|
// esbuild's own verdict: a one-import build with the build's resolve options and every load stubbed empty, whose
|
|
117
102
|
// metafile still names a disabled module `(disabled):<path>`. -> that path (absolute), or null
|
|
118
|
-
#probeDisabled(specifier, kind, resolveDir, { esbuild, initialOptions }) {
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
})
|
|
136
|
-
}
|
|
103
|
+
#probeDisabled = memoized(({ specifier, kind, resolveDir, build: { esbuild, initialOptions } }) => {
|
|
104
|
+
const options = Object.fromEntries(RESOLVE_OPTIONS.filter((k) => initialOptions[k] !== undefined).map((k) => [k, initialOptions[k]]))
|
|
105
|
+
const cwd = initialOptions.absWorkingDir ?? process.cwd()
|
|
106
|
+
return esbuild.build({
|
|
107
|
+
...options,
|
|
108
|
+
stdin: { ...probeSource(specifier, kind), resolveDir },
|
|
109
|
+
bundle: true,
|
|
110
|
+
write: false,
|
|
111
|
+
metafile: true,
|
|
112
|
+
logLevel: 'silent',
|
|
113
|
+
plugins: [{ name: 'stasis-probe', setup: (build) => build.onLoad({ filter: /$/ }, () => ({ contents: '', loader: 'empty' })) }],
|
|
114
|
+
}).then(({ metafile }) => {
|
|
115
|
+
const found = metafile.inputs['<stdin>']?.imports.find((i) => i.original === specifier)?.path
|
|
116
|
+
if (!found?.startsWith('(disabled):')) return null
|
|
117
|
+
return resolvePath(cwd, found.slice('(disabled):'.length))
|
|
118
|
+
}, () => null)
|
|
119
|
+
}, ({ specifier, kind, resolveDir }) => JSON.stringify([kind, resolveDir, specifier]))
|
|
137
120
|
|
|
138
121
|
// A `browser` field `false` makes esbuild resolve an import to an empty "disabled" module, but its resolve API
|
|
139
122
|
// drops that flag: a bare name comes back namespace-less, a file as its plain path, which a probe confirms where a
|
|
@@ -144,51 +127,55 @@ export class StasisEsbuild {
|
|
|
144
127
|
if (res.namespace !== 'file' || (build.initialOptions.platform ?? 'browser') !== 'browser') return false
|
|
145
128
|
if (!(await this.#mayBeDisabled(res.path, specifier, resolveDir))) return false
|
|
146
129
|
// A sibling plugin may have resolved the import to something else entirely.
|
|
147
|
-
return (await this.#probeDisabled(specifier, kind, resolveDir, build)) === res.path
|
|
130
|
+
return (await this.#probeDisabled({ specifier, kind, resolveDir, build })) === res.path
|
|
148
131
|
}
|
|
149
132
|
|
|
150
133
|
setup = ({ onResolve, onLoad, onStart, onEnd, resolve, initialOptions, esbuild }) => {
|
|
151
|
-
|
|
152
|
-
const
|
|
134
|
+
const stasis = this.#stasis
|
|
135
|
+
const { state } = stasis
|
|
136
|
+
if (!state) return
|
|
137
|
+
const { loadBundle } = state.config
|
|
138
|
+
const emptyModuleURL = fileURL(resolvePath(state.root, EMPTY_MODULE_PATH))
|
|
153
139
|
|
|
154
140
|
// Rebuilds re-fire onStart against the same registrations.
|
|
155
|
-
if (!
|
|
141
|
+
if (!loadBundle) {
|
|
156
142
|
onStart(() => {
|
|
157
|
-
|
|
158
|
-
return
|
|
143
|
+
const text = stasis.startBuild()
|
|
144
|
+
return text && { errors: [{ text }] }
|
|
159
145
|
})
|
|
160
146
|
}
|
|
161
147
|
|
|
162
|
-
//
|
|
163
|
-
if (
|
|
148
|
+
// A failed build mustn't overwrite the user's good file.
|
|
149
|
+
if (stasis.ownsWrite) {
|
|
164
150
|
onEnd((result) => {
|
|
165
|
-
if (result.errors.length === 0)
|
|
151
|
+
if (result.errors.length === 0) state.write()
|
|
166
152
|
})
|
|
167
153
|
}
|
|
168
154
|
|
|
169
155
|
// Load mode resolves through the bundle's import map: the file may not be on disk. namespace 'file' with the
|
|
170
156
|
// original path (esbuild doesn't stat a plugin's) keeps the output (banners, asset names, maps) a capture's.
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
157
|
+
if (loadBundle) {
|
|
158
|
+
onResolve({ filter: /$/ }, ({ path: specifier, importer, kind: resolveKind, with: attrs }) => {
|
|
159
|
+
const isEntry = resolveKind === 'entry-point'
|
|
160
|
+
let url
|
|
161
|
+
if (isEntry) {
|
|
162
|
+
// Anchored to cwd, as the run loader does, so the file needn't be on disk.
|
|
163
|
+
url = specifier.startsWith('file:') ? specifier : fileURL(resolvePath(process.cwd(), specifier))
|
|
164
|
+
if (state.config.full) state.assertEntry(url)
|
|
165
|
+
} else {
|
|
166
|
+
// Looked up even for a built-in's name: a browser build records `fs` where a `browser` field disables it or
|
|
167
|
+
// a package by that name serves it. KNOWN GAP: a Node-loader-captured bundle keys an attributed edge under
|
|
168
|
+
// specific conditions, which this `*` lookup won't match.
|
|
169
|
+
url = stasis.attestedImport(importer, specifier, { importAttributes: attrs, platform: this.#platform })?.url
|
|
170
|
+
if (url === undefined) return undefined
|
|
171
|
+
}
|
|
172
|
+
const format = state.getFormat(url)
|
|
173
|
+
const kind = url === emptyModuleURL ? 'empty' : Bundle.isResourceFormat(format) ? 'resource' : 'code'
|
|
174
|
+
// A stylesheet URL's query and fragment, which the emitted URL carries, as esbuild's own resolution keeps them.
|
|
175
|
+
const suffix = CSS_RESOLVE_KINDS.has(resolveKind) ? urlSuffix(specifier) : ''
|
|
176
|
+
return { path: fileURLToPath(url), namespace: 'file', ...(suffix && { suffix }), pluginData: { isEntry, kind } }
|
|
177
|
+
})
|
|
178
|
+
}
|
|
192
179
|
|
|
193
180
|
onResolve({ filter: /$/, namespace: 'file' }, async ({ path: specifier, with: attrs, ...args }) => {
|
|
194
181
|
const isEntry = !args.importer
|
|
@@ -198,24 +185,23 @@ export class StasisEsbuild {
|
|
|
198
185
|
if (res.errors.length > 0) return undefined
|
|
199
186
|
// Declined, esbuild re-resolves a disabled import into its own empty module, the attested one bundle=load serves.
|
|
200
187
|
if (!isEntry && await this.#isDisabled(res, specifier, args, { esbuild, initialOptions })) {
|
|
201
|
-
if (!
|
|
202
|
-
this.#emptyModule ??=
|
|
203
|
-
|
|
188
|
+
if (!loadBundle) {
|
|
189
|
+
this.#emptyModule ??= state.addEmptyModule({ reason: 'esbuild' })
|
|
190
|
+
state.addImport(fileURL(args.importer), specifier, this.#emptyModule, { importAttributes: attrs })
|
|
204
191
|
}
|
|
205
192
|
return undefined
|
|
206
193
|
}
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
`
|
|
194
|
+
// But a stylesheet URL's own query and fragment, esbuild's suffix of it, which load mode reads off the specifier.
|
|
195
|
+
assert.ok(res.suffix === '' || (CSS_RESOLVE_KINDS.has(args.kind) && res.suffix === urlSuffix(specifier)),
|
|
196
|
+
`StasisEsbuild: a sibling plugin set res.suffix='${res.suffix}' on '${specifier}', which stasis can't persist`)
|
|
210
197
|
|
|
211
198
|
let kind = 'skip'
|
|
212
199
|
if (res.namespace === 'file' && !res.external) {
|
|
213
|
-
kind = classifyExtension(res.path,
|
|
200
|
+
kind = classifyExtension(res.path, state.config.resources)
|
|
214
201
|
if (kind === 'unknown') return { errors: [{ text: unsupportedExtension('StasisEsbuild', `'${res.path}'`) }] }
|
|
215
202
|
// Resources too: load mode resolves every specifier through this map, so one with no edge would fall through
|
|
216
203
|
// to esbuild's disk resolver, unattested.
|
|
217
|
-
|
|
218
|
-
if (!isEntry) this.#state.addImport(pathToFileURL(args.importer).toString(), specifier, url, { importAttributes: attrs })
|
|
204
|
+
if (!isEntry) stasis.addImport(args.importer, specifier, res.path, attrs)
|
|
219
205
|
}
|
|
220
206
|
return { ...res, pluginData: { ...res.pluginData, isEntry, kind } }
|
|
221
207
|
})
|
|
@@ -226,31 +212,26 @@ export class StasisEsbuild {
|
|
|
226
212
|
assertPersistableAttributes(attrs)
|
|
227
213
|
|
|
228
214
|
// getFile verifies the hash and throws on a file the bundle doesn't carry: no disk fallback.
|
|
229
|
-
if (
|
|
230
|
-
const { source } =
|
|
215
|
+
if (loadBundle) {
|
|
216
|
+
const { source } = state.getFile(fileURL(path))
|
|
231
217
|
// esbuild's own loader for disabled modules, which a CSS @import, `composes` or url() accepts too.
|
|
232
218
|
if (kind === 'empty') return { contents: source, loader: 'empty' }
|
|
233
219
|
if (kind === 'resource') {
|
|
234
220
|
const override = this.#loaders.get(extname(path))
|
|
235
221
|
if (override) return { contents: source, loader: override }
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
// The build's own loader for it, so a resource none loads fails as at capture, not parsed as js.
|
|
239
|
-
return { contents: source, loader: 'default' }
|
|
222
|
+
// Else the build's own loader for it, so a resource none loads fails as at capture, not parsed as js.
|
|
223
|
+
return (await this.#resource?.(source, { path })) || { contents: source, loader: 'default' }
|
|
240
224
|
}
|
|
241
225
|
const loader = this.#loaderFor(path)
|
|
242
226
|
return (await this.#transform?.(source, { path, loader })) ?? { contents: source, loader }
|
|
243
227
|
}
|
|
244
228
|
|
|
245
229
|
const source = await realReadFile(path)
|
|
246
|
-
|
|
247
|
-
if (
|
|
248
|
-
if (
|
|
249
|
-
this.#seen.add(path)
|
|
250
|
-
this.#state.addFile(pathToFileURL(path).toString(), { source, isEntry: pluginData?.isEntry, resource, reason: 'esbuild' })
|
|
251
|
-
}
|
|
230
|
+
// A file loads once per set of import attributes: each read is checked, the first recorded.
|
|
231
|
+
if (stasis.claim(path)) stasis.addFile(path, source, kind, pluginData.isEntry)
|
|
232
|
+
else if (kind === 'code') assertCodeUtf8('StasisEsbuild', path, source)
|
|
252
233
|
// A resource is emitted by esbuild, through the build's own `loader` config.
|
|
253
|
-
return resource ? undefined : { contents: source, loader: this.#loaderFor(path) }
|
|
234
|
+
return kind === 'resource' ? undefined : { contents: source, loader: this.#loaderFor(path) }
|
|
254
235
|
})
|
|
255
236
|
}
|
|
256
237
|
}
|
|
@@ -2,6 +2,8 @@ import assert from 'node:assert/strict'
|
|
|
2
2
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
3
3
|
import { createRequire } from 'node:module'
|
|
4
4
|
|
|
5
|
+
import { upsert } from '@exodus/stasis-core/util'
|
|
6
|
+
|
|
5
7
|
// Stands in for the project's Babel transformer under ./metro-transformer.js, to keep each import as WRITTEN: Metro
|
|
6
8
|
// names a dependency by the specifier Babel leaves, so a rewrite (babel-plugin-module-resolver's) would leave it only
|
|
7
9
|
// that. An added plugin records each specifier in its `pre` (Babel runs every `pre` before any visitor) and reads it
|
|
@@ -118,8 +120,7 @@ export function transform(args) {
|
|
|
118
120
|
context.consumed.add(specifier)
|
|
119
121
|
continue
|
|
120
122
|
}
|
|
121
|
-
|
|
122
|
-
context.asWritten.get(specifier).add(written)
|
|
123
|
+
upsert(context.asWritten, specifier, () => new Set()).add(written)
|
|
123
124
|
}
|
|
124
125
|
return result
|
|
125
126
|
}
|
package/src/metro-native.js
CHANGED
|
@@ -3,7 +3,7 @@ import { basename, dirname, join, posix, relative, sep } from 'node:path'
|
|
|
3
3
|
|
|
4
4
|
import { readJson } from '@exodus/stasis-core/bundle-util'
|
|
5
5
|
import { diskHost } from '@exodus/stasis-core/host'
|
|
6
|
-
import { CODE_EXTENSIONS, classifyFormat, isAutoExcludedDir, isBinaryPlist, isDotEnvFile, isExcludedNativeFile, isNativeArtifact, nameFormat, pathExt, toPosix, upsert } from '@exodus/stasis-core/util'
|
|
6
|
+
import { CODE_EXTENSIONS, classifyFormat, isAutoExcludedDir, isBinaryPlist, isDotEnvFile, isExcludedNativeFile, isNativeArtifact, metroFormat, nameFormat, pathExt, toPosix, upsert } from '@exodus/stasis-core/util'
|
|
7
7
|
|
|
8
8
|
// The native build inputs of a React Native app's packages, shared by the Metro plugin's capture and `stasis bundle
|
|
9
9
|
// --metro` so the two carry the same files. `fs` is a host: readdir(dir) -> Dirent[] (throws where `dir` isn't one),
|
|
@@ -37,42 +37,37 @@ export function isExcludedNativeDir(name, { win32 = process.platform === 'win32'
|
|
|
37
37
|
const NATIVE_BUILD_OUTPUT_DIRS = new Set(['node_modules', 'build', '.gradle', '.cxx', 'Pods', 'DerivedData'])
|
|
38
38
|
const isSkippedNativeWalkDir = (name) => NATIVE_BUILD_OUTPUT_DIRS.has(name) || isAutoExcludedDir(name) || isNativeArtifact(name)
|
|
39
39
|
|
|
40
|
-
// A compiled tool (Hermes' `hermesc`), never source.
|
|
41
|
-
const isExtensionlessBinary = (name, content) => pathExt(name) === '' && Buffer.isBuffer(content) && !isUtf8(content)
|
|
42
|
-
|
|
43
40
|
// A native capture's view of a file by name: { action: 'code', format } for a native build input, 'skip' for noise
|
|
44
41
|
// or a JS-family file by extension (Metro owns those), else 'resource'.
|
|
45
42
|
export function classifyNativeCapture(name, { win32 = process.platform === 'win32', content } = {}) {
|
|
46
43
|
// `.env` files carry secrets: an automated capture must never sweep them in.
|
|
47
44
|
if (isExcludedNativeFile(name, { win32 }) || isDotEnvFile(name)) return { action: 'skip' }
|
|
48
45
|
// Name-matched code is a native build input even where its tag is a Node format the JS graph would own.
|
|
49
|
-
|
|
50
|
-
if (byName !== undefined) return { action: 'code', format: byName }
|
|
51
|
-
if (CODE_EXTENSIONS.has(pathExt(name))) return { action: 'skip' }
|
|
46
|
+
if (nameFormat(name) === undefined && CODE_EXTENSIONS.has(pathExt(name))) return { action: 'skip' }
|
|
52
47
|
const format = classifyFormat(name, { content })
|
|
53
48
|
return format === undefined ? { action: 'resource' } : { action: 'code', format }
|
|
54
49
|
}
|
|
55
50
|
|
|
56
51
|
// classifyNativeCapture refined by the bytes, which only ever demote; a 'resource' gets its format from its bytes.
|
|
57
52
|
export function refineNativeCapture(classified, name, content, resources = new Set()) {
|
|
58
|
-
|
|
53
|
+
// A compiled tool (Hermes' `hermesc`), never source.
|
|
54
|
+
if (pathExt(name) === '' && Buffer.isBuffer(content) && !isUtf8(content)) return { action: 'skip' }
|
|
59
55
|
if (isBinaryPlist(name, content)) return { action: resources.has('plist') ? 'resource' : 'skip' }
|
|
60
56
|
return classified
|
|
61
57
|
}
|
|
62
58
|
|
|
63
|
-
// A file name as Metro's AssetPaths reads it (parsePlatformFilePath, then parseBaseName)
|
|
64
|
-
// less any scale (`a@2x.png` is `a.png`'s),
|
|
65
|
-
//
|
|
59
|
+
// A file name as Metro's AssetPaths reads it (parsePlatformFilePath, then parseBaseName) for `platform` (a name or
|
|
60
|
+
// null): its asset, `${name}.${type}` less any scale (`a@2x.png` is `a.png`'s), and its platform where it names
|
|
61
|
+
// `platform` (`a.ios.png`; `a.android.png` is an asset of its own). -> null for a name with no type
|
|
66
62
|
const METRO_PLATFORM_FILE = /^(.+?)(?:\.([^.]+))?\.([^.]+)$/u
|
|
67
|
-
const METRO_ASSET_SCALE = /^(.+?)(?:@
|
|
68
|
-
|
|
63
|
+
const METRO_ASSET_SCALE = /^(.+?)(?:@[\d.]+x)?$/u
|
|
64
|
+
function parseMetroAssetName(name, platform) {
|
|
69
65
|
const match = METRO_PLATFORM_FILE.exec(name)
|
|
70
66
|
if (match === null) return null
|
|
71
67
|
const [, base, suffix, type] = match
|
|
72
|
-
const ofPlatform = suffix
|
|
73
|
-
const [, root
|
|
74
|
-
|
|
75
|
-
return { asset: `${root}.${type}`, name: root, type, resolution: Number.isNaN(resolution) ? 1 : resolution, platform: ofPlatform ? platform : null }
|
|
68
|
+
const ofPlatform = suffix === platform
|
|
69
|
+
const [, root] = METRO_ASSET_SCALE.exec(suffix === undefined || ofPlatform ? base : `${base}.${suffix}`)
|
|
70
|
+
return { asset: `${root}.${type}`, platform: ofPlatform ? platform : null }
|
|
76
71
|
}
|
|
77
72
|
|
|
78
73
|
// A file's stat for metroAssetFiles, where a listing names one the disk lacks.
|
|
@@ -100,7 +95,7 @@ export function metroAssetFiles(path, platform = null, host = diskHost) {
|
|
|
100
95
|
if (parsed?.asset !== own.asset || host.stat(join(dir, name))?.isFile() !== true) continue
|
|
101
96
|
upsert(byPlatform, parsed.platform, () => []).push(join(dir, name))
|
|
102
97
|
}
|
|
103
|
-
return
|
|
98
|
+
return byPlatform.get(platform) ?? byPlatform.get(null) ?? []
|
|
104
99
|
}
|
|
105
100
|
|
|
106
101
|
// Whether the package at `root` ships native code: an ios/ or android/ dir, or a podspec under it.
|
|
@@ -119,7 +114,7 @@ const isCodegenSpec = (name) => /^(?:Native.+|.+NativeComponent)/u.test(name) &&
|
|
|
119
114
|
|
|
120
115
|
// Each native build input of the package at `root`, walked whole (a podspec may compile `cpp/` beside `ios/`) but
|
|
121
116
|
// build output, prebuilt binaries, an off-platform top-level dir, symlinks and what the shared classifier skips; and
|
|
122
|
-
// its codegen specs, as code
|
|
117
|
+
// its codegen specs, as code Metro's format names. -> yields { file, source, action: 'code' | 'resource', format }
|
|
123
118
|
export function* nativeInputs(root, fs, { resources = new Set(), skip = () => false } = {}) {
|
|
124
119
|
yield* walk(root, true)
|
|
125
120
|
for (const dir of codegenSources(root, fs)) yield* sources(dir)
|
|
@@ -129,7 +124,7 @@ export function* nativeInputs(root, fs, { resources = new Set(), skip = () => fa
|
|
|
129
124
|
if (ent.isSymbolicLink() || ent.name.startsWith('.') || ent.name === 'node_modules' || ent.name.startsWith('__tests')) continue
|
|
130
125
|
const file = join(dir, ent.name)
|
|
131
126
|
if (ent.isDirectory()) yield* sources(file)
|
|
132
|
-
else if (ent.isFile() && isCodegenSpec(ent.name) && !skip(file)) yield { file, source: fs.readFile(file), action: 'code', format:
|
|
127
|
+
else if (ent.isFile() && isCodegenSpec(ent.name) && !skip(file)) yield { file, source: fs.readFile(file), action: 'code', format: metroFormat(file) }
|
|
133
128
|
}
|
|
134
129
|
}
|
|
135
130
|
function* walk(dir, atRoot) {
|
|
@@ -179,7 +174,7 @@ const PACKAGE_NAME = /^(?:@[^/\\@.][^/\\]*\/)?[^/\\@.][^/\\]*$/u
|
|
|
179
174
|
export function linkedPackages(projectDir, fs) {
|
|
180
175
|
const manifest = readJson(join(projectDir, 'package.json'), fs)
|
|
181
176
|
const listed = (field) => (manifest?.[field] && typeof manifest[field] === 'object' ? Object.keys(manifest[field]) : [])
|
|
182
|
-
const names = new Set([
|
|
177
|
+
const names = new Set(['dependencies', 'peerDependencies', 'devDependencies'].flatMap(listed))
|
|
183
178
|
const dirs = []
|
|
184
179
|
for (const name of names) {
|
|
185
180
|
if (!PACKAGE_NAME.test(name)) continue
|
package/src/metro-transformer.js
CHANGED
|
@@ -5,6 +5,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
|
5
5
|
|
|
6
6
|
import { State } from '@exodus/stasis-core/state'
|
|
7
7
|
import { servedByBundle } from '@exodus/stasis-core/state-util'
|
|
8
|
+
import { upsert } from '@exodus/stasis-core/util'
|
|
8
9
|
import { transformContext } from './metro-babel-transformer.js'
|
|
9
10
|
|
|
10
11
|
// The worker half of StasisMetro, wired by withStasis() as `transformerPath` around the project's transformer. It
|
|
@@ -20,14 +21,12 @@ const require = createRequire(import.meta.url)
|
|
|
20
21
|
const bases = new Map()
|
|
21
22
|
function baseOf(config, projectRoot = process.cwd()) {
|
|
22
23
|
const path = config?.stasisBaseTransformerPath ?? (process.env.EXODUS_STASIS_METRO_BASE_TRANSFORMER || 'metro-transform-worker')
|
|
23
|
-
|
|
24
|
-
if (!bases.has(key)) {
|
|
24
|
+
return upsert(bases, `${projectRoot}\0${path}`, () => {
|
|
25
25
|
const resolve = (name) => require.resolve(name, { paths: [projectRoot, dirname(fileURLToPath(import.meta.url))] })
|
|
26
26
|
let file = resolve(path)
|
|
27
27
|
if (require(file).transform === transform) file = resolve('metro-transform-worker')
|
|
28
|
-
|
|
29
|
-
}
|
|
30
|
-
return bases.get(key)
|
|
28
|
+
return { file, transformer: require(file) }
|
|
29
|
+
})
|
|
31
30
|
}
|
|
32
31
|
|
|
33
32
|
const baseConfig = ({ stasisBaseTransformerPath: _, ...config } = {}) => config
|