babel-plugin-react-native-direct-imports 1.2.0 → 1.2.1-rc.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.
@@ -0,0 +1,455 @@
1
+ /**
2
+ * Resolves named/default exports of an arbitrary package to the module that
3
+ * actually defines them. Used at runtime for packages without a shipped map,
4
+ * and by `scripts/generate-maps.js` to generate the maps of the ones that
5
+ * have one, by statically following the ES re-exports of the
6
+ * installed package's entry file ("barrel"):
7
+ *
8
+ * // react-native-svg/src/index.ts
9
+ * export * from './ReactNativeSVG';
10
+ * export { default } from './ReactNativeSVG';
11
+ * // ...
12
+ * // react-native-svg/src/elements.ts
13
+ * import Defs from './elements/Defs';
14
+ * export { Defs };
15
+ *
16
+ * resolveImport('react-native-svg', dir, 'Defs')
17
+ * // -> ['react-native-svg/src/elements/Defs', 'default']
18
+ *
19
+ * The entry file is picked like Metro does: `exports["."]` when the package has
20
+ * an `exports` field, otherwise `react-native`, then `module`, then `main` of
21
+ * its `package.json`. Names are resolved lazily, one at a time, so only the
22
+ * files on the path to a name are parsed.
23
+ *
24
+ * With an `exports` field, the emitted path is the public specifier the file
25
+ * is exposed as, not its location (`"./elements/*": "./src/elements/*.ts"`
26
+ * turns `src/elements/Defs.ts` into `pkg/elements/Defs`). A file that no
27
+ * `exports` entry exposes can't be imported from outside, so the import is
28
+ * kept as it is.
29
+ *
30
+ * Supported: `export { a } from`, `export { default as a } from`,
31
+ * `export * from`, `export * as ns from`, `import x from; export { x }`,
32
+ * `export default <imported binding>` and local declarations. Types
33
+ * (`export type`, interfaces, ...) are ignored. A name that can't be traced to
34
+ * a file inside the package (bare specifiers, CommonJS, ...) resolves to
35
+ * `null`, so the original import is kept.
36
+ */
37
+
38
+ const fs = require('fs');
39
+ const nodePath = require('path');
40
+
41
+ const EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.mjs'];
42
+ const ENTRY_FIELDS = ['react-native', 'module', 'main'];
43
+
44
+ const isFile = (path) => {
45
+ try {
46
+ return fs.statSync(path).isFile();
47
+ } catch {
48
+ return false;
49
+ }
50
+ };
51
+
52
+ // `./elements` may be `elements.ts` or `elements/index.ts` (files win, like
53
+ // in Node and Metro).
54
+ const resolveFile = (base) => {
55
+ if (isFile(base)) return base;
56
+ for (const ext of EXTENSIONS) {
57
+ if (isFile(base + ext)) return base + ext;
58
+ }
59
+ for (const ext of EXTENSIONS) {
60
+ const index = nodePath.join(base, `index${ext}`);
61
+ if (isFile(index)) return index;
62
+ }
63
+ return null;
64
+ };
65
+
66
+ // Walks up from `fromDir` like Node's `node_modules` lookup, without going
67
+ // through `require.resolve` so packages with an `exports` field still work.
68
+ const findPackageRoot = (name, fromDir) => {
69
+ for (let dir = fromDir; ; dir = nodePath.dirname(dir)) {
70
+ const root = nodePath.join(dir, 'node_modules', name);
71
+ if (isFile(nodePath.join(root, 'package.json'))) return root;
72
+ if (nodePath.dirname(dir) === dir) return null;
73
+ }
74
+ };
75
+
76
+ // Conditions a bundler like Metro matches in `exports`, in the order the
77
+ // package lists them.
78
+ const CONDITIONS = new Set(['react-native', 'import', 'module', 'default']);
79
+
80
+ // A target is a path, a list of fallbacks or an object of conditions.
81
+ const pickTarget = (target) => {
82
+ if (typeof target === 'string') return target;
83
+ if (Array.isArray(target)) {
84
+ for (const item of target) {
85
+ const picked = pickTarget(item);
86
+ if (picked !== null) return picked;
87
+ }
88
+ return null;
89
+ }
90
+ if (target && typeof target === 'object') {
91
+ for (const [condition, value] of Object.entries(target)) {
92
+ if (!CONDITIONS.has(condition)) continue;
93
+ const picked = pickTarget(value);
94
+ if (picked !== null) return picked;
95
+ }
96
+ }
97
+ return null;
98
+ };
99
+
100
+ // `exports` is a map of subpaths ("." or "./x"), or a bare target meaning ".".
101
+ const normalizeExports = (exportsField) => {
102
+ if (exportsField === undefined || exportsField === null) return null;
103
+ const isMap =
104
+ typeof exportsField === 'object' &&
105
+ !Array.isArray(exportsField) &&
106
+ Object.keys(exportsField).some((key) => key.startsWith('.'));
107
+ return isMap ? exportsField : { '.': exportsField };
108
+ };
109
+
110
+ const splitPattern = (pattern) => {
111
+ const star = pattern.indexOf('*');
112
+ return star === -1
113
+ ? null
114
+ : { prefix: pattern.slice(0, star), suffix: pattern.slice(star + 1) };
115
+ };
116
+
117
+ const matchPattern = (pattern, value) => {
118
+ const parts = splitPattern(pattern);
119
+ return parts &&
120
+ value.length >= pattern.length &&
121
+ value.startsWith(parts.prefix) &&
122
+ value.endsWith(parts.suffix)
123
+ ? value.slice(parts.prefix.length, value.length - parts.suffix.length)
124
+ : null;
125
+ };
126
+
127
+ // Node's resolution of a subpath ("./elements/Defs") through `exports`:
128
+ // the file it points to ("./src/elements/Defs.ts"), or `null`.
129
+ const resolveExport = (exportsMap, subpath) => {
130
+ if (Object.hasOwn(exportsMap, subpath) && !subpath.includes('*')) {
131
+ return pickTarget(exportsMap[subpath]);
132
+ }
133
+
134
+ let best = null;
135
+ for (const key of Object.keys(exportsMap)) {
136
+ const captured = matchPattern(key, subpath);
137
+ if (captured === null) continue;
138
+ // The longest prefix wins.
139
+ if (!best || splitPattern(key).prefix.length > best.prefixLength) {
140
+ best = { key, captured, prefixLength: splitPattern(key).prefix.length };
141
+ }
142
+ }
143
+ const target = best && pickTarget(exportsMap[best.key]);
144
+ return target === null || target === undefined
145
+ ? null
146
+ : target.split('*').join(best.captured);
147
+ };
148
+
149
+ // The public subpath ("./elements/Defs") a file ("./src/elements/Defs.ts") is
150
+ // exposed as, or `null` when nothing exposes it. Candidates come from the
151
+ // entries pointing at the file; the winner has to resolve back to it.
152
+ const findExportedSubpath = (exportsMap, file) => {
153
+ for (const [key, value] of Object.entries(exportsMap)) {
154
+ if (key === '.' || !key.startsWith('./')) continue;
155
+ const target = pickTarget(value);
156
+ if (target === null) continue;
157
+
158
+ let subpath = null;
159
+ if (!target.includes('*')) {
160
+ if (target === file && !key.includes('*')) subpath = key;
161
+ } else {
162
+ const captured = matchPattern(target, file);
163
+ if (captured !== null && key.includes('*')) {
164
+ subpath = key.split('*').join(captured);
165
+ }
166
+ }
167
+
168
+ if (subpath !== null && resolveExport(exportsMap, subpath) === file) {
169
+ return subpath;
170
+ }
171
+ }
172
+ return null;
173
+ };
174
+
175
+ const parserPlugins = (file) => {
176
+ if (file.endsWith('.ts')) return ['typescript'];
177
+ if (file.endsWith('.tsx')) return ['typescript', 'jsx'];
178
+ return ['jsx', 'flow'];
179
+ };
180
+
181
+ const isTypeOnly = (node) =>
182
+ node.importKind === 'type' ||
183
+ node.importKind === 'typeof' ||
184
+ node.exportKind === 'type';
185
+
186
+ // `options` (used by the map generator, not at runtime):
187
+ // entry - entry file relative to the package root, instead of the
188
+ // one `package.json` points at
189
+ // ignoreExports - ignore the `exports` field: paths are file locations, for
190
+ // packages whose deep paths are meant to be imported anyway
191
+ const createPackageResolver = ({ types: t, parseSync }, options = {}) => {
192
+ const nameOf = (node) => (t.isIdentifier(node) ? node.name : node.value);
193
+
194
+ const analyses = new Map();
195
+
196
+ // { locals: Set<name>, reexports: Map<name, {source, imported}>, stars: [source] }
197
+ // `imported` is an export name of `source`, `'default'` or `'*'`.
198
+ const analyze = (file) => {
199
+ const cached = analyses.get(file);
200
+ if (cached) return cached;
201
+
202
+ const ast = parseSync(fs.readFileSync(file, 'utf8'), {
203
+ filename: file,
204
+ babelrc: false,
205
+ configFile: false,
206
+ sourceType: 'module',
207
+ parserOpts: { plugins: parserPlugins(file) },
208
+ });
209
+ const { body } = ast.program;
210
+
211
+ const info = { locals: new Set(), reexports: new Map(), stars: [] };
212
+ const imports = new Map();
213
+ const typeNames = new Set();
214
+
215
+ for (const node of body) {
216
+ if (!t.isImportDeclaration(node)) continue;
217
+ for (const spec of node.specifiers) {
218
+ if (isTypeOnly(node) || isTypeOnly(spec)) {
219
+ typeNames.add(spec.local.name);
220
+ continue;
221
+ }
222
+ imports.set(spec.local.name, {
223
+ source: node.source.value,
224
+ imported: t.isImportDefaultSpecifier(spec)
225
+ ? 'default'
226
+ : t.isImportNamespaceSpecifier(spec)
227
+ ? '*'
228
+ : nameOf(spec.imported),
229
+ });
230
+ }
231
+ }
232
+
233
+ // `export { X }` / `export default X`: X is either an import (a re-export)
234
+ // or something declared in this file.
235
+ const exportBinding = (exported, local) => {
236
+ if (typeNames.has(local)) return;
237
+ const imported = imports.get(local);
238
+ if (imported) info.reexports.set(exported, imported);
239
+ else info.locals.add(exported);
240
+ };
241
+
242
+ for (const node of body) {
243
+ if (t.isExportAllDeclaration(node)) {
244
+ if (!isTypeOnly(node)) info.stars.push(node.source.value);
245
+ } else if (t.isExportDefaultDeclaration(node)) {
246
+ const { declaration } = node;
247
+ if (t.isIdentifier(declaration)) {
248
+ exportBinding('default', declaration.name);
249
+ } else if (
250
+ !t.isTSInterfaceDeclaration(declaration) &&
251
+ !t.isTSDeclareFunction(declaration)
252
+ ) {
253
+ info.locals.add('default');
254
+ }
255
+ } else if (t.isExportNamedDeclaration(node)) {
256
+ if (isTypeOnly(node)) continue;
257
+
258
+ if (node.source) {
259
+ for (const spec of node.specifiers) {
260
+ if (isTypeOnly(spec)) continue;
261
+ info.reexports.set(nameOf(spec.exported), {
262
+ source: node.source.value,
263
+ imported: t.isExportNamespaceSpecifier(spec)
264
+ ? '*'
265
+ : t.isExportDefaultSpecifier(spec)
266
+ ? 'default'
267
+ : nameOf(spec.local),
268
+ });
269
+ }
270
+ continue;
271
+ }
272
+
273
+ const { declaration } = node;
274
+ if (declaration) {
275
+ if (declaration.declare) continue;
276
+ if (t.isVariableDeclaration(declaration)) {
277
+ for (const name of Object.keys(t.getBindingIdentifiers(declaration))) {
278
+ info.locals.add(name);
279
+ }
280
+ } else if (
281
+ t.isFunctionDeclaration(declaration) ||
282
+ t.isClassDeclaration(declaration) ||
283
+ (t.isTSEnumDeclaration(declaration) && !declaration.const)
284
+ ) {
285
+ info.locals.add(declaration.id.name);
286
+ }
287
+ continue;
288
+ }
289
+
290
+ for (const spec of node.specifiers) {
291
+ if (!isTypeOnly(spec)) {
292
+ exportBinding(nameOf(spec.exported), spec.local.name);
293
+ }
294
+ }
295
+ }
296
+ }
297
+
298
+ analyses.set(file, info);
299
+ return info;
300
+ };
301
+
302
+ const resolveSource = (fromFile, source) =>
303
+ source.startsWith('.')
304
+ ? resolveFile(nodePath.resolve(nodePath.dirname(fromFile), source))
305
+ : null;
306
+
307
+ // Finds the file that defines `name` as seen from `file`:
308
+ // `{ file, name }`, or `null` if it can't be traced.
309
+ const lookup = (file, name, seen = new Set()) => {
310
+ const key = `${file}\0${name}`;
311
+ if (seen.has(key)) return null;
312
+ seen.add(key);
313
+
314
+ const info = analyze(file);
315
+ if (info.locals.has(name)) return { file, name };
316
+
317
+ const reexport = info.reexports.get(name);
318
+ if (reexport) {
319
+ const target = resolveSource(file, reexport.source);
320
+ if (!target) return null;
321
+ if (reexport.imported === '*') return { file: target, name: '*' };
322
+ // Not traceable any further (e.g. a CommonJS file): the barrel itself
323
+ // says the name comes from `target`.
324
+ return (
325
+ lookup(target, reexport.imported, seen) ?? {
326
+ file: target,
327
+ name: reexport.imported,
328
+ }
329
+ );
330
+ }
331
+
332
+ // `export *` never re-exports `default`.
333
+ if (name !== 'default') {
334
+ for (const source of info.stars) {
335
+ const target = resolveSource(file, source);
336
+ const found = target && lookup(target, name, seen);
337
+ if (found) return found;
338
+ }
339
+ }
340
+
341
+ return null;
342
+ };
343
+
344
+ const packages = new Map();
345
+
346
+ const loadPackage = (name, fromDir) => {
347
+ const cacheKey = `${name}\0${fromDir}`;
348
+ const cached = packages.get(cacheKey);
349
+ if (cached) return cached;
350
+
351
+ const root = findPackageRoot(name, fromDir);
352
+ if (!root) {
353
+ throw new Error(
354
+ `[react-native-direct-imports] Can't find the package "${name}" listed in \`packages\`, looked in node_modules from ${fromDir}`,
355
+ );
356
+ }
357
+
358
+ const manifest = JSON.parse(
359
+ fs.readFileSync(nodePath.join(root, 'package.json'), 'utf8'),
360
+ );
361
+ const exportsMap = options.ignoreExports
362
+ ? null
363
+ : normalizeExports(manifest.exports);
364
+ const field =
365
+ options.entry ??
366
+ (exportsMap && pickTarget(exportsMap['.'])) ??
367
+ ENTRY_FIELDS.map((key) => manifest[key]).find(
368
+ (value) => typeof value === 'string',
369
+ );
370
+ const entry = resolveFile(nodePath.join(root, field ?? 'index'));
371
+ if (!entry) {
372
+ throw new Error(
373
+ `[react-native-direct-imports] Can't find the entry file of "${name}" (${field ?? 'index'})`,
374
+ );
375
+ }
376
+
377
+ const { locals, reexports, stars } = analyze(entry);
378
+ if (locals.size + reexports.size + stars.length === 0) {
379
+ throw new Error(
380
+ `[react-native-direct-imports] "${name}" can't be resolved: its entry ${nodePath.relative(root, entry)} has no ES module exports (only packages that ship ES module sources or builds are supported)`,
381
+ );
382
+ }
383
+
384
+ const loaded = { root, entry, exportsMap };
385
+ packages.set(cacheKey, loaded);
386
+ return loaded;
387
+ };
388
+
389
+ // Every name the package's entry exports (`'default'` included), however
390
+ // it is reached. Used to generate maps.
391
+ const listExports = (packageName, fromDir) => {
392
+ const { entry } = loadPackage(packageName, fromDir);
393
+ const names = new Set();
394
+ const visited = new Set();
395
+
396
+ const visit = (file, viaStar) => {
397
+ if (visited.has(file)) return;
398
+ visited.add(file);
399
+
400
+ const info = analyze(file);
401
+ for (const name of [...info.locals, ...info.reexports.keys()]) {
402
+ // `export *` never re-exports `default`.
403
+ if (!(viaStar && name === 'default')) names.add(name);
404
+ }
405
+ for (const source of info.stars) {
406
+ const target = resolveSource(file, source);
407
+ if (target) visit(target, true);
408
+ }
409
+ };
410
+
411
+ visit(entry, false);
412
+ return [...names];
413
+ };
414
+
415
+ const resolved = new Map();
416
+
417
+ // Returns `['<package>/<path>', exportName]` for the module defining
418
+ // `importedName` (`'default'` for the default export), or `null` if the
419
+ // import should stay as it is.
420
+ const resolveImport = (packageName, fromDir, importedName) => {
421
+ const { root, entry, exportsMap } = loadPackage(packageName, fromDir);
422
+
423
+ const cacheKey = `${entry}\0${importedName}`;
424
+ if (resolved.has(cacheKey)) return resolved.get(cacheKey);
425
+
426
+ const origin = lookup(entry, importedName);
427
+ let result = null;
428
+ // Names declared in the entry file itself have nowhere else to go.
429
+ if (origin && origin.file !== entry) {
430
+ const relative = nodePath
431
+ .relative(root, origin.file)
432
+ .split(nodePath.sep)
433
+ .join('/');
434
+
435
+ if (exportsMap) {
436
+ const subpath = findExportedSubpath(exportsMap, `./${relative}`);
437
+ if (subpath !== null) {
438
+ result = [`${packageName}/${subpath.slice(2)}`, origin.name];
439
+ }
440
+ } else {
441
+ result = [
442
+ `${packageName}/${relative.replace(/\.(?:[cm]?[jt]sx?)$/, '')}`,
443
+ origin.name,
444
+ ];
445
+ }
446
+ }
447
+
448
+ resolved.set(cacheKey, result);
449
+ return result;
450
+ };
451
+
452
+ return { resolveImport, listExports };
453
+ };
454
+
455
+ module.exports = { createPackageResolver, findPackageRoot };
package/CHANGELOG.md DELETED
@@ -1,21 +0,0 @@
1
- # babel-plugin-react-native-direct-imports
2
-
3
- ## 1.2.0
4
-
5
- ### Minor Changes
6
-
7
- - [#8](https://github.com/retyui/babel-plugin-react-native-direct-imports/pull/8) [`a4c6d6e`](https://github.com/retyui/babel-plugin-react-native-direct-imports/commit/a4c6d6e76448742134745b8c11e9a2ac0aff06f4) Thanks [@retyui](https://github.com/retyui)! - Ship all version maps as a single `maps.json` with version ranges instead of 142 per-version files, cutting the installed package size by ~98% (≈980 KB of maps -> ≈15 KB) and the npm tarball from ≈19 KB to ≈10 KB.
8
-
9
- An unknown `reactNativeVersion` now falls back to the closest older map instead of failing the build, so upgrading React Native before updating the plugin no longer breaks it. Only a version older than every known map (< 0.70.0) throws.
10
-
11
- ## 1.1.2
12
-
13
- ### Patch Changes
14
-
15
- - [`2570f1a`](https://github.com/retyui/babel-plugin-react-native-direct-imports/commit/2570f1acf12e7d79f827fb4ad240bfd850e7ebf9) Thanks [@retyui](https://github.com/retyui)! - Add react-native 0.88.1 map
16
-
17
- ## 1.1.1
18
-
19
- ### Patch Changes
20
-
21
- - [`cc962c5`](https://github.com/retyui/babel-plugin-react-native-direct-imports/commit/cc962c50b402247d6fce371fe1a8afc2dd429ca3) Thanks [@retyui](https://github.com/retyui)! - Publish via npm trusted publishing with provenance