-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.plugin.js
More file actions
688 lines (649 loc) · 26.1 KB
/
Copy pathapp.plugin.js
File metadata and controls
688 lines (649 loc) · 26.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
// Expo config plugin for @comapeo/core-react-native.
//
// Writes the consumer's Sentry configuration into AndroidManifest
// meta-data and Info.plist keys at `expo prebuild`. Native readers
// (SentryConfig.{kt,swift}) pick up the values; the embedded
// backend picks them up via Node argv.
//
// `@sentry/react-native` is a non-optional peer dep of this module,
// so the SDK is always present in the consumer's app. Whether
// Sentry actually emits is gated at runtime: absence of the `sentry`
// argument here means "Sentry installed but inert" — `initSentry()`
// returns early because no DSN was baked into the manifest /
// Info.plist.
//
// When invoked without a `sentry` argument the plugin actively
// REMOVES every key it owns (handles `--no-clean` re-prebuilds
// where stale entries from a previous run would otherwise survive).
//
// `release` is omitted from the plugin args by default — the
// native readers fall back to versionName+versionCode (Android) /
// CFBundleShortVersionString+CFBundleVersion (iOS) so successive
// EAS builds get distinct release tags.
// `@expo/config-plugins` is CommonJS; pull named functions via
// default-import-then-destructure (this package is ESM).
import configPlugins from "@expo/config-plugins";
import { createRequire } from "node:module";
import { copyFile, mkdir, rm, writeFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import { dirname, isAbsolute, join, relative } from "node:path";
import { fileURLToPath } from "node:url";
const { withAndroidManifest } = configPlugins;
const { withMainApplication } = configPlugins;
const { withInfoPlist } = configPlugins;
const { withPodfile } = configPlugins;
const { withDangerousMod } = configPlugins;
const { withXcodeProject, IOSConfig } = configPlugins;
const require = createRequire(import.meta.url);
const {
mergeContents,
} = require("@expo/config-plugins/build/utils/generateCode");
// Manifest meta-data on the main `<application>` tag is shared
// across processes within the package.
const ANDROID_KEYS = {
dsn: "com.comapeo.core.sentry.dsn",
environment: "com.comapeo.core.sentry.environment",
release: "com.comapeo.core.sentry.release",
sampleRate: "com.comapeo.core.sentry.sampleRate",
tracesSampleRate: "com.comapeo.core.sentry.tracesSampleRate",
rpcArgsBytes: "com.comapeo.core.sentry.rpcArgsBytes",
diagnosticsEnabledDefault:
"com.comapeo.core.sentry.diagnosticsEnabledDefault",
applicationUsageDataDefault:
"com.comapeo.core.sentry.applicationUsageDataDefault",
debugDefault: "com.comapeo.core.sentry.debugDefault",
enableLogs: "com.comapeo.core.sentry.enableLogs",
// Identifies the @comapeo/core-react-native module build the FGS
// process is running. Set on the FGS-side `sentry-android` scope
// as the `comapeo.rn` tag and `comapeoBackend` context so FGS-
// emitted captures (incl. Node-forwarded events) carry the same
// module / backend-dep identification as RN-side events do via
// `initSentry`.
moduleVersion: "com.comapeo.core.module.version",
backendModulesJson: "com.comapeo.core.backend.modules",
};
// Online map style URL the consuming app sets via `defaultOnlineStyleUrl`.
// Read by native (NodeJSService.{kt,swift}) and forwarded to the backend as
// the 5th argv positional; absent → backend falls back to its built-in URL.
const ANDROID_MAP_STYLE_URL_KEY = "com.comapeo.core.map.defaultOnlineStyleUrl";
const IOS_MAP_STYLE_URL_KEY = "ComapeoCoreDefaultOnlineStyleUrl";
// Prefixed with `ComapeoCore` to avoid colliding with
// `@sentry/react-native`'s own keys (`SentryDsn`, etc.).
const IOS_KEYS = {
dsn: "ComapeoCoreSentryDsn",
environment: "ComapeoCoreSentryEnvironment",
release: "ComapeoCoreSentryRelease",
sampleRate: "ComapeoCoreSentrySampleRate",
tracesSampleRate: "ComapeoCoreSentryTracesSampleRate",
rpcArgsBytes: "ComapeoCoreSentryRpcArgsBytes",
diagnosticsEnabledDefault:
"ComapeoCoreSentryDiagnosticsEnabledDefault",
applicationUsageDataDefault:
"ComapeoCoreSentryApplicationUsageDataDefault",
debugDefault: "ComapeoCoreSentryDebugDefault",
enableLogs: "ComapeoCoreSentryEnableLogs",
};
function withComapeoCore(config, props) {
// Always pass through both mods, even when Sentry is "off",
// so a `--no-clean` re-prebuild after disabling Sentry strips
// stale entries from the previous run rather than shipping
// the old DSN.
const sentry = props?.sentry ? normalizeSentryProps(props.sentry) : null;
const moduleIdent = sentry ? readModuleIdentification() : null;
config = withSentryAndroid(config, sentry, moduleIdent);
config = withSentryIos(config, sentry);
config = withSentryLibraryEvolution(config);
// iOS Debug builds: ship the backend sourcemaps next to the bundle so
// Node's `--enable-source-maps` (passed by NodeJSService under #if DEBUG)
// symbolicates backend errors in-process — no Sentry upload needed.
// Release builds skip the copy (the bundle's map stays out of the IPA).
// Android handles the debug case via its `src/debug/` asset tree instead.
config = withDebugSourcemapsIos(config);
// Optional default project config (presets/categories) supplied by the
// consuming app. The module no longer ships @comapeo/default-categories;
// when this prop is absent, new projects get no default config.
config = withDefaultConfigAndroid(config, props?.defaultConfig);
config = withDefaultConfigIos(config, props?.defaultConfig);
// Optional online map style URL. Absent → the backend uses its built-in
// default. Always passed through both mods so a `--no-clean` re-prebuild
// after removing the prop strips the stale value.
config = withDefaultOnlineStyleUrlAndroid(config, props?.defaultOnlineStyleUrl);
config = withDefaultOnlineStyleUrlIos(config, props?.defaultOnlineStyleUrl);
// The embedded map server serves tiles over cleartext HTTP on
// loopback; release builds block cleartext by default. Permit it
// for localhost only, on both platforms.
config = withMapServerCleartextAndroid(config);
config = withMapServerCleartextIos(config);
// The embedded backend connects directly to peers on the local subnet;
// iOS gates that behind the Local Network prompt, so ship a usage
// description (overridable via `localNetworkPermission`). iOS only.
config = withLocalNetworkPermissionIos(config, props?.localNetworkPermission);
// Skip React Native init in the headless `:ComapeoCore` backend process — running
// RN there risks a cold-start ANR (see com.comapeo.core.ComapeoProcessGuard).
config = withComapeoCoreProcessGuard(config);
return config;
}
// Inject the process guard at the top of the host app's MainApplication.onCreate.
// Rationale and detection live in com.comapeo.core.ComapeoProcessGuard; this only
// splices in the call.
const PROCESS_GUARD_MARKER = "comapeo-core-process-guard";
const PROCESS_GUARD_ANCHOR = "super.onCreate()";
const PROCESS_GUARD_KOTLIN = `
// ${PROCESS_GUARD_MARKER}: skip React Native init in the :ComapeoCore backend
// process — running it there risks a cold-start ANR. See ComapeoProcessGuard.
if (com.comapeo.core.ComapeoProcessGuard.isBackendProcess(this)) {
return
}`;
function withComapeoCoreProcessGuard(config) {
return withMainApplication(config, (cfg) => {
const { language, contents } = cfg.modResults;
if (contents.includes(PROCESS_GUARD_MARKER)) return cfg;
// Hard-fail rather than warn-and-skip: a skipped guard ships the cold-start ANR
// risk to production, which a missed warning wouldn't catch.
if (language !== "kt") {
throw new Error(
`@comapeo/core-react-native plugin: MainApplication is ${language}, not Kotlin. ` +
"The :ComapeoCore process guard only supports a Kotlin MainApplication; " +
"a Java MainApplication would run full React Native init in the headless " +
"backend process, risking a cold-start ANR. Failing prebuild rather than shipping that.",
);
}
const idx = contents.indexOf(PROCESS_GUARD_ANCHOR);
if (idx === -1) {
throw new Error(
`@comapeo/core-react-native plugin: could not find \`${PROCESS_GUARD_ANCHOR}\` ` +
"in MainApplication.kt to anchor the :ComapeoCore process guard. The generated " +
"MainApplication template likely changed and the plugin must be updated. Failing " +
"prebuild rather than silently shipping the cold-start ANR risk in the backend process.",
);
}
const at = idx + PROCESS_GUARD_ANCHOR.length;
cfg.modResults.contents =
contents.slice(0, at) + PROCESS_GUARD_KOTLIN + contents.slice(at);
return cfg;
});
}
// Scoped to loopback so the rest of the app keeps the secure default
// (no cleartext to the public internet).
const ANDROID_NETWORK_SECURITY_CONFIG_RESOURCE =
"comapeo_core_network_security_config";
const ANDROID_NETWORK_SECURITY_CONFIG_XML = `<?xml version="1.0" encoding="utf-8"?>
<!-- Generated by @comapeo/core-react-native. The embedded map server
serves tiles over cleartext HTTP on loopback; permit cleartext for
localhost only so the rest of the app keeps the secure default. -->
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="false">127.0.0.1</domain>
<domain includeSubdomains="false">localhost</domain>
</domain-config>
</network-security-config>
`;
function withMapServerCleartextAndroid(config) {
config = withDangerousMod(config, [
"android",
async (cfg) => {
const resXmlDir = join(
cfg.modRequest.platformProjectRoot,
"app/src/main/res/xml",
);
await mkdir(resXmlDir, { recursive: true });
await writeFile(
join(resXmlDir, `${ANDROID_NETWORK_SECURITY_CONFIG_RESOURCE}.xml`),
ANDROID_NETWORK_SECURITY_CONFIG_XML,
);
return cfg;
},
]);
return withAndroidManifest(config, (cfg) => {
const application = cfg.modResults.manifest.application?.[0];
if (!application) {
throw new Error(
"@comapeo/core-react-native plugin: AndroidManifest.xml has no <application> element",
);
}
application.$["android:networkSecurityConfig"] =
`@xml/${ANDROID_NETWORK_SECURITY_CONFIG_RESOURCE}`;
return cfg;
});
}
// `NSAllowsLocalNetworking` lifts ATS for loopback/.local hosts only,
// leaving ATS enforced for the public internet.
function withMapServerCleartextIos(config) {
return withInfoPlist(config, (cfg) => {
const ats = cfg.modResults.NSAppTransportSecurity || {};
ats.NSAllowsLocalNetworking = true;
cfg.modResults.NSAppTransportSecurity = ats;
return cfg;
});
}
const IOS_LOCAL_NETWORK_USAGE_KEY = "NSLocalNetworkUsageDescription";
const DEFAULT_LOCAL_NETWORK_USAGE_DESCRIPTION =
"Connects to nearby devices on your local network to sync with other CoMapeo peers.";
// iOS Local Network privacy is enforced at the socket layer, not the HTTP
// stack — so unlike ATS/cleartext it reaches the Node thread, where the
// embedded backend opens direct connections to peers on the local subnet
// (hyperswarm). Without a usage description iOS denies those connections
// with no prompt. The module owns this key; customise the wording via the
// `localNetworkPermission` prop rather than setting the Info.plist key
// separately. mDNS/Bonjour discovery and the matching `NSBonjourServices`
// stay the app's concern — the module neither browses nor advertises.
function withLocalNetworkPermissionIos(config, usageDescription) {
return withInfoPlist(config, (cfg) => {
cfg.modResults[IOS_LOCAL_NETWORK_USAGE_KEY] =
typeof usageDescription === "string"
? usageDescription
: DEFAULT_LOCAL_NETWORK_USAGE_DESCRIPTION;
return cfg;
});
}
// Fixed on-device filename the native readers look for: Android extracts
// it from `assets/nodejs-project/` into the node project dir; iOS resolves
// it as a bundle resource. Native passes its resolved path to the backend
// as the `defaultConfigPath` argv positional.
const DEFAULT_CONFIG_FILENAME = "comapeo-default-config.comapeocat";
// Resolve the consumer's `defaultConfig` path (absolute, or relative to
// the app project root) and assert it exists — a typo'd path should fail
// prebuild loudly rather than silently ship no config.
function resolveDefaultConfigSource(modRequest, defaultConfig) {
if (typeof defaultConfig !== "string" || defaultConfig.length === 0) {
throw new Error(
"@comapeo/core-react-native plugin: `defaultConfig` must be a path to a .comapeocat file",
);
}
const abs = isAbsolute(defaultConfig)
? defaultConfig
: join(modRequest.projectRoot, defaultConfig);
if (!existsSync(abs)) {
throw new Error(
`@comapeo/core-react-native plugin: \`defaultConfig\` file not found: ${abs}`,
);
}
return abs;
}
// Android: merge the config into the app's `assets/nodejs-project/` so it
// rides the existing asset→filesDir extraction the backend bundle already
// uses (assets have no fs path; the file needs one at runtime).
function withDefaultConfigAndroid(config, defaultConfig) {
return withDangerousMod(config, [
"android",
async (cfg) => {
const destDir = join(
cfg.modRequest.platformProjectRoot,
"app/src/main/assets/nodejs-project",
);
const dest = join(destDir, DEFAULT_CONFIG_FILENAME);
if (defaultConfig == null) {
// --no-clean re-prebuild after removing the prop: drop a stale copy.
await rm(dest, { force: true });
return cfg;
}
const src = resolveDefaultConfigSource(cfg.modRequest, defaultConfig);
await mkdir(destDir, { recursive: true });
await copyFile(src, dest);
return cfg;
},
]);
}
// iOS: copy the file into the app target's project directory and register
// it in Copy Bundle Resources so `Bundle.main` resolves it at runtime.
function withDefaultConfigIos(config, defaultConfig) {
config = withDangerousMod(config, [
"ios",
async (cfg) => {
const dest = join(
cfg.modRequest.platformProjectRoot,
cfg.modRequest.projectName,
DEFAULT_CONFIG_FILENAME,
);
if (defaultConfig == null) {
await rm(dest, { force: true });
return cfg;
}
const src = resolveDefaultConfigSource(cfg.modRequest, defaultConfig);
await copyFile(src, dest);
return cfg;
},
]);
// Registration is add-only. `addResourceFileToGroup` is idempotent
// (skips a file already in the group), so repeat prebuilds don't
// duplicate the entry. We don't strip the entry when `defaultConfig`
// is removed: `xcode`'s `removeResourceFile` throws on RN/Expo projects
// (it assumes a `Resources` PBXGroup that doesn't exist here), and
// hand-removing pbxproj sections is version-fragile. Removing the prop
// therefore requires a clean prebuild (`expo prebuild --clean`) to drop
// the stale reference; otherwise the build looks for a missing file.
if (defaultConfig == null) return config;
return withXcodeProject(config, (cfg) => {
IOSConfig.XcodeUtils.addResourceFileToGroup({
filepath: `${cfg.modRequest.projectName}/${DEFAULT_CONFIG_FILENAME}`,
groupName: cfg.modRequest.projectName,
project: cfg.modResults,
isBuildFile: true,
verbose: false,
});
return cfg;
});
}
// Validate the consumer's `defaultOnlineStyleUrl` — a malformed URL should
// fail prebuild loudly rather than silently ship a broken style. `null`
// (prop absent) is allowed: native then forwards an empty slot and the
// backend uses its built-in default.
function normalizeStyleUrl(styleUrl) {
if (styleUrl == null) return undefined;
if (typeof styleUrl !== "string" || styleUrl.length === 0) {
throw new Error(
"@comapeo/core-react-native plugin: `defaultOnlineStyleUrl` must be a non-empty URL string",
);
}
let parsed;
try {
parsed = new globalThis.URL(styleUrl);
} catch {
throw new Error(
`@comapeo/core-react-native plugin: \`defaultOnlineStyleUrl\` is not a valid URL: ${styleUrl}`,
);
}
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
throw new Error(
`@comapeo/core-react-native plugin: \`defaultOnlineStyleUrl\` must be an http(s) URL: ${styleUrl}`,
);
}
return styleUrl;
}
function withDefaultOnlineStyleUrlAndroid(config, styleUrl) {
const url = normalizeStyleUrl(styleUrl);
return withAndroidManifest(config, (cfg) => {
const application = cfg.modResults.manifest.application?.[0];
if (!application) {
throw new Error(
"@comapeo/core-react-native plugin: AndroidManifest.xml has no <application> element",
);
}
application["meta-data"] = application["meta-data"] || [];
syncAndroidMetaData(application, ANDROID_MAP_STYLE_URL_KEY, url);
return cfg;
});
}
function withDefaultOnlineStyleUrlIos(config, styleUrl) {
const url = normalizeStyleUrl(styleUrl);
return withInfoPlist(config, (cfg) => {
setOrDelete(cfg.modResults, IOS_MAP_STYLE_URL_KEY, url);
return cfg;
});
}
// getsentry/sentry-cocoa#7950: Xcode 26's Swift compiler drops
// `SentrySDK.startTransaction` (and other Swift-only APIs) from the
// Sentry module unless the pod builds with library evolution.
// `SentryNativeBridge.swift` calls that API, so every consumer needs
// this. Inserted INSIDE the existing `post_install` block because
// CocoaPods allows only one `post_install` hook per Podfile.
const SENTRY_LIBRARY_EVOLUTION_HOOK = `\
installer.pods_project.targets.each do |target|
if target.name.start_with?('Sentry')
target.build_configurations.each do |build_configuration|
build_configuration.build_settings['BUILD_LIBRARY_FOR_DISTRIBUTION'] = 'YES'
end
end
end`;
function withSentryLibraryEvolution(config) {
return withPodfile(config, (cfg) => {
cfg.modResults.contents = mergeContents({
tag: "comapeo-core-sentry-library-evolution",
src: cfg.modResults.contents,
newSrc: SENTRY_LIBRARY_EVOLUTION_HOOK,
anchor: /post_install do \|installer\|/,
offset: 1,
comment: "#",
}).contents;
return cfg;
});
}
// Adds the Debug-only `ComapeoCoreSourcemaps` companion pod to the consumer's
// Podfile. `:configurations => ['Debug']` makes CocoaPods copy its resources
// (the backend `.map` files, shaped as a `nodejs-project` dir) only in Debug
// builds — they merge next to the bundle in the `.app`, where Node resolves
// them via `--enable-source-maps` (passed by NodeJSService under #if DEBUG).
// Release builds never include the pod, so the IPA stays lean.
//
// The pod is added explicitly here, never autolinked — see
// `ComapeoCoreSourcemaps.podspec` and the pinned `apple.podspecPath` in
// `expo-module.config.json`. `:path` is computed per-consumer so it survives
// monorepo node_modules hoisting.
function withDebugSourcemapsIos(config) {
return withPodfile(config, (cfg) => {
const podDir = join(dirname(fileURLToPath(import.meta.url)), "ios");
const relPodPath =
relative(cfg.modRequest.platformProjectRoot, podDir) || ".";
const podLine =
` pod 'ComapeoCoreSourcemaps', :path => '${relPodPath}', ` +
`:configurations => ['Debug']`;
cfg.modResults.contents = mergeContents({
tag: "comapeo-core-debug-sourcemaps",
src: cfg.modResults.contents,
newSrc: podLine,
anchor: /use_expo_modules!/,
offset: 1,
comment: "#",
}).contents;
return cfg;
});
}
/**
* Module version label + bundled-backend dep map — the same values
* `src/version.ts` exposes to the RN-side `initSentry`. Used only on
* Android: iOS is single-process and the RN-side global scope already
* covers FGS-equivalent captures. Best-effort; failures fall back to
* just the package.json `version` so a half-built dev checkout still
* prebuilds.
*/
function readModuleIdentification() {
let moduleVersion;
try {
moduleVersion = require("./build/version.js").COMAPEO_MODULE_VERSION_LABEL;
} catch {
try {
moduleVersion = require("./package.json").version;
} catch {
return null;
}
}
let backendModules = {};
try {
const backendPkg = require("./backend/package.json");
backendModules = Object.fromEntries(
Object.entries(backendPkg.dependencies ?? {}).filter(
([name]) =>
name.startsWith("@comapeo/") || name === "@mapeo/crypto",
),
);
} catch {
// Backend package.json missing — ship the version label without
// the dep map. Better than failing prebuild.
}
return {
moduleVersion,
backendModulesJson: JSON.stringify(backendModules),
};
}
function normalizeSentryProps(sentry) {
if (typeof sentry !== "object" || sentry === null) {
throw new Error(
"@comapeo/core-react-native plugin: `sentry` must be an object",
);
}
if (!sentry.dsn || typeof sentry.dsn !== "string") {
throw new Error(
"@comapeo/core-react-native plugin: `sentry.dsn` is required when sentry is configured. " +
"Source it from EAS env vars in app.config.js, e.g. process.env.SENTRY_DSN.",
);
}
if (!sentry.environment || typeof sentry.environment !== "string") {
throw new Error(
"@comapeo/core-react-native plugin: `sentry.environment` is required when sentry is configured. " +
"Sourced per build profile via EAS env vars.",
);
}
// Coerce numbers/booleans to strings — manifest meta-data and
// Info.plist values are string-typed in the native readers.
const normalized = {
dsn: sentry.dsn,
environment: sentry.environment,
};
if (sentry.release !== undefined) normalized.release = String(sentry.release);
if (sentry.sampleRate !== undefined) {
normalized.sampleRate = String(sentry.sampleRate);
}
if (sentry.tracesSampleRate !== undefined) {
normalized.tracesSampleRate = String(sentry.tracesSampleRate);
}
if (sentry.rpcArgsBytes !== undefined) {
normalized.rpcArgsBytes = String(sentry.rpcArgsBytes);
}
if (sentry.diagnosticsEnabledDefault !== undefined) {
normalized.diagnosticsEnabledDefault = sentry.diagnosticsEnabledDefault
? "true"
: "false";
}
if (sentry.applicationUsageDataDefault !== undefined) {
normalized.applicationUsageDataDefault = sentry.applicationUsageDataDefault
? "true"
: "false";
}
if (sentry.debugDefault !== undefined) {
normalized.debugDefault = sentry.debugDefault ? "true" : "false";
}
if (sentry.enableLogs !== undefined) {
normalized.enableLogs = sentry.enableLogs ? "true" : "false";
}
return normalized;
}
function withSentryAndroid(config, sentry, moduleIdent) {
return withAndroidManifest(config, (cfg) => {
const manifest = cfg.modResults;
const application = manifest.manifest.application?.[0];
if (!application) {
throw new Error(
"@comapeo/core-react-native plugin: AndroidManifest.xml has no <application> element",
);
}
application["meta-data"] = application["meta-data"] || [];
if (sentry == null) {
// Off: strip only the keys this plugin owns. Other plugins'
// keys (e.g. `io.sentry.dsn` from @sentry/react-native) stay.
for (const name of Object.values(ANDROID_KEYS)) {
removeAndroidMetaData(application, name);
}
return cfg;
}
upsertAndroidMetaData(application, ANDROID_KEYS.dsn, sentry.dsn);
upsertAndroidMetaData(
application,
ANDROID_KEYS.environment,
sentry.environment,
);
syncAndroidMetaData(application, ANDROID_KEYS.release, sentry.release);
syncAndroidMetaData(
application,
ANDROID_KEYS.sampleRate,
sentry.sampleRate,
);
syncAndroidMetaData(
application,
ANDROID_KEYS.tracesSampleRate,
sentry.tracesSampleRate,
);
syncAndroidMetaData(
application,
ANDROID_KEYS.rpcArgsBytes,
sentry.rpcArgsBytes,
);
syncAndroidMetaData(
application,
ANDROID_KEYS.diagnosticsEnabledDefault,
sentry.diagnosticsEnabledDefault,
);
syncAndroidMetaData(
application,
ANDROID_KEYS.applicationUsageDataDefault,
sentry.applicationUsageDataDefault,
);
syncAndroidMetaData(
application,
ANDROID_KEYS.debugDefault,
sentry.debugDefault,
);
syncAndroidMetaData(
application,
ANDROID_KEYS.enableLogs,
sentry.enableLogs,
);
syncAndroidMetaData(
application,
ANDROID_KEYS.moduleVersion,
moduleIdent?.moduleVersion,
);
syncAndroidMetaData(
application,
ANDROID_KEYS.backendModulesJson,
moduleIdent?.backendModulesJson,
);
return cfg;
});
}
function syncAndroidMetaData(application, name, value) {
if (value === undefined) {
removeAndroidMetaData(application, name);
} else {
upsertAndroidMetaData(application, name, value);
}
}
function upsertAndroidMetaData(application, name, value) {
const list = application["meta-data"];
const existing = list.find((m) => m.$?.["android:name"] === name);
if (existing) {
existing.$["android:value"] = value;
} else {
list.push({ $: { "android:name": name, "android:value": value } });
}
}
function removeAndroidMetaData(application, name) {
const list = application["meta-data"];
const idx = list.findIndex((m) => m.$?.["android:name"] === name);
if (idx !== -1) list.splice(idx, 1);
}
function withSentryIos(config, sentry) {
return withInfoPlist(config, (cfg) => {
const plist = cfg.modResults;
if (sentry == null) {
for (const key of Object.values(IOS_KEYS)) delete plist[key];
return cfg;
}
plist[IOS_KEYS.dsn] = sentry.dsn;
plist[IOS_KEYS.environment] = sentry.environment;
setOrDelete(plist, IOS_KEYS.release, sentry.release);
setOrDelete(plist, IOS_KEYS.sampleRate, sentry.sampleRate);
setOrDelete(plist, IOS_KEYS.tracesSampleRate, sentry.tracesSampleRate);
setOrDelete(plist, IOS_KEYS.rpcArgsBytes, sentry.rpcArgsBytes);
setOrDelete(
plist,
IOS_KEYS.diagnosticsEnabledDefault,
sentry.diagnosticsEnabledDefault,
);
setOrDelete(
plist,
IOS_KEYS.applicationUsageDataDefault,
sentry.applicationUsageDataDefault,
);
setOrDelete(plist, IOS_KEYS.debugDefault, sentry.debugDefault);
setOrDelete(plist, IOS_KEYS.enableLogs, sentry.enableLogs);
return cfg;
});
}
function setOrDelete(plist, key, value) {
if (value === undefined) {
delete plist[key];
} else {
plist[key] = value;
}
}
export default withComapeoCore;