expo 58.0.16 → 58.0.19

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.
@@ -7,9 +7,10 @@
7
7
  * two forms:
8
8
  *
9
9
  * - PRECOMPILED — modules with built Debug + Release xcframeworks
10
- * (ExpoModulesCore, ExpoModulesJSI, ExpoModulesWorklets, …): declared to
10
+ * (ExpoModulesCore, ExpoModulesWorklets, …): declared to
11
11
  * RN as paired dynamic frameworks. RN selects, links, embeds, and signs
12
- * them outside SwiftPM.
12
+ * them outside SwiftPM. ExpoModulesJSI is the exception: an app build
13
+ * phase compiles it against the app's React Native.
13
14
  * - SOURCE-BUILT — modules compiled from source (Expo, EXConstants, …):
14
15
  * emitted as a source `Package.swift`. Pure-Swift modules are a single
15
16
  * target; mixed Swift/ObjC modules need a checked-in Package.swift.
@@ -37,6 +38,7 @@
37
38
  'use strict';
38
39
 
39
40
  const fs = require('fs');
41
+ const { createRequire } = require('module');
40
42
  const path = require('path');
41
43
 
42
44
  const { readPodfileProperties, resolveAppTarget } = require('./app-target');
@@ -53,12 +55,14 @@ const {
53
55
  moduleNeedsReact,
54
56
  scanAppleSources,
55
57
  } = require('./classify');
58
+ const { configureSpmUpdateCommand, spmUpdateCommand } = require('./commands');
56
59
  const {
57
60
  classifyUnsupported,
58
61
  collectDuplicatePods,
59
62
  collectRootConflicts,
60
63
  pluginError,
61
64
  realPathOrSelf,
65
+ renderBuildFromSourceFallbackWarning,
62
66
  renderExtraPodsWarning,
63
67
  renderLeftOutCompanionWarning,
64
68
  renderPartlyProvidedPackageWarning,
@@ -66,22 +70,44 @@ const {
66
70
  renderUnmappedDependencyWarning,
67
71
  renderXcconfigLinkerWarning,
68
72
  reportUnsupported,
73
+ BUILD_FROM_SOURCE_OPTION,
74
+ rerunSpmUpdate,
69
75
  unmappedPodDependencies,
70
76
  } = require('./diagnostics');
71
77
  const {
78
+ PRECOMPILED_SOURCE_KINDS,
72
79
  artifactBaseDirs,
73
80
  assertDistinctFlavoredFrameworks,
81
+ assertHeadersMatchSources,
74
82
  byteOrder,
83
+ frameworkSource,
84
+ hasPrecompiledArtifact,
85
+ headersXCFrameworkDirs,
86
+ headersXCFrameworkSearchPaths,
75
87
  prepareCompileInterfaces,
76
88
  resolveFlavoredFramework,
89
+ resolveHeadersXCFramework,
90
+ resolveHeadersXCFrameworkWithSource,
77
91
  resolveSpmDependencyFrameworks,
78
92
  } = require('./flavored-frameworks');
79
- const { emitSourceManifestPackage, emitPureSwiftSourcePackage } = require('./manifests');
93
+ const {
94
+ dependsOnCoreHeaders,
95
+ dumpModuleManifest,
96
+ emitDirectPackage,
97
+ prepareDirectWatchPaths,
98
+ } = require('./direct');
99
+ const {
100
+ emitExpoModulesJSIHeadersPackage,
101
+ emitPureSwiftSourcePackage,
102
+ emitSourceManifestPackage,
103
+ } = require('./manifests');
80
104
  const { readPrebuiltMetadata } = require('./metadata');
81
105
  const { readPodspecFacts } = require('./podspec');
82
106
  const { scriptPhasesForModules } = require('./script-phases');
83
107
 
84
108
  const CORE_POD = 'ExpoModulesCore';
109
+ const CORE_PACKAGE = 'expo-modules-core';
110
+ const JSI_POD = 'ExpoModulesJSI';
85
111
 
86
112
  /** npm name → autolinked root, only for roots still on disk. */
87
113
  function collectAutolinkedRoots(autolinking) {
@@ -103,7 +129,7 @@ function collectAutolinkedRoots(autolinking) {
103
129
  * podspec dir that is gone is its own declaring root, or two missing packages would
104
130
  * walk up to one ancestor and pass for one.
105
131
  */
106
- function podIdentity(record, pod, packageName, autolinkedRoot, scanSources) {
132
+ function podIdentity(record, pod, packageName, autolinkedRoot, readModuleRoot) {
107
133
  const documentedRoot = documentedPackageRoot(record);
108
134
  const walkedRoot = autolinkedRoot ?? findModuleRoot(pod.podspecDir);
109
135
  const declaringRoot =
@@ -122,21 +148,27 @@ function podIdentity(record, pod, packageName, autolinkedRoot, scanSources) {
122
148
  iosDeploymentTarget: record?.iosDeploymentTarget ?? null,
123
149
  spmPackages: record?.spmPackages ?? [],
124
150
  autolinkWhen: record?.autolinkWhen ?? null,
125
- sources: scanSources(moduleRoot),
151
+ sources: readModuleRoot.sources(moduleRoot),
126
152
  podspec: readPodspecFacts({ podName: pod.podName, podspecDir: pod.podspecDir, moduleRoot }),
127
153
  };
128
154
  }
129
155
 
156
+ /** `read`, run at most once per module root: several pods can share one. */
157
+ function oncePerModuleRoot(read) {
158
+ const results = new Map();
159
+ return (moduleRoot) => {
160
+ if (!results.has(moduleRoot)) results.set(moduleRoot, read(moduleRoot));
161
+ return results.get(moduleRoot);
162
+ };
163
+ }
164
+
130
165
  /**
131
166
  * Every pod's identity, keyed by the pod, resolved once so every pass agrees on it.
132
167
  *
133
168
  * @param metadata `readPrebuiltMetadata()`: records by pod name.
134
169
  */
135
170
  function resolvePodIdentities(modules, metadata, autolinkedRoots) {
136
- const sourceScans = new Map();
137
- const scanSources = (moduleRoot) =>
138
- sourceScans.get(moduleRoot) ??
139
- sourceScans.set(moduleRoot, scanAppleSources(moduleRoot)).get(moduleRoot);
171
+ const readModuleRoot = { sources: oncePerModuleRoot(scanAppleSources) };
140
172
  const identities = new Map();
141
173
  for (const mod of modules) {
142
174
  for (const pod of mod.pods ?? []) {
@@ -147,7 +179,7 @@ function resolvePodIdentities(modules, metadata, autolinkedRoots) {
147
179
  pod,
148
180
  mod.packageName,
149
181
  autolinkedRoots.get(mod.packageName),
150
- scanSources
182
+ readModuleRoot
151
183
  )
152
184
  );
153
185
  }
@@ -286,55 +318,270 @@ function uncoveredPod(identity, ...refusals) {
286
318
 
287
319
  /**
288
320
  * What the passes decided for each pod, keyed by pod name: CocoaPods pod names are
289
- * unique, so a name two packages list is one pod. `linkedAs` is `'precompiled'`,
290
- * `'manifest'`, `'pure-swift'` or null. A precompiled record carries its
291
- * `framework`.
321
+ * unique, so a name two packages list is one pod. `linkedAs` is `'build-phase'`,
322
+ * `'precompiled'`, `'manifest'`, `'pure-swift'` or null. ExpoModulesJSI starts as
323
+ * `'build-phase'` (see `linkExpoModulesJSI`). A precompiled record carries its
324
+ * `framework`; `linkPrecompiledPods` documents `buildFromSource`.
292
325
  */
293
326
  function podRecords(identities) {
294
327
  const records = new Map();
295
328
  for (const identity of identities.values()) {
296
329
  if (!records.has(identity.podName)) {
297
- records.set(identity.podName, { identity, linkedAs: null });
330
+ const linkedAs = identity.podName === JSI_POD ? 'build-phase' : null;
331
+ records.set(identity.podName, { identity, linkedAs });
298
332
  }
299
333
  }
300
334
  return records;
301
335
  }
302
336
 
337
+ /**
338
+ * Before pass 1 — ExpoModulesJSI is never linked precompiled, whatever artifacts exist:
339
+ * it must be compiled against the app's React Native, which the app's "Build
340
+ * ExpoModulesJSI" phase does. Source packages compile against its headers package
341
+ * instead. Returns that package's directory, or null when expo-modules-jsi is not
342
+ * autolinked.
343
+ */
344
+ function linkExpoModulesJSI(identities, outDir, cacheDir, appRoot) {
345
+ const identity = [...identities.values()].find((i) => i.podName === JSI_POD);
346
+ if (identity == null) return null;
347
+ const { packageName, moduleRoot, productName } = identity;
348
+ const headers = resolveHeadersXCFramework({ packageName, moduleRoot, productName, cacheDir });
349
+ if (headers == null) {
350
+ const searched = headersXCFrameworkDirs(packageName, moduleRoot);
351
+ throw pluginError({
352
+ what: `${productName}Headers.xcframework (or .tar.gz) was not found in ${searched.join(', ')}.`,
353
+ why: `npm ships only the headers of ${productName}, because the framework must be compiled against the app's React Native: Swift packages compile against those headers, and the app's "Build ${productName}" phase builds the framework.`,
354
+ how: `Reinstall ${packageName} with your package manager. From the Expo repository root, build the headers with \`node tools/bin/expotools.js prebuild ${packageName}\`.`,
355
+ });
356
+ }
357
+ const builtRoot = buildPhaseJsiRoot(appRoot);
358
+ assertHeadersMatchSources(headers, {
359
+ packageName,
360
+ productName,
361
+ sourceRoots: builtRoot == null ? [moduleRoot] : [moduleRoot, builtRoot],
362
+ });
363
+ return emitExpoModulesJSIHeadersPackage(headers, outDir);
364
+ }
365
+
366
+ /**
367
+ * The expo-modules-jsi the app's "Build ExpoModulesJSI" phase builds, resolved through expo and
368
+ * expo-modules-core as its launcher in script-phases.js does. Null when that chain does not resolve.
369
+ */
370
+ function buildPhaseJsiRoot(appRoot) {
371
+ // Not `require.resolve(..., { paths })`: from inside the expo package, Node resolves `expo` to
372
+ // this package itself, whatever the paths.
373
+ const dir = (name, from) =>
374
+ path.dirname(createRequire(path.join(from, 'package.json')).resolve(`${name}/package.json`));
375
+ try {
376
+ return dir('expo-modules-jsi', dir('expo-modules-core', dir('expo', appRoot)));
377
+ } catch {
378
+ return null;
379
+ }
380
+ }
381
+
382
+ /**
383
+ * The entry of the app's `buildFromSource` autolinking option that matches a pod, as
384
+ * `{ entry, exact }`, or undefined. An entry is exact for a pod when it is, character for
385
+ * character, the pod name or the npm package name. Any other entry is a pattern, matched as
386
+ * CocoaPods matches it in `precompiled_modules.rb#build_from_source?`: a regular expression
387
+ * that must match the whole pod name or npm package name. An exact entry wins over a pattern.
388
+ * An exact entry for ExpoModulesCore fails the sync, because every source package compiles
389
+ * against the precompiled one; a pattern matching it leaves it precompiled.
390
+ */
391
+ function buildFromSourceMatcher(patterns) {
392
+ const entries = patterns.map((pattern) => {
393
+ try {
394
+ return { pattern, expression: new RegExp(`^${pattern}$`) };
395
+ } catch (error) {
396
+ throw pluginError(
397
+ {
398
+ what: `The buildFromSource entry "${pattern}" in your app's Expo autolinking options is not a valid regular expression: ${error.message}.`,
399
+ why: 'Each entry is matched as a regular expression against the pod name and the npm package name of every module, to choose the modules built from source instead of linked precompiled.',
400
+ how: `Fix the entry in ${BUILD_FROM_SOURCE_OPTION}. ${rerunSpmUpdate()}`,
401
+ },
402
+ { cause: error }
403
+ );
404
+ }
405
+ });
406
+ const matchFor = ({ podName, packageName }) => {
407
+ const exact = patterns.find((pattern) => pattern === podName || pattern === packageName);
408
+ if (exact != null) return { entry: exact, exact: true };
409
+ const pattern = entries.find(
410
+ ({ expression }) => expression.test(podName) || expression.test(packageName)
411
+ )?.pattern;
412
+ return pattern != null ? { entry: pattern, exact: false } : undefined;
413
+ };
414
+ const coreMatch = matchFor({ podName: CORE_POD, packageName: CORE_PACKAGE });
415
+ if (coreMatch?.exact) {
416
+ const coreEntry = coreMatch.entry;
417
+ throw pluginError({
418
+ what: `The buildFromSource entry "${coreEntry}" in your app's Expo autolinking options matches ${CORE_POD} (${CORE_PACKAGE}), which Swift Package Manager cannot build from source.`,
419
+ why: `Under Swift Package Manager, ${CORE_POD} is always linked precompiled: every Expo module built from source compiles against its precompiled interface.`,
420
+ how: `Remove "${coreEntry}" from ${BUILD_FROM_SOURCE_OPTION}, or narrow it so it no longer matches ${CORE_POD} or ${CORE_PACKAGE}. ${rerunSpmUpdate()}`,
421
+ });
422
+ }
423
+ return matchFor;
424
+ }
425
+
303
426
  /**
304
427
  * Pass 1 — precompiled runtime frameworks. The declaration is all-or-nothing:
305
428
  * once one flavor exists, the resolver requires and prepares both before RN
306
429
  * receives the plugin result. No runtime binary enters the SwiftPM graph.
307
430
  * A pod name several packages list is looked up from each of them, in order,
308
- * until one has an artifact. Returns the records it linked, in that order.
431
+ * until one has an artifact. A pod the app builds from source — buildFromSource matches
432
+ * the pod or any package that lists it, an exact entry for any of them winning — is never
433
+ * linked precompiled, unless it is one of `fallbackPods`; when it has an artifact, its
434
+ * record keeps the `buildFromSource` match, so a pattern can fall back and an exact entry
435
+ * be reported should no source route take it. A fallback pod whose artifact does not resolve
436
+ * keeps its match too, marked `precompiledIncomplete`. Returns the records it linked, in that
437
+ * order.
438
+ *
439
+ * @param matchBuildFromSource `buildFromSourceMatcher`'s result.
440
+ * @param fallbackPods the matching pattern by pod name, for each pod linked precompiled though
441
+ * a pattern matches it.
309
442
  */
310
- function linkPrecompiledPods(identities, records, cacheDir) {
443
+ function linkPrecompiledPods(identities, records, cacheDir, matchBuildFromSource, fallbackPods) {
444
+ const matchesByPod = new Map();
445
+ for (const identity of identities.values()) {
446
+ if (fallbackPods.has(identity.podName)) continue;
447
+ const match = matchBuildFromSource(identity);
448
+ const known = matchesByPod.get(identity.podName);
449
+ if (match != null && (known == null || (match.exact && !known.exact))) {
450
+ matchesByPod.set(identity.podName, match);
451
+ }
452
+ }
311
453
  const linked = [];
312
454
  for (const identity of identities.values()) {
313
455
  const record = records.get(identity.podName);
314
456
  if (record.linkedAs != null) continue;
315
- const framework = resolveFlavoredFramework({
457
+ const lookup = {
316
458
  packageName: identity.packageName,
317
459
  moduleRoot: identity.moduleRoot,
318
460
  frameworkName: identity.productName,
319
- cacheDir,
320
- });
321
- if (framework == null) continue;
461
+ };
462
+ const match = matchesByPod.get(identity.podName);
463
+ if (match != null) {
464
+ if (record.buildFromSource == null && hasPrecompiledArtifact(lookup)) {
465
+ record.buildFromSource = match;
466
+ }
467
+ continue;
468
+ }
469
+ const framework = resolveFlavoredFramework({ ...lookup, cacheDir });
470
+ if (framework == null) {
471
+ if (fallbackPods.has(identity.podName)) {
472
+ const entry = fallbackPods.get(identity.podName);
473
+ record.buildFromSource = { entry, exact: false, precompiledIncomplete: true };
474
+ }
475
+ continue;
476
+ }
322
477
  Object.assign(record, { identity, linkedAs: 'precompiled', framework });
323
478
  linked.push(record);
324
479
  }
325
480
  return linked;
326
481
  }
327
482
 
483
+ const SOURCE_LABELS = {
484
+ env: 'EXPO_PRECOMPILED_MODULES_PATH',
485
+ monorepo: 'the Expo monorepo prebuild output',
486
+ bundled: 'its npm package',
487
+ };
488
+
489
+ const describeSource = (source) => `${SOURCE_LABELS[source.kind]} (${source.dir})`;
490
+
491
+ /**
492
+ * Compares the kind of place, not the directory: every package has its own directory in
493
+ * each of them. Returns the `pluginError` parts describing the mix, or null when there is
494
+ * none.
495
+ *
496
+ * @param subjects `{ label, packageName, source }` for each precompiled artifact to check.
497
+ */
498
+ function mixedSourcesReport(coreSource, subjects) {
499
+ const mixed = subjects.filter((subject) => subject.source?.kind !== coreSource?.kind);
500
+ if (mixed.length === 0) return null;
501
+ const packages = [...new Set(mixed.map((subject) => subject.packageName))].join(' ');
502
+ return {
503
+ what: `${mixed
504
+ .map(
505
+ (subject) =>
506
+ `${subject.label} (${subject.packageName}) comes from ${describeSource(subject.source)}`
507
+ )
508
+ .join('; ')}, but ExpoModulesCore comes from ${describeSource(coreSource)}.`,
509
+ why: 'Precompiled Expo modules, and the headers Expo modules compile against, are bound to the exact ExpoModulesCore build they were made with, so mixing builds from different places can crash the app at launch on a missing symbol.',
510
+ how: `Take every precompiled module from one place: unset EXPO_PRECOMPILED_MODULES_PATH if it is set; from the Expo repository root, build the packages into the same place as ExpoModulesCore with \`node tools/bin/expotools.js prebuild ${packages}\`; otherwise reinstall your JavaScript dependencies so every package uses the build it ships. ${rerunSpmUpdate()}`,
511
+ };
512
+ }
513
+
514
+ /**
515
+ * The ExpoModulesCore headers xcframework, for direct modules to compile against. It must
516
+ * come from the same kind of place as the ExpoModulesCore binary.
517
+ */
518
+ function resolveCoreHeaders(core, coreSource, cacheDir) {
519
+ const { packageName, moduleRoot, productName } = core;
520
+ const lookup = { packageName, moduleRoot, productName };
521
+ const lookupRank = (source) => PRECOMPILED_SOURCE_KINDS.indexOf(source.kind);
522
+ const builtLocally = coreSource?.kind === 'env' || coreSource?.kind === 'monorepo';
523
+ // Headers past the place a local ExpoModulesCore build comes from cannot match it, so the
524
+ // lookup ends there: a broken copy further on would fail first, with advice that cannot
525
+ // fix the missing headers. No headers up to that place mean the build produced none.
526
+ const headers = resolveHeadersXCFrameworkWithSource({
527
+ ...lookup,
528
+ cacheDir,
529
+ lastKind: builtLocally ? coreSource.kind : undefined,
530
+ });
531
+ if (builtLocally && (headers == null || lookupRank(headers.source) > lookupRank(coreSource))) {
532
+ const prebuild = '`node tools/bin/expotools.js prebuild expo-modules-core expo-modules-jsi`';
533
+ throw pluginError({
534
+ what: `${productName}Headers.xcframework is missing under ${coreSource.dir}, where ${productName} comes from (${SOURCE_LABELS[coreSource.kind]}).`,
535
+ why: `Expo modules built from their own Package.swift compile against these headers, and the headers must come from the same build as ${productName}. That build did not produce them.`,
536
+ how:
537
+ coreSource.kind === 'env'
538
+ ? `Unset EXPO_PRECOMPILED_MODULES_PATH, or point it at a directory that holds a complete prebuild of expo-modules-core and expo-modules-jsi, including their headers. ${rerunSpmUpdate()}`
539
+ : `From the Expo repository root, run ${prebuild}. ${rerunSpmUpdate()}`,
540
+ });
541
+ }
542
+ if (headers == null) {
543
+ throw pluginError({
544
+ what: `Expo modules built from their own Package.swift compile against ${productName}Headers.xcframework, which was not found (searched ${headersXCFrameworkSearchPaths(lookup).join(', ')}).`,
545
+ why: `The installed ${packageName} was published without a headers xcframework, or the local prebuild has not produced it yet.`,
546
+ how: `From the Expo repository root, run \`node tools/bin/expotools.js prebuild ${packageName}\`. Otherwise upgrade ${packageName} to a version that ships a headers xcframework. ${rerunSpmUpdate()}`,
547
+ });
548
+ }
549
+ const mixed = mixedSourcesReport(coreSource, [
550
+ { label: `${productName}Headers.xcframework`, packageName, source: headers.source },
551
+ ]);
552
+ if (mixed != null) throw pluginError(mixed);
553
+ return headers.xcframework;
554
+ }
555
+
328
556
  /**
329
- * Emits the source package of the module whose first pod is `identity`: its
330
- * checked-in manifest mirrored, or else one Swift target over its sources. A
557
+ * Emits the source package of the module whose first pod is `identity`: its checked-in
558
+ * manifest as it stands when that depends on ExpoModulesCoreHeaders (`direct` is then
559
+ * set), else that manifest mirrored, or else one Swift target over its sources. A
331
560
  * pure-Swift module is refused when its podspec declares linkage, because the
332
561
  * emitted package would link less than the podspec does. Returns null for a module
333
562
  * with no sources: the pod's own `no-apple-sources` report covers it.
563
+ *
564
+ * @param dumpManifest `dumpModuleManifest`, run at most once per real module root.
334
565
  */
335
- function emitSourceModule(identity, hasManifest, emitContext) {
336
- const { moduleRoot, podName, iosDeploymentTarget, spmPackages, sources, podspec } = identity;
337
- if (hasManifest) return emitSourceManifestPackage(moduleRoot, emitContext);
566
+ function emitSourceModule(identity, hasManifest, emitContext, dumpManifest) {
567
+ const { moduleRoot, packageName, podName, iosDeploymentTarget, spmPackages, sources, podspec } =
568
+ identity;
569
+ if (hasManifest) {
570
+ const { json, manifest } = dumpManifest(moduleRoot, packageName);
571
+ if (!dependsOnCoreHeaders(manifest)) {
572
+ return emitSourceManifestPackage(moduleRoot, emitContext, json);
573
+ }
574
+ const emission = emitDirectPackage({
575
+ moduleRoot,
576
+ packageName,
577
+ outDir: emitContext.outDir,
578
+ coreHeadersXCFramework: emitContext.coreHeadersXCFramework,
579
+ jsiHeadersPkgPath: emitContext.jsiHeadersPkgPath,
580
+ macroTool: emitContext.macroTool,
581
+ manifest,
582
+ });
583
+ return { ...emission, direct: true };
584
+ }
338
585
  if (podspec.linkage != null) {
339
586
  return { refusal: { reason: 'needs-manifest-for-linkage', ...podspec.linkage } };
340
587
  }
@@ -350,12 +597,14 @@ function emitSourceModule(identity, hasManifest, emitContext) {
350
597
  * headers/module-interface tree and leave runtime linking entirely to RN.
351
598
  *
352
599
  * @param emitContext what every emitted package is generated against.
353
- * @returns `emitted`, one `{ identity, linkedAs, emission }` per package it emitted, in
354
- * emission order, `identity` being the pod it was emitted for; and `refusals`, by
600
+ * @param dumpManifest `manifestDumper`'s result.
601
+ * @returns `emitted`, one `{ identity, linkedAs, direct, emission }` per package it emitted,
602
+ * in emission order, `identity` being the pod it was emitted for and `direct` whether a
603
+ * checked-in manifest is built as it stands; and `refusals`, by
355
604
  * module root and then reason, each a function from an uncovered pod's identity to
356
605
  * its refusal.
357
606
  */
358
- function linkSourceModules(modules, identities, records, emitContext) {
607
+ function linkSourceModules(modules, identities, records, emitContext, dumpManifest) {
359
608
  const emitted = [];
360
609
  const refusals = new Map();
361
610
  // What the branches below read comes from the first pod's module root, so a
@@ -402,15 +651,15 @@ function linkSourceModules(modules, identities, records, emitContext) {
402
651
  // emitSourceModule for the podspec linkage check that outranks it.
403
652
  if (!hasManifest && !sources.pureSwift) continue;
404
653
 
405
- const emission = emitSourceModule(first, hasManifest, emitContext);
654
+ const emission = emitSourceModule(first, hasManifest, emitContext, dumpManifest);
406
655
  if (emission == null) continue;
407
- const { refusal, ok } = emission;
656
+ const { refusal, ok, direct = false } = emission;
408
657
  if (refusal != null) {
409
658
  refuse(moduleRoot, refusal.reason, () => refusal);
410
659
  continue;
411
660
  }
412
661
  const kind = hasManifest ? 'manifest' : 'pure-swift';
413
- emitted.push({ identity: first, linkedAs: kind, emission: ok });
662
+ emitted.push({ identity: first, linkedAs: kind, direct, emission: ok });
414
663
  if (!hasManifest) {
415
664
  Object.assign(records.get(first.podName), { identity: first, linkedAs: kind });
416
665
  continue;
@@ -434,6 +683,124 @@ function linkSourceModules(modules, identities, records, emitContext) {
434
683
  return { emitted, refusals };
435
684
  }
436
685
 
686
+ /** `dumpModuleManifest`, run at most once per real module root. */
687
+ function manifestDumper() {
688
+ // By real path: listings can reach one manifest through different symlinks.
689
+ const dumpsByRealRoot = new Map();
690
+ return (moduleRoot, packageName) => {
691
+ const realRoot = fs.realpathSync(moduleRoot);
692
+ if (!dumpsByRealRoot.has(realRoot)) {
693
+ dumpsByRealRoot.set(realRoot, dumpModuleManifest(moduleRoot, packageName));
694
+ }
695
+ return dumpsByRealRoot.get(realRoot);
696
+ };
697
+ }
698
+
699
+ /**
700
+ * Both passes, over fresh pod records, with the pods in `fallbackPods` linked precompiled
701
+ * though a buildFromSource pattern matches them.
702
+ *
703
+ * @param sourceContext `{ react, outDir, codegenPkgPath, jsiHeadersPkgPath }`: what every
704
+ * emitted package is generated against, besides what pass 1 decides.
705
+ */
706
+ function linkPasses(
707
+ fallbackPods,
708
+ { modules, identities, cacheDir, matchBuildFromSource, dumpManifest, sourceContext }
709
+ ) {
710
+ const records = podRecords(identities);
711
+ const precompiled = linkPrecompiledPods(
712
+ identities,
713
+ records,
714
+ cacheDir,
715
+ matchBuildFromSource,
716
+ fallbackPods
717
+ );
718
+ // The SwiftPM packages those modules link ship as their own XCFrameworks, and
719
+ // RN takes them in the same flat array. They join before the interface tree is
720
+ // built, so source modules compile against their headers too.
721
+ const dependencyFrameworks = resolveSpmDependencyFrameworks(
722
+ precompiled.map(({ identity: { podName, moduleRoot, spmPackages } }) => ({
723
+ podName,
724
+ moduleRoot,
725
+ spmDependencies: spmPackages.map((pkg) => pkg.productName),
726
+ }))
727
+ );
728
+ const flavoredFrameworks = [...precompiled.map((r) => r.framework), ...dependencyFrameworks].sort(
729
+ (a, b) => byteOrder(a.id, b.id)
730
+ );
731
+ assertDistinctFlavoredFrameworks(flavoredFrameworks);
732
+ const coreRecord = precompiled.find((r) => r.identity.podName === CORE_POD) ?? null;
733
+ const coreSource = coreRecord && frameworkSource(coreRecord.framework);
734
+ const satisfiedDependencies = new Set(dependencyFrameworks.map((f) => f.frameworkName));
735
+ const frameworkSearchPath =
736
+ precompiled.length > 0
737
+ ? prepareCompileInterfaces(
738
+ flavoredFrameworks,
739
+ path.join(sourceContext.outDir, 'compile-interfaces')
740
+ )
741
+ : null;
742
+
743
+ const core = coreRecord?.identity ?? null;
744
+ const coreAvailable = core != null && frameworkSearchPath != null;
745
+ let sourceModules = { emitted: [], refusals: new Map() };
746
+ if (coreAvailable) {
747
+ let resolvedMacroFlags = null;
748
+ let resolvedCoreHeadersXCFramework = null;
749
+ sourceModules = linkSourceModules(
750
+ modules,
751
+ identities,
752
+ records,
753
+ {
754
+ ...sourceContext,
755
+ frameworkSearchPath,
756
+ minimumIosDeploymentTarget: core.iosDeploymentTarget,
757
+ satisfiedDependencies,
758
+ // Every emitted target may use the macros (CocoaPods' "is core or depends on core" gate).
759
+ // Lazy: an install that emits no source package needs no macro plugin.
760
+ get macroFlags() {
761
+ return (resolvedMacroFlags ??= macroPluginFlags(core.moduleRoot));
762
+ },
763
+ get macroTool() {
764
+ return macroPluginTool(core.moduleRoot);
765
+ },
766
+ // Lazy: only a direct module needs the headers, and only then must they exist.
767
+ get coreHeadersXCFramework() {
768
+ return (resolvedCoreHeadersXCFramework ??= resolveCoreHeaders(
769
+ core,
770
+ coreSource,
771
+ cacheDir
772
+ ));
773
+ },
774
+ },
775
+ dumpManifest
776
+ );
777
+ }
778
+ return {
779
+ records,
780
+ precompiled,
781
+ flavoredFrameworks,
782
+ coreRecord,
783
+ coreSource,
784
+ satisfiedDependencies,
785
+ coreAvailable,
786
+ sourceModules,
787
+ };
788
+ }
789
+
790
+ /**
791
+ * Removes the packages an earlier round of `linkPasses` emitted that the last round did not,
792
+ * so no package the sync dropped is left beside the ones it links.
793
+ *
794
+ * @param emittedByRound `sourceModules.emitted` of each round, the last round last.
795
+ */
796
+ function removeDiscardedEmissions(emittedByRound) {
797
+ const packagePath = ({ emission }) => emission.packageDep.path;
798
+ const kept = new Set(emittedByRound.at(-1).map(packagePath));
799
+ for (const discarded of new Set(emittedByRound.slice(0, -1).flat().map(packagePath))) {
800
+ if (!kept.has(discarded)) fs.rmSync(discarded, { recursive: true, force: true });
801
+ }
802
+ }
803
+
437
804
  /**
438
805
  * The emitted products React Native links, and a label for each one an unmet
439
806
  * `autolinkWhen` condition withholds. Only a checked-in manifest's products are
@@ -491,7 +858,11 @@ function summarizeRecords(
491
858
  );
492
859
  const pending = [...records.values()]
493
860
  .filter((r) => r.linkedAs == null)
494
- .map(({ identity }) => uncoveredPod(identity, ...refusalsFor(identity)));
861
+ .map(({ identity, buildFromSource }) => ({
862
+ ...uncoveredPod(identity, ...refusalsFor(identity)),
863
+ buildFromSourceEntry: buildFromSource?.entry,
864
+ precompiledIncomplete: buildFromSource?.precompiledIncomplete,
865
+ }));
495
866
 
496
867
  // What the resolved dependencies already carry is not uncovered, their subspecs
497
868
  // included.
@@ -531,6 +902,8 @@ function summarizeRecords(
531
902
  ...(react != null ? emitted : []),
532
903
  ];
533
904
  const podNames = (list) => list.map((r) => r.identity.podName);
905
+ const packageNames = (list) => list.map((r) => r.identity.packageName);
906
+ const fromManifests = emitted.filter((r) => r.linkedAs === 'manifest');
534
907
 
535
908
  return {
536
909
  packageDependencies: emitted.map((r) => r.emission.packageDep),
@@ -545,9 +918,8 @@ function summarizeRecords(
545
918
  ),
546
919
  xcconfigLinkage,
547
920
  precompiledPods: podNames(precompiled),
548
- manifestPackages: emitted
549
- .filter((r) => r.linkedAs === 'manifest')
550
- .map((r) => r.identity.packageName),
921
+ manifestPackages: packageNames(fromManifests),
922
+ directPackages: packageNames(fromManifests.filter((r) => r.direct)),
551
923
  pureSwiftPods: podNames(pureSwift),
552
924
  reactWiredPods: podNames(reactWired),
553
925
  };
@@ -574,7 +946,7 @@ function watchPaths(identities, { entitlementPath, podfilePropertiesPath }) {
574
946
  // Swift macros need the prebuilt plugin executable; mirrors
575
947
  // project_integrator.rb#resolve_macros_plugin_dir.
576
948
  // It declares no SwiftPM products, so it travels as a compiler flag, not a dependency.
577
- function macroPluginFlags(coreModuleRoot) {
949
+ function macroPluginTool(coreModuleRoot) {
578
950
  const macroPluginFault = (
579
951
  what,
580
952
  missing,
@@ -605,9 +977,24 @@ function macroPluginFlags(coreModuleRoot) {
605
977
  macroPluginFault(`The Expo Swift macro plugin is missing its executable at ${tool}.`, 'it')
606
978
  );
607
979
  }
980
+ return tool;
981
+ }
982
+
983
+ function macroPluginFlags(coreModuleRoot) {
984
+ const tool = macroPluginTool(coreModuleRoot);
608
985
  return ['-Xfrontend', '-load-plugin-executable', '-Xfrontend', `${tool}#ExpoModulesMacros`];
609
986
  }
610
987
 
988
+ /** The app's react-native: the root React Native passes, or else the one the app resolves. */
989
+ function appReactNativeRoot(context, appRoot) {
990
+ if (typeof context.reactNativeRoot === 'string') return context.reactNativeRoot;
991
+ try {
992
+ return path.dirname(require.resolve('react-native/package.json', { paths: [appRoot] }));
993
+ } catch {
994
+ return null;
995
+ }
996
+ }
997
+
611
998
  module.exports = function expoSpmPlugin(context) {
612
999
  const { autolinking, react, outputDir } = context;
613
1000
  // `context.appRoot` is the Xcode project dir (`<app>/ios`); the autolinking
@@ -617,7 +1004,9 @@ module.exports = function expoSpmPlugin(context) {
617
1004
  // provider, with no Expo modules registering at runtime. RN's contract hands
618
1005
  // us that root directly.
619
1006
  const appRoot = context.projectRoot;
620
- const { modules, extraDependencies } = resolveExpoModules(appRoot);
1007
+ configureSpmUpdateCommand({ appRoot, reactNativeRoot: appReactNativeRoot(context, appRoot) });
1008
+ const { modules, extraDependencies, buildFromSource = [] } = resolveExpoModules(appRoot);
1009
+ const matchBuildFromSource = buildFromSourceMatcher(buildFromSource);
621
1010
  const metadata = readPrebuiltMetadata(appRoot);
622
1011
  const autolinkedRoots = collectAutolinkedRoots(autolinking);
623
1012
  const identities = resolvePodIdentities(modules, metadata, autolinkedRoots);
@@ -654,46 +1043,65 @@ module.exports = function expoSpmPlugin(context) {
654
1043
  ? codegenCandidate
655
1044
  : null;
656
1045
 
657
- const records = podRecords(identities);
658
- const precompiled = linkPrecompiledPods(identities, records, artifactCacheDir);
659
- // The SwiftPM packages those modules link ship as their own XCFrameworks, and
660
- // RN takes them in the same flat array. They join before the interface tree is
661
- // built, so source modules compile against their headers too.
662
- const dependencyFrameworks = resolveSpmDependencyFrameworks(
663
- precompiled.map(({ identity: { podName, moduleRoot, spmPackages } }) => ({
664
- podName,
665
- moduleRoot,
666
- spmDependencies: spmPackages.map((pkg) => pkg.productName),
667
- }))
668
- );
669
- const flavoredFrameworks = [...precompiled.map((r) => r.framework), ...dependencyFrameworks].sort(
670
- (a, b) => byteOrder(a.id, b.id)
671
- );
672
- assertDistinctFlavoredFrameworks(flavoredFrameworks);
673
- const satisfiedDependencies = new Set(dependencyFrameworks.map((f) => f.frameworkName));
674
- const frameworkSearchPath =
675
- precompiled.length > 0
676
- ? prepareCompileInterfaces(flavoredFrameworks, path.join(outDir, 'compile-interfaces'))
677
- : null;
678
-
679
- const core = precompiled.find((r) => r.identity.podName === CORE_POD)?.identity ?? null;
680
- const coreAvailable = core != null && frameworkSearchPath != null;
681
- let sourceModules = { emitted: [], refusals: new Map() };
682
- if (coreAvailable) {
683
- let resolvedMacroFlags = null;
684
- sourceModules = linkSourceModules(modules, identities, records, {
685
- react,
686
- frameworkSearchPath,
687
- outDir,
688
- codegenPkgPath,
689
- minimumIosDeploymentTarget: core.iosDeploymentTarget,
690
- satisfiedDependencies,
691
- // Every emitted target may use the macros (CocoaPods' "is core or depends on core" gate).
692
- // Lazy: an install that emits no source package needs no macro plugin.
693
- get macroFlags() {
694
- return (resolvedMacroFlags ??= macroPluginFlags(core.moduleRoot));
695
- },
696
- });
1046
+ const jsiHeadersPkgPath = linkExpoModulesJSI(identities, outDir, artifactCacheDir, appRoot);
1047
+ const passOptions = {
1048
+ modules,
1049
+ identities,
1050
+ cacheDir: artifactCacheDir,
1051
+ matchBuildFromSource,
1052
+ dumpManifest: manifestDumper(),
1053
+ sourceContext: { react, outDir, codegenPkgPath, jsiHeadersPkgPath },
1054
+ };
1055
+ // A pod a buildFromSource pattern matches is linked precompiled when no source route takes
1056
+ // it, as ExpoModulesCore never is. Linking one changes what pass 2 decides — a sibling pod's
1057
+ // route, the products already satisfied, the interface tree — so both passes run again until
1058
+ // no other pod falls back. Transitional: needed until every Expo module, ExpoModulesCore
1059
+ // included, has a checked-in Package.swift that SwiftPM can build from source.
1060
+ const fallbackEntries = new Map();
1061
+ const coreMatch = matchBuildFromSource({ podName: CORE_POD, packageName: CORE_PACKAGE });
1062
+ if (coreMatch != null) fallbackEntries.set(CORE_POD, coreMatch.entry);
1063
+ const emittedByRound = [];
1064
+ let passes;
1065
+ let fallingBack;
1066
+ do {
1067
+ passes = linkPasses(fallbackEntries, passOptions);
1068
+ emittedByRound.push(passes.sourceModules.emitted);
1069
+ fallingBack = [...passes.records.values()].filter(
1070
+ (r) =>
1071
+ r.linkedAs == null &&
1072
+ r.buildFromSource?.exact === false &&
1073
+ !fallbackEntries.has(r.identity.podName)
1074
+ );
1075
+ for (const { identity, buildFromSource } of fallingBack) {
1076
+ fallbackEntries.set(identity.podName, buildFromSource.entry);
1077
+ }
1078
+ } while (fallingBack.length > 0);
1079
+ removeDiscardedEmissions(emittedByRound);
1080
+ const {
1081
+ records,
1082
+ precompiled,
1083
+ flavoredFrameworks,
1084
+ coreRecord,
1085
+ coreSource,
1086
+ satisfiedDependencies,
1087
+ coreAvailable,
1088
+ sourceModules,
1089
+ } = passes;
1090
+ const mixedModules =
1091
+ coreRecord &&
1092
+ mixedSourcesReport(
1093
+ coreSource,
1094
+ precompiled
1095
+ .filter((r) => r !== coreRecord)
1096
+ .map(({ identity, framework }) => ({
1097
+ label: identity.productName,
1098
+ packageName: identity.packageName,
1099
+ source: frameworkSource(framework),
1100
+ }))
1101
+ );
1102
+ if (mixedModules != null) {
1103
+ const { what, why, how } = mixedModules;
1104
+ console.warn(`[expo-spm-plugin] WARNING: ${what} ${why} ${how}`);
697
1105
  }
698
1106
 
699
1107
  // Anything still uncovered has no xcframework and no way to be built from
@@ -710,8 +1118,10 @@ module.exports = function expoSpmPlugin(context) {
710
1118
  });
711
1119
  const logListed = (label, names) =>
712
1120
  console.log(`[expo-spm-plugin] ${label} (${names.length}): ${names.join(', ') || '—'}`);
1121
+ logListed('built by an app build phase', jsiHeadersPkgPath != null ? [JSI_POD] : []);
713
1122
  logListed('paired runtime frameworks', summary.precompiledPods);
714
1123
  logListed('source via checked-in manifest', summary.manifestPackages);
1124
+ logListed('source via direct checked-in manifest', summary.directPackages);
715
1125
  logListed('source pure-Swift', summary.pureSwiftPods);
716
1126
  logListed('React wired into', summary.reactWiredPods);
717
1127
  logListed('gated off', summary.gatedOffProducts);
@@ -719,6 +1129,16 @@ module.exports = function expoSpmPlugin(context) {
719
1129
  'not supported',
720
1130
  summary.pending.map((p) => p.podName)
721
1131
  );
1132
+ const fellBack = precompiled
1133
+ .filter((r) => fallbackEntries.has(r.identity.podName))
1134
+ .map(({ identity: { podName, packageName } }) => ({
1135
+ podName,
1136
+ packageName,
1137
+ entry: fallbackEntries.get(podName),
1138
+ }));
1139
+ if (fellBack.length > 0) {
1140
+ console.warn(renderBuildFromSourceFallbackWarning(fellBack));
1141
+ }
722
1142
  if (summary.unmappedDeps.length > 0) {
723
1143
  console.warn(renderUnmappedDependencyWarning(summary.unmappedDeps));
724
1144
  }
@@ -776,7 +1196,7 @@ module.exports = function expoSpmPlugin(context) {
776
1196
  [
777
1197
  `Generating ExpoModulesProvider.swift for ${appRoot} failed: ${error.message}`,
778
1198
  ' That file is the registry every Expo native module is looked up through, so without it the app builds and then fails at launch with "Cannot find native module".',
779
- ' The message above comes from `expo-modules-autolinking generate-modules-provider`. Fix what it names — a module with an unreadable expo-module.config.json is the common cause — then re-run `npx react-native spm update`.',
1199
+ ` The message above comes from \`expo-modules-autolinking generate-modules-provider\`. Fix what it names — a module with an unreadable expo-module.config.json is the common cause — then re-run \`${spmUpdateCommand()}\`.`,
780
1200
  ].join('\n'),
781
1201
  { cause: error }
782
1202
  );
@@ -786,7 +1206,7 @@ module.exports = function expoSpmPlugin(context) {
786
1206
  [
787
1207
  `The Expo module registry generator wrote no ExpoModulesProvider.swift to ${outDir}, although ${modules.length} Expo ${modules.length === 1 ? 'module' : 'modules'} resolved.`,
788
1208
  ' Without that file no Expo native module is registered, and the app fails at launch with "Cannot find native module".',
789
- ' Re-run `npx react-native spm update`. If the file is still missing, report it at https://github.com/expo/expo/issues with the output of `npx expo-modules-autolinking resolve --platform apple --json` run in your app.',
1209
+ ` Re-run \`${spmUpdateCommand()}\`. If the file is still missing, report it at https://github.com/expo/expo/issues with the output of \`npx expo-modules-autolinking resolve --platform apple --json\` run in your app.`,
790
1210
  ].join('\n')
791
1211
  );
792
1212
  }
@@ -811,12 +1231,13 @@ module.exports = function expoSpmPlugin(context) {
811
1231
  );
812
1232
  }
813
1233
 
1234
+ const directWatchPaths = prepareDirectWatchPaths(summary.directPackages, outDir);
814
1235
  return {
815
1236
  packageDependencies: summary.packageDependencies,
816
1237
  productDependencies: summary.productDependencies,
817
1238
  generatedSources,
818
1239
  flavoredFrameworks,
819
- watchPaths: watchPaths(identities, appTarget),
1240
+ watchPaths: [...watchPaths(identities, appTarget), ...directWatchPaths],
820
1241
  scriptPhases,
821
1242
  };
822
1243
  };