-
Notifications
You must be signed in to change notification settings - Fork 453
Expand file tree
/
Copy pathapp.plugin.js
More file actions
715 lines (618 loc) · 26.2 KB
/
app.plugin.js
File metadata and controls
715 lines (618 loc) · 26.2 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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
/**
* Expo config plugin for @clerk/clerk-expo
* Automatically configures iOS and Android to work with Clerk native components
*
* When this plugin is used:
* 1. iOS is configured with Swift Package Manager dependency for clerk-ios
* 2. Android is configured with packaging exclusions for dependencies
*
* Native modules are registered via react-native.config.js and standard
* React Native autolinking (RCTViewManager / ReactPackage).
*/
const {
withXcodeProject,
withDangerousMod,
withInfoPlist,
withAppBuildGradle,
withEntitlementsPlist,
} = require('@expo/config-plugins');
const path = require('path');
const fs = require('fs');
const CLERK_IOS_REPO = 'https://github.com/clerk/clerk-ios.git';
const CLERK_IOS_VERSION = '1.0.0';
const CLERK_MIN_IOS_VERSION = '17.0';
const withClerkIOS = config => {
console.log('✅ Clerk iOS plugin loaded');
// IMPORTANT: Set iOS deployment target in Podfile.properties.json BEFORE pod install
// This ensures ClerkExpo pod gets installed (it requires iOS 17.0)
config = withDangerousMod(config, [
'ios',
async config => {
const podfilePropertiesPath = path.join(config.modRequest.platformProjectRoot, 'Podfile.properties.json');
let properties = {};
if (fs.existsSync(podfilePropertiesPath)) {
try {
properties = JSON.parse(fs.readFileSync(podfilePropertiesPath, 'utf8'));
} catch {
// If file exists but is invalid JSON, start fresh
}
}
// Set the iOS deployment target
if (
!properties['ios.deploymentTarget'] ||
parseFloat(properties['ios.deploymentTarget']) < parseFloat(CLERK_MIN_IOS_VERSION)
) {
properties['ios.deploymentTarget'] = CLERK_MIN_IOS_VERSION;
fs.writeFileSync(podfilePropertiesPath, JSON.stringify(properties, null, 2) + '\n');
console.log(`✅ Set ios.deploymentTarget to ${CLERK_MIN_IOS_VERSION} in Podfile.properties.json`);
}
return config;
},
]);
// First update the iOS deployment target to 17.0 (required by Clerk iOS SDK)
config = withXcodeProject(config, config => {
const xcodeProject = config.modResults;
try {
// Update deployment target in all build configurations
const buildConfigs = xcodeProject.hash.project.objects.XCBuildConfiguration || {};
for (const [uuid, buildConfig] of Object.entries(buildConfigs)) {
if (buildConfig && buildConfig.buildSettings) {
const currentTarget = buildConfig.buildSettings.IPHONEOS_DEPLOYMENT_TARGET;
if (currentTarget && parseFloat(currentTarget) < parseFloat(CLERK_MIN_IOS_VERSION)) {
buildConfig.buildSettings.IPHONEOS_DEPLOYMENT_TARGET = CLERK_MIN_IOS_VERSION;
}
}
}
console.log(`✅ Updated iOS deployment target to ${CLERK_MIN_IOS_VERSION}`);
} catch (error) {
console.error('❌ Error updating deployment target:', error.message);
}
return config;
});
// Then add the Swift Package dependency
config = withXcodeProject(config, config => {
const xcodeProject = config.modResults;
try {
// Get the main app target
const targets = xcodeProject.getFirstTarget();
if (!targets) {
console.warn('⚠️ Could not find main target in Xcode project');
return config;
}
const targetUuid = targets.uuid;
const targetName = targets.name;
// Add Swift Package reference to the project
const packageUuid = xcodeProject.generateUuid();
const packageName = 'clerk-ios';
// Add package reference to XCRemoteSwiftPackageReference section
if (!xcodeProject.hash.project.objects.XCRemoteSwiftPackageReference) {
xcodeProject.hash.project.objects.XCRemoteSwiftPackageReference = {};
}
xcodeProject.hash.project.objects.XCRemoteSwiftPackageReference[packageUuid] = {
isa: 'XCRemoteSwiftPackageReference',
repositoryURL: CLERK_IOS_REPO,
requirement: {
kind: 'exactVersion',
version: CLERK_IOS_VERSION,
},
};
// Add package product dependencies (ClerkKit + ClerkKitUI)
const productUuidKit = xcodeProject.generateUuid();
const productUuidKitUI = xcodeProject.generateUuid();
if (!xcodeProject.hash.project.objects.XCSwiftPackageProductDependency) {
xcodeProject.hash.project.objects.XCSwiftPackageProductDependency = {};
}
xcodeProject.hash.project.objects.XCSwiftPackageProductDependency[productUuidKit] = {
isa: 'XCSwiftPackageProductDependency',
package: packageUuid,
productName: 'ClerkKit',
};
xcodeProject.hash.project.objects.XCSwiftPackageProductDependency[productUuidKitUI] = {
isa: 'XCSwiftPackageProductDependency',
package: packageUuid,
productName: 'ClerkKitUI',
};
// Add package to project's package references
const projectSection = xcodeProject.hash.project.objects.PBXProject;
const projectUuid = Object.keys(projectSection)[0];
const project = projectSection[projectUuid];
if (!project.packageReferences) {
project.packageReferences = [];
}
// Check if package is already added
const alreadyAdded = project.packageReferences.some(ref => {
const refObj = xcodeProject.hash.project.objects.XCRemoteSwiftPackageReference[ref.value];
return refObj && refObj.repositoryURL === CLERK_IOS_REPO;
});
if (!alreadyAdded) {
project.packageReferences.push({
value: packageUuid,
comment: packageName,
});
}
// Add package products to main app target
const nativeTarget = xcodeProject.hash.project.objects.PBXNativeTarget[targetUuid];
if (!nativeTarget.packageProductDependencies) {
nativeTarget.packageProductDependencies = [];
}
const kitAlreadyAdded = nativeTarget.packageProductDependencies.some(dep => dep.value === productUuidKit);
if (!kitAlreadyAdded) {
nativeTarget.packageProductDependencies.push({
value: productUuidKit,
comment: 'ClerkKit',
});
}
const kitUIAlreadyAdded = nativeTarget.packageProductDependencies.some(dep => dep.value === productUuidKitUI);
if (!kitUIAlreadyAdded) {
nativeTarget.packageProductDependencies.push({
value: productUuidKitUI,
comment: 'ClerkKitUI',
});
}
// Also add packages to ClerkExpo pod target if it exists
const allTargets = xcodeProject.hash.project.objects.PBXNativeTarget;
for (const [uuid, target] of Object.entries(allTargets)) {
if (target && target.name === 'ClerkExpo') {
if (!target.packageProductDependencies) {
target.packageProductDependencies = [];
}
const podKitAdded = target.packageProductDependencies.some(dep => dep.value === productUuidKit);
if (!podKitAdded) {
target.packageProductDependencies.push({
value: productUuidKit,
comment: 'ClerkKit',
});
}
const podKitUIAdded = target.packageProductDependencies.some(dep => dep.value === productUuidKitUI);
if (!podKitUIAdded) {
target.packageProductDependencies.push({
value: productUuidKitUI,
comment: 'ClerkKitUI',
});
}
console.log(`✅ Added ClerkKit and ClerkKitUI packages to ClerkExpo pod target`);
}
}
console.log(`✅ Added clerk-ios Swift package dependency (${CLERK_IOS_VERSION})`);
} catch (error) {
console.error('❌ Error adding clerk-ios package:', error.message);
}
return config;
});
// Inject ClerkViewFactory.register() call into AppDelegate.swift
config = withDangerousMod(config, [
'ios',
async config => {
const platformProjectRoot = config.modRequest.platformProjectRoot;
const projectName = config.modRequest.projectName;
const appDelegatePath = path.join(platformProjectRoot, projectName, 'AppDelegate.swift');
if (fs.existsSync(appDelegatePath)) {
let contents = fs.readFileSync(appDelegatePath, 'utf8');
// Check if already added
if (!contents.includes('ClerkViewFactory.register()')) {
// Find the didFinishLaunchingWithOptions method and add the registration call
// Look for the return statement in didFinishLaunching
const pattern = /(func application\s*\([^)]*didFinishLaunchingWithOptions[^)]*\)[^{]*\{)/;
const match = contents.match(pattern);
if (match) {
// Insert after the opening brace of didFinishLaunching
const insertPoint = match.index + match[0].length;
const registrationCode = '\n // Register Clerk native views\n ClerkViewFactory.register()\n';
contents = contents.slice(0, insertPoint) + registrationCode + contents.slice(insertPoint);
fs.writeFileSync(appDelegatePath, contents);
console.log('✅ Added ClerkViewFactory.register() to AppDelegate.swift');
} else {
console.warn('⚠️ Could not find didFinishLaunchingWithOptions in AppDelegate.swift');
}
}
}
return config;
},
]);
// Then inject ClerkViewFactory.swift into the app target
// This is required because the file uses `import ClerkKit` which is only available
// via SPM in the app target (CocoaPods targets can't see SPM packages)
config = withXcodeProject(config, config => {
try {
const platformProjectRoot = config.modRequest.platformProjectRoot;
const projectName = config.modRequest.projectName;
const iosProjectPath = path.join(platformProjectRoot, projectName);
// Find the ClerkViewFactory.swift source file using Node's module resolution,
// which handles arbitrary nesting depths in pnpm/yarn/npm workspaces.
let sourceFile;
try {
const packageRoot = path.dirname(require.resolve('@clerk/expo/package.json'));
sourceFile = path.join(packageRoot, 'ios', 'ClerkViewFactory.swift');
} catch {
sourceFile = null;
}
if (sourceFile && fs.existsSync(sourceFile)) {
// ALWAYS copy the file to ensure we have the latest version
const targetFile = path.join(iosProjectPath, 'ClerkViewFactory.swift');
fs.copyFileSync(sourceFile, targetFile);
console.log('✅ Copied ClerkViewFactory.swift to app target');
// Add the file to the Xcode project manually
const xcodeProject = config.modResults;
const relativePath = `${projectName}/ClerkViewFactory.swift`;
const fileName = 'ClerkViewFactory.swift';
try {
// Get the main target
const target = xcodeProject.getFirstTarget();
if (!target || !target.uuid) {
console.warn('⚠️ Could not find target UUID, file copied but not added to project');
return config;
}
const targetUuid = target.uuid;
// Check if file is already in the Xcode project references
const fileReferences = xcodeProject.hash.project.objects.PBXFileReference || {};
const alreadyExists = Object.values(fileReferences).some(ref => ref && ref.path === fileName);
if (alreadyExists) {
// File is already in project, but we still copied the latest version
console.log('✅ ClerkViewFactory.swift updated in app target');
return config;
}
// 1. Create PBXFileReference
const fileRefUuid = xcodeProject.generateUuid();
if (!xcodeProject.hash.project.objects.PBXFileReference) {
xcodeProject.hash.project.objects.PBXFileReference = {};
}
xcodeProject.hash.project.objects.PBXFileReference[fileRefUuid] = {
isa: 'PBXFileReference',
lastKnownFileType: 'sourcecode.swift',
name: fileName,
path: relativePath, // Use full relative path (projectName/ClerkViewFactory.swift)
sourceTree: '"<group>"',
};
// 2. Create PBXBuildFile
const buildFileUuid = xcodeProject.generateUuid();
if (!xcodeProject.hash.project.objects.PBXBuildFile) {
xcodeProject.hash.project.objects.PBXBuildFile = {};
}
xcodeProject.hash.project.objects.PBXBuildFile[buildFileUuid] = {
isa: 'PBXBuildFile',
fileRef: fileRefUuid,
fileRef_comment: fileName,
};
// 3. Add to PBXSourcesBuildPhase
const buildPhases = xcodeProject.hash.project.objects.PBXSourcesBuildPhase || {};
let sourcesPhaseUuid = null;
// Find the sources build phase for the main target
const nativeTarget = xcodeProject.hash.project.objects.PBXNativeTarget[targetUuid];
if (nativeTarget && nativeTarget.buildPhases) {
for (const phase of nativeTarget.buildPhases) {
if (buildPhases[phase.value] && buildPhases[phase.value].isa === 'PBXSourcesBuildPhase') {
sourcesPhaseUuid = phase.value;
break;
}
}
}
if (sourcesPhaseUuid && buildPhases[sourcesPhaseUuid]) {
if (!buildPhases[sourcesPhaseUuid].files) {
buildPhases[sourcesPhaseUuid].files = [];
}
buildPhases[sourcesPhaseUuid].files.push({
value: buildFileUuid,
comment: fileName,
});
} else {
console.warn('⚠️ Could not find PBXSourcesBuildPhase for target');
}
// 4. Add to PBXGroup (main group for the project)
const groups = xcodeProject.hash.project.objects.PBXGroup || {};
let mainGroupUuid = null;
// Find the group with the same name as the project
for (const [uuid, group] of Object.entries(groups)) {
if (group && group.name === projectName) {
mainGroupUuid = uuid;
break;
}
}
if (mainGroupUuid && groups[mainGroupUuid]) {
if (!groups[mainGroupUuid].children) {
groups[mainGroupUuid].children = [];
}
// Add file reference to the group
groups[mainGroupUuid].children.push({
value: fileRefUuid,
comment: fileName,
});
} else {
console.warn('⚠️ Could not find main PBXGroup for project');
}
console.log('✅ Added ClerkViewFactory.swift to Xcode project');
} catch (addError) {
console.error('❌ Error adding file to Xcode project:', addError.message);
console.error(addError.stack);
}
} else {
console.warn('⚠️ ClerkViewFactory.swift not found, skipping injection');
}
} catch (error) {
console.error('❌ Error injecting ClerkViewFactory.swift:', error.message);
}
return config;
});
// Inject SPM package resolution into Podfile post_install hook
// This runs synchronously during pod install, ensuring packages are resolved before prebuild completes
config = withDangerousMod(config, [
'ios',
async config => {
const platformProjectRoot = config.modRequest.platformProjectRoot;
const projectName = config.modRequest.projectName;
const podfilePath = path.join(platformProjectRoot, 'Podfile');
if (fs.existsSync(podfilePath)) {
let podfileContents = fs.readFileSync(podfilePath, 'utf8');
// Check if we've already added our resolution code
if (!podfileContents.includes('# Clerk: Resolve SPM packages')) {
// Code to inject into existing post_install block
// Note: We run this AFTER react_native_post_install to ensure the workspace is fully written
const spmResolutionCode = `
# Clerk: Resolve SPM packages synchronously during pod install
# This ensures packages are downloaded before the user opens Xcode
# We wait until the end of post_install to ensure workspace is fully written
at_exit do
workspace_path = File.join(__dir__, '${projectName}.xcworkspace')
if File.exist?(workspace_path)
puts ""
puts "📦 [Clerk] Resolving Swift Package dependencies..."
puts " This may take a minute on first run..."
# Use backticks to capture output and check exit status
output = \`xcodebuild -resolvePackageDependencies -workspace "#{workspace_path}" -scheme "${projectName}" 2>&1\`
if $?.success?
puts "✅ [Clerk] Swift Package dependencies resolved successfully"
else
puts "⚠️ [Clerk] SPM resolution output:"
puts output.lines.last(10).join
end
puts ""
end
end
`;
// Insert our code at the beginning of the existing post_install block
if (podfileContents.includes('post_install do |installer|')) {
podfileContents = podfileContents.replace(
/post_install do \|installer\|/,
`post_install do |installer|${spmResolutionCode}`,
);
fs.writeFileSync(podfilePath, podfileContents);
console.log('✅ Added SPM resolution to Podfile post_install hook');
}
}
}
return config;
},
]);
return config;
};
/**
* Add packaging exclusions to Android app build.gradle to resolve
* duplicate META-INF file conflicts from clerk-android dependencies.
*/
const withClerkAndroid = config => {
console.log('✅ Clerk Android plugin loaded');
return withAppBuildGradle(config, modConfig => {
let buildGradle = modConfig.modResults.contents;
// --- META-INF exclusion ---
if (!buildGradle.includes('META-INF/versions/9/OSGI-INF/MANIFEST.MF')) {
// AGP 8+ uses `packaging` DSL, older versions use `packagingOptions`
const packagingMatch = buildGradle.match(/packaging\s*\{/) || buildGradle.match(/packagingOptions\s*\{/);
if (packagingMatch) {
const blockName = packagingMatch[0].trim().replace(/\s*\{$/, '');
const resourcesExclude = `${blockName} {
// Clerk Android SDK: exclude duplicate META-INF files
resources {
excludes += ['META-INF/versions/9/OSGI-INF/MANIFEST.MF']
}`;
buildGradle = buildGradle.replace(new RegExp(`${blockName}\\s*\\{`), resourcesExclude);
} else {
// No packaging block found; append one at the end of the android block
const androidBlockEnd = buildGradle.lastIndexOf('}');
if (androidBlockEnd !== -1) {
const packagingBlock = `\n packaging {\n resources {\n excludes += ['META-INF/versions/9/OSGI-INF/MANIFEST.MF']\n }\n }\n`;
buildGradle = buildGradle.slice(0, androidBlockEnd) + packagingBlock + buildGradle.slice(androidBlockEnd);
}
}
console.log('✅ Clerk Android packaging exclusions added');
}
// --- Kotlin metadata version check skip ---
if (!buildGradle.includes('-Xskip-metadata-version-check')) {
const kotlinOptionsMatch = buildGradle.match(/kotlinOptions\s*\{/);
if (kotlinOptionsMatch) {
buildGradle = buildGradle.replace(
/kotlinOptions\s*\{/,
`kotlinOptions {\n // Clerk: allow reading metadata from newer Kotlin versions\n freeCompilerArgs += ['-Xskip-metadata-version-check']`,
);
} else {
const androidMatch = buildGradle.match(/android\s*\{/);
if (androidMatch) {
buildGradle = buildGradle.replace(
/android\s*\{/,
`android {\n kotlinOptions {\n // Clerk: allow reading metadata from newer Kotlin versions\n freeCompilerArgs += ['-Xskip-metadata-version-check']\n }`,
);
}
}
console.log('✅ Clerk Android Kotlin metadata version check skip added');
}
modConfig.modResults.contents = buildGradle;
return modConfig;
});
};
/**
* Add Google Sign-In URL scheme to Info.plist (from main branch)
*/
const withClerkGoogleSignIn = config => {
const iosUrlScheme =
process.env.EXPO_PUBLIC_CLERK_GOOGLE_IOS_URL_SCHEME ||
(config.extra && config.extra.EXPO_PUBLIC_CLERK_GOOGLE_IOS_URL_SCHEME);
if (!iosUrlScheme) {
return config;
}
return withInfoPlist(config, modConfig => {
if (!Array.isArray(modConfig.modResults.CFBundleURLTypes)) {
modConfig.modResults.CFBundleURLTypes = [];
}
const schemeExists = modConfig.modResults.CFBundleURLTypes.some(urlType =>
urlType.CFBundleURLSchemes?.includes(iosUrlScheme),
);
if (!schemeExists) {
modConfig.modResults.CFBundleURLTypes.push({
CFBundleURLSchemes: [iosUrlScheme],
});
console.log(`✅ Added Google Sign-In URL scheme: ${iosUrlScheme}`);
}
return modConfig;
});
};
/**
* Combined Clerk Expo plugin
*
* When this plugin is configured in app.json/app.config.js:
* 1. iOS gets Swift Package Manager dependency for clerk-ios SDK
* 2. Android gets packaging exclusions for dependency conflicts
* 3. Google Sign-In URL scheme is configured (if env var is set)
*
* Native modules are registered via react-native.config.js and standard
* React Native autolinking (RCTViewManager / ReactPackage).
*/
/**
* Write ClerkKeychainService to Info.plist when keychainService is provided.
* This allows extension apps (watch, widget, app clip) to share the same
* keychain entry as the main app by using a custom service identifier.
*/
const withClerkKeychainService = (config, { keychainService } = {}) => {
if (!keychainService) {
return config;
}
return withInfoPlist(config, modConfig => {
modConfig.modResults.ClerkKeychainService = keychainService;
console.log(`✅ Set ClerkKeychainService in Info.plist: ${keychainService}`);
return modConfig;
});
};
/**
* Add Sign in with Apple entitlement to the iOS app.
* Required for the native Apple Sign In flow via ASAuthorizationController.
*/
const withClerkAppleSignIn = config => {
return withEntitlementsPlist(config, modConfig => {
if (!modConfig.modResults['com.apple.developer.applesignin']) {
modConfig.modResults['com.apple.developer.applesignin'] = ['Default'];
console.log('✅ Added Sign in with Apple entitlement');
}
return modConfig;
});
};
/**
* Apply a custom theme to Clerk native components (iOS + Android).
*
* Accepts a `theme` prop pointing to a JSON file with optional keys:
* - colors: { primary, background, input, danger, success, warning,
* foreground, mutedForeground, primaryForeground, inputForeground,
* neutral, border, ring, muted, shadow } (hex color strings)
* - darkColors: same keys as colors (for dark mode)
* - design: { fontFamily: string, borderRadius: number }
*
* iOS: Embeds the parsed JSON into Info.plist under key "ClerkTheme".
* When darkColors is present, removes UIUserInterfaceStyle to allow
* system dark mode.
* Android: Copies the JSON file to android/app/src/main/assets/clerk_theme.json.
*/
const VALID_COLOR_KEYS = [
'primary',
'background',
'input',
'danger',
'success',
'warning',
'foreground',
'mutedForeground',
'primaryForeground',
'inputForeground',
'neutral',
'border',
'ring',
'muted',
'shadow',
];
const HEX_COLOR_REGEX = /^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/;
function validateThemeJson(theme) {
const validateColors = (colors, label) => {
if (!colors || typeof colors !== 'object') return;
for (const [key, value] of Object.entries(colors)) {
if (!VALID_COLOR_KEYS.includes(key)) {
console.warn(`⚠️ Clerk theme: unknown color key "${key}" in ${label}, ignoring`);
continue;
}
if (typeof value !== 'string' || !HEX_COLOR_REGEX.test(value)) {
throw new Error(`Clerk theme: invalid hex color for ${label}.${key}: "${value}"`);
}
}
};
if (theme.colors) validateColors(theme.colors, 'colors');
if (theme.darkColors) validateColors(theme.darkColors, 'darkColors');
if (theme.design) {
if (theme.design.fontFamily != null && typeof theme.design.fontFamily !== 'string') {
throw new Error(`Clerk theme: design.fontFamily must be a string`);
}
if (theme.design.borderRadius != null && typeof theme.design.borderRadius !== 'number') {
throw new Error(`Clerk theme: design.borderRadius must be a number`);
}
}
}
const withClerkTheme = (config, props = {}) => {
const { theme } = props;
if (!theme) return config;
// Resolve the theme file path relative to the project root
const themePath = path.resolve(theme);
if (!fs.existsSync(themePath)) {
console.warn(`⚠️ Clerk theme file not found: ${themePath}, skipping theme`);
return config;
}
let themeJson;
try {
themeJson = JSON.parse(fs.readFileSync(themePath, 'utf8'));
validateThemeJson(themeJson);
} catch (e) {
throw new Error(`Clerk theme: failed to parse ${themePath}: ${e.message}`);
}
// iOS: Embed theme in Info.plist under "ClerkTheme"
config = withInfoPlist(config, modConfig => {
modConfig.modResults.ClerkTheme = themeJson;
console.log('✅ Embedded Clerk theme in Info.plist');
// When darkColors is provided, remove UIUserInterfaceStyle to allow
// the system to switch between light and dark mode automatically.
if (themeJson.darkColors) {
delete modConfig.modResults.UIUserInterfaceStyle;
console.log('✅ Removed UIUserInterfaceStyle to enable system dark mode');
}
return modConfig;
});
// Android: Copy theme JSON to assets
config = withDangerousMod(config, [
'android',
async config => {
const assetsDir = path.join(config.modRequest.platformProjectRoot, 'app', 'src', 'main', 'assets');
if (!fs.existsSync(assetsDir)) {
fs.mkdirSync(assetsDir, { recursive: true });
}
const destPath = path.join(assetsDir, 'clerk_theme.json');
fs.writeFileSync(destPath, JSON.stringify(themeJson, null, 2) + '\n');
console.log('✅ Copied Clerk theme to Android assets');
return config;
},
]);
return config;
};
const withClerkExpo = (config, props = {}) => {
const { appleSignIn = true } = props;
config = withClerkIOS(config);
if (appleSignIn !== false) {
config = withClerkAppleSignIn(config);
}
config = withClerkGoogleSignIn(config);
config = withClerkAndroid(config);
config = withClerkKeychainService(config, props);
config = withClerkTheme(config, props);
return config;
};
module.exports = withClerkExpo;