-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathwithMParticleAndroid.ts
More file actions
401 lines (350 loc) · 10.7 KB
/
Copy pathwithMParticleAndroid.ts
File metadata and controls
401 lines (350 loc) · 10.7 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
import {
ConfigPlugin,
withMainApplication,
withAppBuildGradle,
} from '@expo/config-plugins';
import { mergeContents } from '@expo/config-plugins/build/utils/generateCode';
import { MParticlePluginProps } from './withMParticle';
import { getCustomBaseUrl } from './customBaseUrl';
// Tag used for mergeContents to identify code blocks added by this plugin
const MPARTICLE_TAG = 'react-native-mparticle';
/**
* Get the mParticle log level string for Android
*/
function getAndroidLogLevel(
logLevel?: MParticlePluginProps['logLevel']
): string | null {
switch (logLevel) {
case 'none':
return 'MParticle.LogLevel.NONE';
case 'error':
return 'MParticle.LogLevel.ERROR';
case 'warning':
return 'MParticle.LogLevel.WARNING';
case 'debug':
return 'MParticle.LogLevel.DEBUG';
case 'verbose':
return 'MParticle.LogLevel.VERBOSE';
default:
return null;
}
}
/**
* Get the mParticle environment string for Android
*/
function getAndroidEnvironment(
environment?: MParticlePluginProps['environment']
): string | null {
switch (environment) {
case 'development':
return 'MParticle.Environment.Development';
case 'production':
return 'MParticle.Environment.Production';
case 'autoDetect':
return 'MParticle.Environment.AutoDetect';
default:
return null;
}
}
/**
* Generate mParticle initialization code for Kotlin MainApplication
*/
function generateKotlinInitCode(props: MParticlePluginProps): string {
const {
androidApiKey,
androidApiSecret,
logLevel,
environment,
useEmptyIdentifyRequest = true,
dataPlanId,
dataPlanVersion,
} = props;
const customBaseUrl = getCustomBaseUrl(props);
const lines: string[] = [
'// mParticle SDK initialization',
'val mParticleOptions = MParticleOptions.builder(this)',
` .credentials("${androidApiKey}", "${androidApiSecret}")`,
];
const androidLogLevel = getAndroidLogLevel(logLevel);
if (androidLogLevel) {
lines.push(` .logLevel(${androidLogLevel})`);
}
const androidEnvironment = getAndroidEnvironment(environment);
if (androidEnvironment) {
lines.push(` .environment(${androidEnvironment})`);
}
if (dataPlanId) {
const versionParam = dataPlanVersion ? `, ${dataPlanVersion}` : '';
lines.push(` .dataplan("${dataPlanId}"${versionParam})`);
}
if (customBaseUrl) {
lines.push(' .networkOptions(');
lines.push(' NetworkOptions.builder()');
lines.push(
` .setCustomBaseURL(${JSON.stringify(customBaseUrl)})`
);
lines.push(' .build()');
lines.push(' )');
}
if (useEmptyIdentifyRequest) {
lines.push(' .identify(IdentityApiRequest.withEmptyUser().build())');
}
lines.push(' .build()');
lines.push('MParticle.start(mParticleOptions)');
return lines.join('\n ');
}
/**
* Generate mParticle initialization code for Java MainApplication
*/
function generateJavaInitCode(props: MParticlePluginProps): string {
const {
androidApiKey,
androidApiSecret,
logLevel,
environment,
useEmptyIdentifyRequest = true,
dataPlanId,
dataPlanVersion,
} = props;
const customBaseUrl = getCustomBaseUrl(props);
const lines: string[] = [
'// mParticle SDK initialization',
'MParticleOptions.Builder optionsBuilder = MParticleOptions.builder(this)',
` .credentials("${androidApiKey}", "${androidApiSecret}")`,
];
const androidLogLevel = getAndroidLogLevel(logLevel);
if (androidLogLevel) {
lines.push(` .logLevel(${androidLogLevel})`);
}
const androidEnvironment = getAndroidEnvironment(environment);
if (androidEnvironment) {
lines.push(` .environment(${androidEnvironment})`);
}
if (dataPlanId) {
const versionParam = dataPlanVersion ? `, ${dataPlanVersion}` : '';
lines.push(` .dataplan("${dataPlanId}"${versionParam})`);
}
if (customBaseUrl) {
lines.push(' .networkOptions(');
lines.push(' NetworkOptions.builder()');
lines.push(
` .setCustomBaseURL(${JSON.stringify(customBaseUrl)})`
);
lines.push(' .build()');
lines.push(' )');
}
if (useEmptyIdentifyRequest) {
lines.push(' .identify(IdentityApiRequest.withEmptyUser().build())');
}
// Java needs semicolons
lines.push(';');
lines.push('MParticle.start(optionsBuilder.build());');
return lines.join('\n ');
}
/**
* Generate mParticle import statements for Kotlin
*/
function getKotlinImports(props: MParticlePluginProps): string {
const imports = [
'import com.mparticle.MParticle',
'import com.mparticle.MParticleOptions',
'import com.mparticle.identity.IdentityApiRequest',
];
if (getCustomBaseUrl(props)) {
imports.push('import com.mparticle.networking.NetworkOptions');
}
return imports.join('\n');
}
/**
* Generate mParticle import statements for Java
*/
function getJavaImports(props: MParticlePluginProps): string {
const imports = [
'import com.mparticle.MParticle;',
'import com.mparticle.MParticleOptions;',
'import com.mparticle.identity.IdentityApiRequest;',
];
if (getCustomBaseUrl(props)) {
imports.push('import com.mparticle.networking.NetworkOptions;');
}
return imports.join('\n');
}
/**
* Add mParticle configuration to MainApplication
* Handles both Kotlin and Java
*/
const withMParticleMainApplication: ConfigPlugin<MParticlePluginProps> = (
config,
props
) => {
return withMainApplication(config, config => {
const { contents, language } = config.modResults;
// Check if mParticle is already initialized
if (
contents.includes('MParticleOptions') ||
contents.includes('mParticleOptions')
) {
return config;
}
const isKotlin = language === 'kt';
if (isKotlin) {
config.modResults.contents = addMParticleToKotlinMainApplication(
contents,
props
);
} else if (language === 'java') {
config.modResults.contents = addMParticleToJavaMainApplication(
contents,
props
);
} else {
console.warn(
`[react-native-mparticle] Unsupported MainApplication language: ${language}. ` +
'mParticle initialization must be added manually.'
);
}
return config;
});
};
/**
* Add mParticle import and initialization to Kotlin MainApplication
*/
function addMParticleToKotlinMainApplication(
contents: string,
props: MParticlePluginProps
): string {
// Add import statements using mergeContents
const withImports = mergeContents({
src: contents,
newSrc: getKotlinImports(props),
anchor: /^package .+$/m,
offset: 1, // Add after package declaration
tag: `${MPARTICLE_TAG}-import`,
comment: '//',
});
// Generate initialization code
const initCode = generateKotlinInitCode(props);
// Find the right place to add initialization code
// Try ApplicationLifecycleDispatcher first (Expo pattern), then super.onCreate()
let result = withImports.contents;
if (
result.includes('ApplicationLifecycleDispatcher.onApplicationCreate(this)')
) {
const withInit = mergeContents({
src: result,
newSrc: `\n ${initCode}\n`,
anchor: /ApplicationLifecycleDispatcher\.onApplicationCreate\(this\)/,
offset: 1, // Add after the anchor
tag: `${MPARTICLE_TAG}-init`,
comment: '//',
});
result = withInit.contents;
} else if (result.includes('super.onCreate()')) {
const withInit = mergeContents({
src: result,
newSrc: `\n ${initCode}\n`,
anchor: /super\.onCreate\(\)/,
offset: 1, // Add after the anchor
tag: `${MPARTICLE_TAG}-init`,
comment: '//',
});
result = withInit.contents;
}
return result;
}
/**
* Add mParticle import and initialization to Java MainApplication
*/
function addMParticleToJavaMainApplication(
contents: string,
props: MParticlePluginProps
): string {
// Add import statements using mergeContents
const withImports = mergeContents({
src: contents,
newSrc: getJavaImports(props),
anchor: /^package .+;$/m,
offset: 1, // Add after package declaration
tag: `${MPARTICLE_TAG}-import`,
comment: '//',
});
// Generate initialization code
const initCode = generateJavaInitCode(props);
// Find the right place to add initialization code
let result = withImports.contents;
if (
result.includes('ApplicationLifecycleDispatcher.onApplicationCreate(this);')
) {
const withInit = mergeContents({
src: result,
newSrc: `\n ${initCode}\n`,
anchor: /ApplicationLifecycleDispatcher\.onApplicationCreate\(this\);/,
offset: 1, // Add after the anchor
tag: `${MPARTICLE_TAG}-init`,
comment: '//',
});
result = withInit.contents;
} else if (result.includes('super.onCreate();')) {
const withInit = mergeContents({
src: result,
newSrc: `\n ${initCode}\n`,
anchor: /super\.onCreate\(\);/,
offset: 1, // Add after the anchor
tag: `${MPARTICLE_TAG}-init`,
comment: '//',
});
result = withInit.contents;
}
return result;
}
/**
* Add kit dependencies to app/build.gradle
*/
const withMParticleAppBuildGradle: ConfigPlugin<MParticlePluginProps> = (
config,
props
) => {
return withAppBuildGradle(config, config => {
const { contents } = config.modResults;
if (!props.androidKits || props.androidKits.length === 0) {
return config;
}
// Check if kits are already added
const kitsAlreadyAdded = props.androidKits.every(kit =>
contents.includes(`com.mparticle:${kit}`)
);
if (kitsAlreadyAdded) {
return config;
}
// Generate kit dependency lines
// Bounded range matches the core SDK range in android/build.gradle so the
// kit and core stay paired on a 5.x line. An unbounded `+` would resolve
// to a pre-release (e.g. 6.0.0-rc.1) and transitively drag the core past
// the bridge's compiled-against API surface.
const kitDependencies = props.androidKits
.map(kit => ` implementation "com.mparticle:${kit}:[5.79.0, 6.0)"`)
.join('\n');
// Use mergeContents for idempotent injection
const withKits = mergeContents({
src: contents,
newSrc: `\n // mParticle kits\n${kitDependencies}`,
anchor: /dependencies\s*\{/,
offset: 1, // Add after the opening brace
tag: `${MPARTICLE_TAG}-kits`,
comment: '//',
});
config.modResults.contents = withKits.contents;
return config;
});
};
/**
* Apply all Android-specific mParticle configurations
*/
export const withMParticleAndroid: ConfigPlugin<MParticlePluginProps> = (
config,
props
) => {
config = withMParticleMainApplication(config, props);
config = withMParticleAppBuildGradle(config, props);
return config;
};