forked from microsoft/react-native-code-push
-
Notifications
You must be signed in to change notification settings - Fork 1
/
CodePush.js
765 lines (678 loc) · 29 KB
/
CodePush.js
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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
import { AcquisitionManager as Sdk } from "code-push/script/acquisition-sdk";
import { Alert } from "./AlertAdapter";
import requestFetchAdapter from "./request-fetch-adapter";
import { AppState, Platform } from "react-native";
import log from "./logging";
import hoistStatics from 'hoist-non-react-statics';
let NativeCodePush = require("react-native").NativeModules.CodePush;
const PackageMixins = require("./package-mixins")(NativeCodePush);
async function checkForUpdate(deploymentKey = null, handleBinaryVersionMismatchCallback = null) {
/*
* Before we ask the server if an update exists, we
* need to retrieve three pieces of information from the
* native side: deployment key, app version (e.g. 1.0.1)
* and the hash of the currently running update (if there is one).
* This allows the client to only receive updates which are targetted
* for their specific deployment and version and which are actually
* different from the CodePush update they have already installed.
*/
const nativeConfig = await getConfiguration();
/*
* If a deployment key was explicitly provided,
* then let's override the one we retrieved
* from the native-side of the app. This allows
* dynamically "redirecting" end-users at different
* deployments (e.g. an early access deployment for insiders).
*/
const config = deploymentKey ? { ...nativeConfig, ...{ deploymentKey } } : nativeConfig;
const sdk = getPromisifiedSdk(requestFetchAdapter, config);
// Use dynamically overridden getCurrentPackage() during tests.
const localPackage = await module.exports.getCurrentPackage();
/*
* If the app has a previously installed update, and that update
* was targetted at the same app version that is currently running,
* then we want to use its package hash to determine whether a new
* release has been made on the server. Otherwise, we only need
* to send the app version to the server, since we are interested
* in any updates for current binary version, regardless of hash.
*/
let queryPackage;
if (localPackage) {
queryPackage = localPackage;
} else {
queryPackage = { appVersion: config.appVersion };
if (Platform.OS === "ios" && config.packageHash) {
queryPackage.packageHash = config.packageHash;
}
}
const update = sharedCodePushOptions.updateChecker
? await (async () => {
try {
// refer to `UpdateCheckRequest` type inside code-push SDK
const updateRequest = {
deployment_key: config.deploymentKey,
app_version: queryPackage.appVersion,
package_hash: queryPackage.packageHash,
is_companion: config.ignoreAppVersion,
label: queryPackage.label,
client_unique_id: config.clientUniqueId,
};
const response = await sharedCodePushOptions.updateChecker(updateRequest);
// extracted from the internal processing of the code-push SDK
const updateInfo = response.update_info;
if (!updateInfo) {
return null;
} else if (updateInfo.update_app_version) {
return { updateAppVersion: true, appVersion: updateInfo.target_binary_range };
} else if (!updateInfo.is_available) {
return null;
}
// refer to `RemotePackage` type inside code-push SDK
return {
deploymentKey: config.deploymentKey,
description: updateInfo.description ?? '',
label: updateInfo.label ?? '',
appVersion: updateInfo.target_binary_range ?? '',
isMandatory: updateInfo.is_mandatory ?? false,
packageHash: updateInfo.package_hash ?? '',
packageSize: updateInfo.package_size ?? 0,
downloadUrl: updateInfo.download_url ?? '',
};
} catch (error) {
log(`An error has occurred at update checker : ${error.stack}`);
if (sharedCodePushOptions.fallbackToAppCenter) {
return await sdk.queryUpdateWithCurrentPackage(queryPackage);
} else {
// update will not happen
return undefined;
}
}
})()
: await sdk.queryUpdateWithCurrentPackage(queryPackage);
if (sharedCodePushOptions.bundleHost && update) {
const fileName = typeof update.downloadUrl === 'string' ? update.downloadUrl.split('/').pop() : null;
if (fileName) {
update.downloadUrl = sharedCodePushOptions.bundleHost + fileName;
}
}
/*
* There are four cases where checkForUpdate will resolve to null:
* ----------------------------------------------------------------
* 1) The server said there isn't an update. This is the most common case.
* 2) The server said there is an update but it requires a newer binary version.
* This would occur when end-users are running an older binary version than
* is available, and CodePush is making sure they don't get an update that
* potentially wouldn't be compatible with what they are running.
* 3) The server said there is an update, but the update's hash is the same as
* the currently running update. This should _never_ happen, unless there is a
* bug in the server, but we're adding this check just to double-check that the
* client app is resilient to a potential issue with the update check.
* 4) The server said there is an update, but the update's hash is the same as that
* of the binary's currently running version. This should only happen in Android -
* unlike iOS, we don't attach the binary's hash to the updateCheck request
* because we want to avoid having to install diff updates against the binary's
* version, which we can't do yet on Android.
*/
if (!update || update.updateAppVersion ||
localPackage && (update.packageHash === localPackage.packageHash) ||
(!localPackage || localPackage._isDebugOnly) && config.packageHash === update.packageHash) {
if (update && update.updateAppVersion) {
log("An update is available but it is not targeting the binary version of your app.");
if (handleBinaryVersionMismatchCallback && typeof handleBinaryVersionMismatchCallback === "function") {
handleBinaryVersionMismatchCallback(update)
}
}
return null;
} else {
const remotePackage = { ...update, ...PackageMixins.remote(sdk.reportStatusDownload) };
remotePackage.failedInstall = await NativeCodePush.isFailedUpdate(remotePackage.packageHash);
remotePackage.deploymentKey = deploymentKey || nativeConfig.deploymentKey;
return remotePackage;
}
}
const getConfiguration = (() => {
let config;
return async function getConfiguration() {
if (config) {
return config;
} else if (testConfig) {
return testConfig;
} else {
config = await NativeCodePush.getConfiguration();
return config;
}
}
})();
async function getCurrentPackage() {
return await getUpdateMetadata(CodePush.UpdateState.LATEST);
}
async function getUpdateMetadata(updateState) {
let updateMetadata = await NativeCodePush.getUpdateMetadata(updateState || CodePush.UpdateState.RUNNING);
if (updateMetadata) {
updateMetadata = {...PackageMixins.local, ...updateMetadata};
updateMetadata.failedInstall = await NativeCodePush.isFailedUpdate(updateMetadata.packageHash);
updateMetadata.isFirstRun = await NativeCodePush.isFirstRun(updateMetadata.packageHash);
}
return updateMetadata;
}
function getPromisifiedSdk(requestFetchAdapter, config) {
// Use dynamically overridden AcquisitionSdk during tests.
const sdk = new module.exports.AcquisitionSdk(requestFetchAdapter, config);
sdk.queryUpdateWithCurrentPackage = (queryPackage) => {
return new Promise((resolve, reject) => {
module.exports.AcquisitionSdk.prototype.queryUpdateWithCurrentPackage.call(sdk, queryPackage, (err, update) => {
if (err) {
reject(err);
} else {
resolve(update);
}
});
});
};
sdk.reportStatusDeploy = (deployedPackage, status, previousLabelOrAppVersion, previousDeploymentKey) => {
return new Promise((resolve, reject) => {
module.exports.AcquisitionSdk.prototype.reportStatusDeploy.call(sdk, deployedPackage, status, previousLabelOrAppVersion, previousDeploymentKey, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
};
sdk.reportStatusDownload = (downloadedPackage) => {
return new Promise((resolve, reject) => {
module.exports.AcquisitionSdk.prototype.reportStatusDownload.call(sdk, downloadedPackage, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
};
return sdk;
}
// This ensures that notifyApplicationReadyInternal is only called once
// in the lifetime of this module instance.
const notifyApplicationReady = (() => {
let notifyApplicationReadyPromise;
return () => {
if (!notifyApplicationReadyPromise) {
notifyApplicationReadyPromise = notifyApplicationReadyInternal();
}
return notifyApplicationReadyPromise;
};
})();
async function notifyApplicationReadyInternal() {
await NativeCodePush.notifyApplicationReady();
const statusReport = await NativeCodePush.getNewStatusReport();
statusReport && tryReportStatus(statusReport); // Don't wait for this to complete.
return statusReport;
}
async function tryReportStatus(statusReport, retryOnAppResume) {
const config = await getConfiguration();
const previousLabelOrAppVersion = statusReport.previousLabelOrAppVersion;
const previousDeploymentKey = statusReport.previousDeploymentKey || config.deploymentKey;
try {
if (statusReport.appVersion) {
log(`Reporting binary update (${statusReport.appVersion})`);
if (!config.deploymentKey) {
throw new Error("Deployment key is missed");
}
const sdk = getPromisifiedSdk(requestFetchAdapter, config);
await sdk.reportStatusDeploy(/* deployedPackage */ null, /* status */ null, previousLabelOrAppVersion, previousDeploymentKey);
} else {
const label = statusReport.package.label;
if (statusReport.status === "DeploymentSucceeded") {
log(`Reporting CodePush update success (${label})`);
} else {
log(`Reporting CodePush update rollback (${label})`);
await NativeCodePush.setLatestRollbackInfo(statusReport.package.packageHash);
}
config.deploymentKey = statusReport.package.deploymentKey;
const sdk = getPromisifiedSdk(requestFetchAdapter, config);
await sdk.reportStatusDeploy(statusReport.package, statusReport.status, previousLabelOrAppVersion, previousDeploymentKey);
}
NativeCodePush.recordStatusReported(statusReport);
retryOnAppResume && retryOnAppResume.remove();
} catch (e) {
log(`Report status failed: ${JSON.stringify(statusReport)}`);
NativeCodePush.saveStatusReportForRetry(statusReport);
// Try again when the app resumes
if (!retryOnAppResume) {
const resumeListener = AppState.addEventListener("change", async (newState) => {
if (newState !== "active") return;
const refreshedStatusReport = await NativeCodePush.getNewStatusReport();
if (refreshedStatusReport) {
tryReportStatus(refreshedStatusReport, resumeListener);
} else {
resumeListener && resumeListener.remove();
}
});
}
}
}
async function shouldUpdateBeIgnored(remotePackage, syncOptions) {
let { rollbackRetryOptions } = syncOptions;
const isFailedPackage = remotePackage && remotePackage.failedInstall;
if (!isFailedPackage || !syncOptions.ignoreFailedUpdates) {
return false;
}
if (!rollbackRetryOptions) {
return true;
}
if (typeof rollbackRetryOptions !== "object") {
rollbackRetryOptions = CodePush.DEFAULT_ROLLBACK_RETRY_OPTIONS;
} else {
rollbackRetryOptions = { ...CodePush.DEFAULT_ROLLBACK_RETRY_OPTIONS, ...rollbackRetryOptions };
}
if (!validateRollbackRetryOptions(rollbackRetryOptions)) {
return true;
}
const latestRollbackInfo = await NativeCodePush.getLatestRollbackInfo();
if (!validateLatestRollbackInfo(latestRollbackInfo, remotePackage.packageHash)) {
log("The latest rollback info is not valid.");
return true;
}
const { delayInHours, maxRetryAttempts } = rollbackRetryOptions;
const hoursSinceLatestRollback = (Date.now() - latestRollbackInfo.time) / (1000 * 60 * 60);
if (hoursSinceLatestRollback >= delayInHours && maxRetryAttempts >= latestRollbackInfo.count) {
log("Previous rollback should be ignored due to rollback retry options.");
return false;
}
return true;
}
function validateLatestRollbackInfo(latestRollbackInfo, packageHash) {
return latestRollbackInfo &&
latestRollbackInfo.time &&
latestRollbackInfo.count &&
latestRollbackInfo.packageHash &&
latestRollbackInfo.packageHash === packageHash;
}
function validateRollbackRetryOptions(rollbackRetryOptions) {
if (typeof rollbackRetryOptions.delayInHours !== "number") {
log("The 'delayInHours' rollback retry parameter must be a number.");
return false;
}
if (typeof rollbackRetryOptions.maxRetryAttempts !== "number") {
log("The 'maxRetryAttempts' rollback retry parameter must be a number.");
return false;
}
if (rollbackRetryOptions.maxRetryAttempts < 1) {
log("The 'maxRetryAttempts' rollback retry parameter cannot be less then 1.");
return false;
}
return true;
}
var testConfig;
// This function is only used for tests. Replaces the default SDK, configuration and native bridge
function setUpTestDependencies(testSdk, providedTestConfig, testNativeBridge) {
if (testSdk) module.exports.AcquisitionSdk = testSdk;
if (providedTestConfig) testConfig = providedTestConfig;
if (testNativeBridge) NativeCodePush = testNativeBridge;
}
async function restartApp(onlyIfUpdateIsPending = false) {
NativeCodePush.restartApp(onlyIfUpdateIsPending);
}
// This function allows only one syncInternal operation to proceed at any given time.
// Parallel calls to sync() while one is ongoing yields CodePush.SyncStatus.SYNC_IN_PROGRESS.
const sync = (() => {
let syncInProgress = false;
const setSyncCompleted = () => { syncInProgress = false; };
return (options = {}, syncStatusChangeCallback, downloadProgressCallback, handleBinaryVersionMismatchCallback) => {
let syncStatusCallbackWithTryCatch, downloadProgressCallbackWithTryCatch;
if (typeof syncStatusChangeCallback === "function") {
syncStatusCallbackWithTryCatch = (...args) => {
try {
syncStatusChangeCallback(...args);
} catch (error) {
log(`An error has occurred : ${error.stack}`);
}
}
}
if (typeof downloadProgressCallback === "function") {
downloadProgressCallbackWithTryCatch = (...args) => {
try {
downloadProgressCallback(...args);
} catch (error) {
log(`An error has occurred: ${error.stack}`);
}
}
}
if (syncInProgress) {
typeof syncStatusCallbackWithTryCatch === "function"
? syncStatusCallbackWithTryCatch(CodePush.SyncStatus.SYNC_IN_PROGRESS)
: log("Sync already in progress.");
return Promise.resolve(CodePush.SyncStatus.SYNC_IN_PROGRESS);
}
syncInProgress = true;
const syncPromise = syncInternal(options, syncStatusCallbackWithTryCatch, downloadProgressCallbackWithTryCatch, handleBinaryVersionMismatchCallback);
syncPromise
.then(setSyncCompleted)
.catch(setSyncCompleted);
return syncPromise;
};
})();
/*
* The syncInternal method provides a simple, one-line experience for
* incorporating the check, download and installation of an update.
*
* It simply composes the existing API methods together and adds additional
* support for respecting mandatory updates, ignoring previously failed
* releases, and displaying a standard confirmation UI to the end-user
* when an update is available.
*/
async function syncInternal(options = {}, syncStatusChangeCallback, downloadProgressCallback, handleBinaryVersionMismatchCallback) {
let resolvedInstallMode;
const syncOptions = {
deploymentKey: null,
ignoreFailedUpdates: true,
rollbackRetryOptions: null,
installMode: CodePush.InstallMode.ON_NEXT_RESTART,
mandatoryInstallMode: CodePush.InstallMode.IMMEDIATE,
minimumBackgroundDuration: 0,
updateDialog: null,
...options
};
syncStatusChangeCallback = typeof syncStatusChangeCallback === "function"
? syncStatusChangeCallback
: (syncStatus) => {
switch(syncStatus) {
case CodePush.SyncStatus.CHECKING_FOR_UPDATE:
log("Checking for update.");
break;
case CodePush.SyncStatus.AWAITING_USER_ACTION:
log("Awaiting user action.");
break;
case CodePush.SyncStatus.DOWNLOADING_PACKAGE:
log("Downloading package.");
break;
case CodePush.SyncStatus.INSTALLING_UPDATE:
log("Installing update.");
break;
case CodePush.SyncStatus.UP_TO_DATE:
log("App is up to date.");
break;
case CodePush.SyncStatus.UPDATE_IGNORED:
log("User cancelled the update.");
break;
case CodePush.SyncStatus.UPDATE_INSTALLED:
if (resolvedInstallMode == CodePush.InstallMode.ON_NEXT_RESTART) {
log("Update is installed and will be run on the next app restart.");
} else if (resolvedInstallMode == CodePush.InstallMode.ON_NEXT_RESUME) {
if (syncOptions.minimumBackgroundDuration > 0) {
log(`Update is installed and will be run after the app has been in the background for at least ${syncOptions.minimumBackgroundDuration} seconds.`);
} else {
log("Update is installed and will be run when the app next resumes.");
}
}
break;
case CodePush.SyncStatus.UNKNOWN_ERROR:
log("An unknown error occurred.");
break;
}
};
try {
await CodePush.notifyApplicationReady();
syncStatusChangeCallback(CodePush.SyncStatus.CHECKING_FOR_UPDATE);
const remotePackage = await checkForUpdate(syncOptions.deploymentKey, handleBinaryVersionMismatchCallback);
const doDownloadAndInstall = async () => {
syncStatusChangeCallback(CodePush.SyncStatus.DOWNLOADING_PACKAGE);
const localPackage = await remotePackage.download(downloadProgressCallback);
// Determine the correct install mode based on whether the update is mandatory or not.
resolvedInstallMode = localPackage.isMandatory ? syncOptions.mandatoryInstallMode : syncOptions.installMode;
syncStatusChangeCallback(CodePush.SyncStatus.INSTALLING_UPDATE);
await localPackage.install(resolvedInstallMode, syncOptions.minimumBackgroundDuration, () => {
syncStatusChangeCallback(CodePush.SyncStatus.UPDATE_INSTALLED);
});
return CodePush.SyncStatus.UPDATE_INSTALLED;
};
const updateShouldBeIgnored = await shouldUpdateBeIgnored(remotePackage, syncOptions);
if (!remotePackage || updateShouldBeIgnored) {
if (updateShouldBeIgnored) {
log("An update is available, but it is being ignored due to having been previously rolled back.");
}
const currentPackage = await CodePush.getCurrentPackage();
if (currentPackage && currentPackage.isPending) {
syncStatusChangeCallback(CodePush.SyncStatus.UPDATE_INSTALLED);
return CodePush.SyncStatus.UPDATE_INSTALLED;
} else {
syncStatusChangeCallback(CodePush.SyncStatus.UP_TO_DATE);
return CodePush.SyncStatus.UP_TO_DATE;
}
} else if (syncOptions.updateDialog) {
// updateDialog supports any truthy value (e.g. true, "goo", 12),
// but we should treat a non-object value as just the default dialog
if (typeof syncOptions.updateDialog !== "object") {
syncOptions.updateDialog = CodePush.DEFAULT_UPDATE_DIALOG;
} else {
syncOptions.updateDialog = { ...CodePush.DEFAULT_UPDATE_DIALOG, ...syncOptions.updateDialog };
}
return await new Promise((resolve, reject) => {
let message = null;
let installButtonText = null;
const dialogButtons = [];
if (remotePackage.isMandatory) {
message = syncOptions.updateDialog.mandatoryUpdateMessage;
installButtonText = syncOptions.updateDialog.mandatoryContinueButtonLabel;
} else {
message = syncOptions.updateDialog.optionalUpdateMessage;
installButtonText = syncOptions.updateDialog.optionalInstallButtonLabel;
// Since this is an optional update, add a button
// to allow the end-user to ignore it
dialogButtons.push({
text: syncOptions.updateDialog.optionalIgnoreButtonLabel,
onPress: () => {
syncStatusChangeCallback(CodePush.SyncStatus.UPDATE_IGNORED);
resolve(CodePush.SyncStatus.UPDATE_IGNORED);
}
});
}
// Since the install button should be placed to the
// right of any other button, add it last
dialogButtons.push({
text: installButtonText,
onPress:() => {
doDownloadAndInstall()
.then(resolve, reject);
}
})
// If the update has a description, and the developer
// explicitly chose to display it, then set that as the message
if (syncOptions.updateDialog.appendReleaseDescription && remotePackage.description) {
message += `${syncOptions.updateDialog.descriptionPrefix} ${remotePackage.description}`;
}
syncStatusChangeCallback(CodePush.SyncStatus.AWAITING_USER_ACTION);
Alert.alert(syncOptions.updateDialog.title, message, dialogButtons);
});
} else {
return await doDownloadAndInstall();
}
} catch (error) {
syncStatusChangeCallback(CodePush.SyncStatus.UNKNOWN_ERROR);
log(error.message);
throw error;
}
};
let CodePush;
/**
* @callback updateChecker
* @param {UpdateCheckRequest} updateRequest Current package information to check for updates.
* @returns {Promise<{update_info: UpdateCheckResponse}>} The result of the update check. Follows the AppCenter API response interface.
*/
/**
* If you pass options once when calling `codePushify`, they will be shared with related functions.
* @type {{
* bundleHost: string | undefined,
* setBundleHost(host: string): void,
* updateChecker: updateChecker | undefined,
* setUpdateChecker(updateCheckerFunction: updateChecker): void,
* fallbackToAppCenter: boolean,
* setFallbackToAppCenter(enable: boolean): void
* }}
*/
const sharedCodePushOptions = {
bundleHost: undefined,
setBundleHost(host) {
if (host && typeof host !== 'string') throw new Error('pass a string to setBundleHost');
if (typeof host === 'string' && host.slice(-1) !== '/') {
host += '/';
}
this.bundleHost = host;
},
updateChecker: undefined,
setUpdateChecker(updateCheckerFunction) {
if (updateCheckerFunction && typeof updateCheckerFunction !== 'function') throw new Error('pass a function to setUpdateChecker');
this.updateChecker = updateCheckerFunction;
},
fallbackToAppCenter: true,
setFallbackToAppCenter(enable) {
this.fallbackToAppCenter = enable;
}
}
function codePushify(options = {}) {
let React;
let ReactNative = require("react-native");
try { React = require("react"); } catch (e) { }
if (!React) {
try { React = ReactNative.React; } catch (e) { }
if (!React) {
throw new Error("Unable to find the 'React' module.");
}
}
if (!React.Component) {
throw new Error(
`Unable to find the "Component" class, please either:
1. Upgrade to a newer version of React Native that supports it, or
2. Call the codePush.sync API in your component instead of using the @codePush decorator`
);
}
sharedCodePushOptions.setBundleHost(options.bundleHost);
sharedCodePushOptions.setUpdateChecker(options.updateChecker);
sharedCodePushOptions.setFallbackToAppCenter(options.fallbackToAppCenter);
const decorator = (RootComponent) => {
class CodePushComponent extends React.Component {
constructor(props) {
super(props);
this.rootComponentRef = React.createRef();
}
componentDidMount() {
if (options.checkFrequency === CodePush.CheckFrequency.MANUAL) {
CodePush.notifyAppReady();
} else {
const rootComponentInstance = this.rootComponentRef.current;
let syncStatusCallback;
if (rootComponentInstance && rootComponentInstance.codePushStatusDidChange) {
syncStatusCallback = rootComponentInstance.codePushStatusDidChange.bind(rootComponentInstance);
}
let downloadProgressCallback;
if (rootComponentInstance && rootComponentInstance.codePushDownloadDidProgress) {
downloadProgressCallback = rootComponentInstance.codePushDownloadDidProgress.bind(rootComponentInstance);
}
let handleBinaryVersionMismatchCallback;
if (rootComponentInstance && rootComponentInstance.codePushOnBinaryVersionMismatch) {
handleBinaryVersionMismatchCallback = rootComponentInstance.codePushOnBinaryVersionMismatch.bind(rootComponentInstance);
}
CodePush.sync(options, syncStatusCallback, downloadProgressCallback, handleBinaryVersionMismatchCallback);
if (options.checkFrequency === CodePush.CheckFrequency.ON_APP_RESUME) {
ReactNative.AppState.addEventListener("change", (newState) => {
if (newState === "active") {
CodePush.sync(options, syncStatusCallback, downloadProgressCallback);
}
});
}
}
}
render() {
const props = {...this.props};
// We can set ref property on class components only (not stateless)
// Check it by render method
if (RootComponent.prototype && RootComponent.prototype.render) {
props.ref = this.rootComponentRef;
}
return <RootComponent {...props} />
}
}
return hoistStatics(CodePushComponent, RootComponent);
}
if (typeof options === "function") {
// Infer that the root component was directly passed to us.
return decorator(options);
} else {
return decorator;
}
}
// If the "NativeCodePush" variable isn't defined, then
// the app didn't properly install the native module,
// and therefore, it doesn't make sense initializing
// the JS interface when it wouldn't work anyways.
if (NativeCodePush) {
CodePush = codePushify;
Object.assign(CodePush, {
AcquisitionSdk: Sdk,
checkForUpdate,
getConfiguration,
getCurrentPackage,
getUpdateMetadata,
log,
notifyAppReady: notifyApplicationReady,
notifyApplicationReady,
restartApp,
setUpTestDependencies,
sync,
disallowRestart: NativeCodePush.disallow,
allowRestart: NativeCodePush.allow,
clearUpdates: NativeCodePush.clearUpdates,
InstallMode: {
IMMEDIATE: NativeCodePush.codePushInstallModeImmediate, // Restart the app immediately
ON_NEXT_RESTART: NativeCodePush.codePushInstallModeOnNextRestart, // Don't artificially restart the app. Allow the update to be "picked up" on the next app restart
ON_NEXT_RESUME: NativeCodePush.codePushInstallModeOnNextResume, // Restart the app the next time it is resumed from the background
ON_NEXT_SUSPEND: NativeCodePush.codePushInstallModeOnNextSuspend // Restart the app _while_ it is in the background,
// but only after it has been in the background for "minimumBackgroundDuration" seconds (0 by default),
// so that user context isn't lost unless the app suspension is long enough to not matter
},
SyncStatus: {
UP_TO_DATE: 0, // The running app is up-to-date
UPDATE_INSTALLED: 1, // The app had an optional/mandatory update that was successfully downloaded and is about to be installed.
UPDATE_IGNORED: 2, // The app had an optional update and the end-user chose to ignore it
UNKNOWN_ERROR: 3,
SYNC_IN_PROGRESS: 4, // There is an ongoing "sync" operation in progress.
CHECKING_FOR_UPDATE: 5,
AWAITING_USER_ACTION: 6,
DOWNLOADING_PACKAGE: 7,
INSTALLING_UPDATE: 8
},
CheckFrequency: {
ON_APP_START: 0,
ON_APP_RESUME: 1,
MANUAL: 2
},
UpdateState: {
RUNNING: NativeCodePush.codePushUpdateStateRunning,
PENDING: NativeCodePush.codePushUpdateStatePending,
LATEST: NativeCodePush.codePushUpdateStateLatest
},
DeploymentStatus: {
FAILED: "DeploymentFailed",
SUCCEEDED: "DeploymentSucceeded",
},
DEFAULT_UPDATE_DIALOG: {
appendReleaseDescription: false,
descriptionPrefix: " Description: ",
mandatoryContinueButtonLabel: "Continue",
mandatoryUpdateMessage: "An update is available that must be installed.",
optionalIgnoreButtonLabel: "Ignore",
optionalInstallButtonLabel: "Install",
optionalUpdateMessage: "An update is available. Would you like to install it?",
title: "Update available"
},
DEFAULT_ROLLBACK_RETRY_OPTIONS: {
delayInHours: 24,
maxRetryAttempts: 1
}
});
} else {
log("The CodePush module doesn't appear to be properly installed. Please double-check that everything is setup correctly.");
}
module.exports = CodePush;