@hot-updater/react-native
Version:
React Native OTA solution for self-hosted
310 lines (309 loc) • 17.1 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var plugin_core_1 = require("@hot-updater/plugin-core");
var config_plugins_1 = require("expo/config-plugins");
var hot_updater_1 = require("hot-updater");
var package_json_1 = __importDefault(require("../../package.json"));
var fingerprintCache = null;
var getFingerprint = function () { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (fingerprintCache) {
return [2 /*return*/, fingerprintCache];
}
return [4 /*yield*/, (0, hot_updater_1.generateFingerprints)()];
case 1:
fingerprintCache = _a.sent();
return [4 /*yield*/, (0, hot_updater_1.createFingerprintJSON)(fingerprintCache)];
case 2:
_a.sent();
return [2 /*return*/, fingerprintCache];
}
});
}); };
/**
* Helper to add lines if they don't exist, anchored by a specific string.
*/
function addLinesOnce(contents, anchor, linesToAdd) {
if (linesToAdd.every(function (line) { return contents.includes(line); })) {
// All lines already exist, do nothing
return contents;
}
// Check if the anchor exists
if (!contents.includes(anchor)) {
// Anchor not found, cannot add lines reliably.
// Consider logging a warning or throwing an error here if necessary.
return contents;
}
// Add lines after the anchor
// Ensure newline separation
return contents.replace(anchor, "".concat(anchor, "\n").concat(linesToAdd.join("\n")));
}
/**
* Helper to replace content only if the target content exists and hasn't been replaced yet.
*/
function replaceContentOnce(contents, searchRegex, replacement, checkIfAlreadyReplaced) {
// If the replacement content is already present, assume it's done.
if (contents.includes(checkIfAlreadyReplaced)) {
return contents;
}
// Otherwise, perform the replacement if the search target exists.
return contents.replace(searchRegex, replacement);
}
/**
* Native code modifications - should only run once
*/
var withHotUpdaterNativeCode = function (config) {
var modifiedConfig = config;
// === iOS: Objective-C & Swift in AppDelegate ===
modifiedConfig = (0, config_plugins_1.withAppDelegate)(modifiedConfig, function (cfg) {
var contents = cfg.modResults.contents;
var iosImport = "#import <HotUpdater/HotUpdater.h>";
var iosBundleUrl = "[HotUpdater bundleURL]";
var iosOriginalBundleUrlRegex = /\[\[NSBundle mainBundle\] URLForResource:@"main" withExtension:@"jsbundle"\]/g;
var iosAppDelegateHeader = '#import "AppDelegate.h"'; // Anchor for import
var swiftImport = "import HotUpdater";
var swiftBundleUrl = "HotUpdater.bundleURL()";
var swiftOriginalBundleUrlRegex = /Bundle\.main\.url\(forResource: "?main"?, withExtension: "jsbundle"\)/g;
var swiftReactImport = "import React"; // Anchor for import
// --- Objective-C ---
if (contents.includes(iosAppDelegateHeader)) {
// Check if it's likely Obj-C
// 1. Add import if missing
contents = addLinesOnce(contents, iosAppDelegateHeader, [iosImport]);
// 2. Replace bundleURL provider if the original exists and hasn't been replaced
contents = replaceContentOnce(contents, iosOriginalBundleUrlRegex, iosBundleUrl, iosBundleUrl);
}
// --- Swift ---
if (contents.includes(swiftReactImport)) {
// Check if it's likely Swift
// 1. Add import if missing
contents = addLinesOnce(contents, swiftReactImport, [swiftImport]);
// 2. Replace bundleURL provider if the original exists and hasn't been replaced
contents = replaceContentOnce(contents, swiftOriginalBundleUrlRegex, swiftBundleUrl, swiftBundleUrl);
}
cfg.modResults.contents = contents;
return cfg;
});
// === Android: Kotlin & Java in MainApplication ===
modifiedConfig = (0, config_plugins_1.withMainApplication)(modifiedConfig, function (cfg) {
var contents = cfg.modResults.contents;
var kotlinImport = "import com.hotupdater.HotUpdater";
var kotlinImportAnchor = "import com.facebook.react.ReactApplication";
var kotlinReactNativeHostAnchor = "object : DefaultReactNativeHost(this) {"; // Start of block
var kotlinMethodCheck = "HotUpdater.getJSBundleFile(applicationContext)"; // Unique part of the method body
// Regex to find an existing getJSBundleFile override (non-greedy)
var kotlinExistingMethodRegex = /^\s*override fun getJSBundleFile\(\): String\?\s*\{[\s\S]*?^\s*\}/gm;
var kotlinHermesAnchor = "override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED";
var kotlinNewArchAnchor = "override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED";
var kotlinNewMethod = "\n override fun getJSBundleFile(): String? {\n return HotUpdater.getJSBundleFile(applicationContext)\n }";
var javaImport = "import com.hotupdater.HotUpdater;";
var javaImportAnchor = "import com.facebook.react.ReactApplication;";
var javaReactNativeHostAnchor = "new DefaultReactNativeHost"; // Part of the instantiation
var javaMethodCheck = "HotUpdater.Companion.getJSBundleFile"; // Unique part of the method body
// Regex to find an existing getJSBundleFile override (non-greedy)
var javaExistingMethodRegex = /^\s*@Override\s+protected String getJSBundleFile\(\)\s*\{[\s\S]*?^\s*\}/gm;
var javaHermesBlockEndAnchor = "return BuildConfig.IS_HERMES_ENABLED;\n }"; // End of the isHermesEnabled method block
var javaNewMethod = "\n @Override\n protected String getJSBundleFile() {\n return HotUpdater.Companion.getJSBundleFile(this.getApplication().getApplicationContext());\n }";
// --- Kotlin ---
if (contents.includes(kotlinReactNativeHostAnchor)) {
// Check if likely Kotlin
// 1. Add import if missing
contents = addLinesOnce(contents, kotlinImportAnchor, [kotlinImport]);
// 2. Add/Replace getJSBundleFile method if needed
if (!contents.includes(kotlinMethodCheck)) {
// Desired method content not found
// Remove potentially existing (different) override first
contents = contents.replace(kotlinExistingMethodRegex, "");
// Add the new method after the isHermesEnabled property
if (contents.includes(kotlinHermesAnchor)) {
contents = contents.replace(kotlinHermesAnchor, "".concat(kotlinHermesAnchor, "\n").concat(kotlinNewMethod));
}
else if (contents.includes(kotlinNewArchAnchor)) {
contents = contents.replace(kotlinNewArchAnchor, "".concat(kotlinNewArchAnchor, "\n").concat(kotlinNewMethod));
}
else {
// Fallback: Add before the closing brace of the object if anchor not found
var rnHostEndRegex = /(\s*object\s*:\s*DefaultReactNativeHost\s*\([\s\S]*?\n)(\s*\})\s*$/m;
if (rnHostEndRegex.test(contents)) {
contents = contents.replace(rnHostEndRegex, "$1".concat(kotlinNewMethod, "\n$2"));
}
else {
throw new Error("[withHotUpdater] Kotlin: Could not find Hermes anchor or closing brace to insert getJSBundleFile.");
}
}
}
}
// --- Java ---
if (contents.includes(javaReactNativeHostAnchor) &&
contents.includes("@Override")) {
// Check if likely Java
// 1. Add import if missing
contents = addLinesOnce(contents, javaImportAnchor, [javaImport]);
// 2. Add/Replace getJSBundleFile method if needed
if (!contents.includes(javaMethodCheck)) {
// Desired method content not found
// Remove potentially existing (different) override first
contents = contents.replace(javaExistingMethodRegex, "");
// Add the new method after the isHermesEnabled method block
if (contents.includes(javaHermesBlockEndAnchor)) {
contents = contents.replace(javaHermesBlockEndAnchor, "".concat(javaHermesBlockEndAnchor, "\n").concat(javaNewMethod));
}
else {
// Fallback: Add before the closing brace of the anonymous class
var rnHostEndRegex = /(\s*new\s*DefaultReactNativeHost\s*\([\s\S]*?\n)(\s*\});\s*$/m;
if (rnHostEndRegex.test(contents)) {
contents = contents.replace(rnHostEndRegex, "$1".concat(javaNewMethod, "\n$2"));
}
else {
throw new Error("[withHotUpdater] Java: Could not find Hermes anchor or closing brace to insert getJSBundleFile.");
}
}
}
}
cfg.modResults.contents = contents;
return cfg;
});
return modifiedConfig;
};
/**
* Configuration updates - should run every time
*/
var withHotUpdaterConfigAsync = function (props) { return function (config) {
var channel = props.channel || "production";
var modifiedConfig = config;
// === iOS: Add channel and fingerprint to Info.plist ===
modifiedConfig = (0, config_plugins_1.withInfoPlist)(modifiedConfig, function (cfg) { return __awaiter(void 0, void 0, void 0, function () {
var fingerprintHash, config, fingerprint;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
fingerprintHash = null;
return [4 /*yield*/, (0, plugin_core_1.loadConfig)(null)];
case 1:
config = _a.sent();
if (!(config.updateStrategy !== "appVersion")) return [3 /*break*/, 3];
return [4 /*yield*/, getFingerprint()];
case 2:
fingerprint = _a.sent();
fingerprintHash = fingerprint.ios.hash;
_a.label = 3;
case 3:
cfg.modResults.HOT_UPDATER_CHANNEL = channel;
if (fingerprintHash) {
cfg.modResults.HOT_UPDATER_FINGERPRINT_HASH = fingerprintHash;
}
return [2 /*return*/, cfg];
}
});
}); });
// === Android: Add channel and fingerprint to strings.xml ===
modifiedConfig = (0, config_plugins_1.withStringsXml)(modifiedConfig, function (cfg) { return __awaiter(void 0, void 0, void 0, function () {
var fingerprintHash, config, fingerprint;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
fingerprintHash = null;
return [4 /*yield*/, (0, plugin_core_1.loadConfig)(null)];
case 1:
config = _a.sent();
if (!(config.updateStrategy !== "appVersion")) return [3 /*break*/, 3];
return [4 /*yield*/, getFingerprint()];
case 2:
fingerprint = _a.sent();
fingerprintHash = fingerprint.android.hash;
_a.label = 3;
case 3:
// Ensure resources object exists
if (!cfg.modResults.resources) {
cfg.modResults.resources = {};
}
if (!cfg.modResults.resources.string) {
cfg.modResults.resources.string = [];
}
// Remove existing hot_updater_channel entry if it exists
cfg.modResults.resources.string = cfg.modResults.resources.string.filter(function (item) { return !(item.$ && item.$.name === "hot_updater_channel"); });
// Add the new hot_updater_channel entry
cfg.modResults.resources.string.push({
$: {
name: "hot_updater_channel",
moduleConfig: "true",
},
_: channel,
});
if (fingerprintHash) {
// Remove existing hot_updater_fingerprint_hash entry if it exists
cfg.modResults.resources.string =
cfg.modResults.resources.string.filter(function (item) {
return !(item.$ && item.$.name === "hot_updater_fingerprint_hash");
});
// Add the new hot_updater_fingerprint_hash entry
cfg.modResults.resources.string.push({
$: {
name: "hot_updater_fingerprint_hash",
moduleConfig: "true",
},
_: fingerprintHash,
});
}
return [2 /*return*/, cfg];
}
});
}); });
return modifiedConfig;
}; };
/**
* Main plugin that combines both native code (run once) and config (run always)
*/
var withHotUpdater = function (config, props) {
if (props === void 0) { props = {}; }
// Apply plugins in order
return (0, config_plugins_1.withPlugins)(config, [
// Native code modifications - wrapped with createRunOncePlugin
(0, config_plugins_1.createRunOncePlugin)(withHotUpdaterNativeCode, "".concat(package_json_1.default.name, "-native"), package_json_1.default.version),
// Configuration updates - runs every time
withHotUpdaterConfigAsync(props),
]);
};
// Export the main plugin
exports.default = withHotUpdater;