@gfean/react-native-bundle-drop 0.2.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -37,12 +37,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
37
37
  return (mod && mod.__esModule) ? mod : { "default": mod };
38
38
  };
39
39
  Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.findProjectRoot = findProjectRoot;
41
+ exports.runBundleScript = runBundleScript;
40
42
  const adm_zip_1 = __importDefault(require("adm-zip"));
41
43
  const child_process_1 = require("child_process");
42
44
  const crypto_1 = require("crypto");
43
45
  const fs = __importStar(require("fs"));
44
46
  const path = __importStar(require("path"));
45
- const packageRoot = path.resolve(__dirname, '..', '..');
47
+ const getPackageRoot = () => process.env.BUNDLE_DROP_PACKAGE_ROOT_OVERRIDE || path.resolve(__dirname, '..', '..');
46
48
  function findProjectRoot(startDir) {
47
49
  let dir = path.resolve(startDir);
48
50
  const MAX_UP = 12;
@@ -59,105 +61,139 @@ function findProjectRoot(startDir) {
59
61
  }
60
62
  return startDir;
61
63
  }
62
- const platform = process.argv[2] || 'ios';
63
- const isAndroid = platform === 'android';
64
- const fileSuffix = isAndroid ? 'android' : 'ios';
65
- const outputDir = path.resolve(packageRoot, 'dist');
66
- const assetsDir = path.join(outputDir, 'assets');
67
- const bundlePath = path.join(outputDir, 'main.jsbundle');
68
- const metadataPath = path.join(outputDir, `metadata-${fileSuffix}.json`);
69
- const zipPath = path.join(outputDir, `bundle-${platform}.zip`);
70
- const imageManifest = {};
71
- const projectRoot = findProjectRoot(process.cwd());
72
- // load runtimeVersion from project-level bundle.drop.config.js if present
73
- let runtimeVersion;
74
- const configPath = path.resolve(projectRoot, 'bundle.drop.config.js');
75
- if (fs.existsSync(configPath)) {
76
- //eslint-disable-next-line
77
- const cfg = require(configPath);
78
- runtimeVersion = cfg?.runtimeVersion?.[platform];
79
- if (!runtimeVersion) {
80
- console.warn(`⚠️ No runtimeVersion found for ${platform} in bundle.drop.config.js. Example: runtimeVersion: { ios: "1.0.0", android: "1.0.0" }`);
64
+ function runBundleScript(options) {
65
+ const packageRoot = getPackageRoot();
66
+ const platform = options?.platform || process.argv[2] || 'ios';
67
+ if (!['ios', 'android'].includes(platform)) {
68
+ console.error('❌ Please provide platform: ios or android');
69
+ process.exit(1);
81
70
  }
82
- }
83
- else {
84
- console.warn('⚠️ bundle.drop.config.js not found in project root; runtimeVersion will be omitted.');
85
- }
86
- // 🧹 Clean up old files
87
- [bundlePath, zipPath, metadataPath].forEach(file => {
88
- if (fs.existsSync(file))
89
- fs.unlinkSync(file);
90
- });
91
- if (fs.existsSync(assetsDir))
92
- fs.rmSync(assetsDir, { recursive: true, force: true });
93
- // 📁 Ensure output dirs
94
- fs.mkdirSync(outputDir, { recursive: true });
95
- fs.mkdirSync(assetsDir, { recursive: true });
96
- console.log(`📦 Bundling React Native code for platform: ${platform}...`);
97
- (0, child_process_1.execSync)(`npx react-native bundle \
71
+ const isAndroid = platform === 'android';
72
+ const fileSuffix = isAndroid ? 'android' : 'ios';
73
+ const outputDir = path.resolve(packageRoot, 'dist');
74
+ const assetsDir = path.join(outputDir, 'assets');
75
+ const bundlePath = path.join(outputDir, 'main.jsbundle');
76
+ const metadataPath = path.join(outputDir, `metadata-${fileSuffix}.json`);
77
+ const zipPath = path.join(outputDir, `bundle-${platform}.zip`);
78
+ const imageManifest = {};
79
+ const projectRoot = findProjectRoot(options?.cwd || process.cwd());
80
+ let runtimeVersion;
81
+ const configPath = path.resolve(projectRoot, 'bundle.drop.config.js');
82
+ if (fs.existsSync(configPath)) {
83
+ //eslint-disable-next-line
84
+ const cfg = require(configPath);
85
+ runtimeVersion = cfg?.runtimeVersion?.[platform];
86
+ if (!runtimeVersion) {
87
+ console.warn(`⚠️ No runtimeVersion found for ${platform} in bundle.drop.config.js. Example: runtimeVersion: { ios: "1.0.0", android: "1.0.0" }`);
88
+ }
89
+ }
90
+ else {
91
+ console.warn('⚠️ bundle.drop.config.js not found in project root; runtimeVersion will be omitted.');
92
+ }
93
+ [bundlePath, zipPath, metadataPath].forEach(file => {
94
+ if (fs.existsSync(file))
95
+ fs.unlinkSync(file);
96
+ });
97
+ if (fs.existsSync(assetsDir))
98
+ fs.rmSync(assetsDir, { recursive: true, force: true });
99
+ fs.mkdirSync(outputDir, { recursive: true });
100
+ fs.mkdirSync(assetsDir, { recursive: true });
101
+ console.log(`📦 Bundling React Native code for platform: ${platform}...`);
102
+ (0, child_process_1.execSync)(`npx react-native bundle \
98
103
  --platform ${platform} \
99
104
  --dev false \
100
105
  --entry-file index.js \
101
106
  --bundle-output ${bundlePath} \
102
107
  --assets-dest ${assetsDir}`, { stdio: 'inherit' });
103
- console.log('✅ Bundle created:', bundlePath);
104
- // 📎 Create metadata
105
- const bundleBuffer = fs.readFileSync(bundlePath);
106
- const hash = (0, crypto_1.createHash)('sha256').update(bundleBuffer).digest('hex');
107
- const metadata = {
108
- platform,
109
- hash,
110
- timestamp: new Date().toISOString(),
111
- bundlePath: 'main.jsbundle',
112
- sizeInBytes: bundleBuffer.length,
113
- };
114
- if (runtimeVersion) {
115
- metadata.runtimeVersion = runtimeVersion;
116
- }
117
- fs.writeFileSync(metadataPath, JSON.stringify(metadata, null, 2));
118
- console.log('🧠 Metadata saved:', metadataPath);
119
- console.log('📌 Hash:', hash);
120
- // 🗜️ Create zip
121
- console.log('📦 Zipping bundle...');
122
- const zip = new adm_zip_1.default();
123
- zip.addFile('main.jsbundle', bundleBuffer);
124
- zip.addFile(`metadata-${fileSuffix}.json`, Buffer.from(JSON.stringify(metadata, null, 2)));
125
- function addAssetsToZip(dir) {
126
- const items = fs.readdirSync(dir);
127
- for (const item of items) {
128
- const fullPath = path.join(dir, item);
129
- const relPath = path.relative(assetsDir, fullPath);
130
- // Keep the relative path as-is (e.g., drawable-mdpi/img.png) without forcing an "assets/" prefix.
131
- const normalizedPath = relPath;
132
- if (fs.statSync(fullPath).isDirectory()) {
133
- addAssetsToZip(fullPath);
108
+ console.log('✅ Bundle created:', bundlePath);
109
+ const osBin = process.platform === 'darwin'
110
+ ? 'osx-bin'
111
+ : process.platform === 'win32'
112
+ ? 'win64-bin'
113
+ : 'linux64-bin';
114
+ const hermesLocations = [
115
+ path.join(projectRoot, 'node_modules', 'react-native', 'sdks', 'hermesc', osBin, 'hermesc'),
116
+ path.join(projectRoot, 'node_modules', 'hermes-engine', osBin, 'hermesc'),
117
+ ];
118
+ const hermescPath = hermesLocations.find(p => fs.existsSync(p));
119
+ if (hermescPath) {
120
+ console.log(`🔥 Compiling to Hermes bytecode (${platform})...`);
121
+ const hbcPath = bundlePath + '.hbc';
122
+ try {
123
+ (0, child_process_1.execSync)(`"${hermescPath}" -emit-binary -out "${hbcPath}" "${bundlePath}"`, { stdio: 'inherit' });
124
+ fs.renameSync(hbcPath, bundlePath);
125
+ console.log('✅ Hermes bytecode compiled successfully');
134
126
  }
135
- else {
136
- const buffer = fs.readFileSync(fullPath);
137
- zip.addFile(normalizedPath, buffer);
138
- if (isAndroid) {
139
- // Build manifest keys that mirror how RN resolves asset URIs on Android.
140
- // Example normalizedPath: drawable-mdpi/login_background.jpg
141
- const withAssetsPrefix = `assets/${normalizedPath}`;
142
- const manifestKey = normalizedPath.replace(/\.[^.]+$/, '');
143
- const manifestKeyNoPrefix = manifestKey.replace(/^assets\//, '');
144
- const baseNameKey = manifestKey.split('/').pop() || manifestKey;
145
- const baseWithExt = normalizedPath.split('/').pop() || normalizedPath;
146
- imageManifest[manifestKey] = normalizedPath;
147
- imageManifest[manifestKeyNoPrefix] = normalizedPath;
148
- imageManifest[withAssetsPrefix.replace(/\.[^.]+$/, '')] = normalizedPath;
149
- // Add basename aliases to catch cases where the resolver only provides the filename.
150
- imageManifest[baseNameKey] = normalizedPath;
151
- imageManifest[baseWithExt] = normalizedPath;
127
+ catch (e) {
128
+ console.warn('⚠️ Hermes compilation failed, falling back to plain JS bundle:', e.message);
129
+ }
130
+ }
131
+ else {
132
+ console.log('ℹ️ hermesc not found — bundling plain JS (JSC or older RN)');
133
+ }
134
+ const bundleBuffer = fs.readFileSync(bundlePath);
135
+ const hash = (0, crypto_1.createHash)('sha256').update(bundleBuffer).digest('hex');
136
+ const metadata = {
137
+ platform,
138
+ hash,
139
+ timestamp: new Date().toISOString(),
140
+ bundlePath: 'main.jsbundle',
141
+ sizeInBytes: bundleBuffer.length,
142
+ };
143
+ if (runtimeVersion) {
144
+ metadata.runtimeVersion = runtimeVersion;
145
+ }
146
+ fs.writeFileSync(metadataPath, JSON.stringify(metadata, null, 2));
147
+ console.log('🧠 Metadata saved:', metadataPath);
148
+ console.log('📌 Hash:', hash);
149
+ console.log('📦 Zipping bundle...');
150
+ const zip = new adm_zip_1.default();
151
+ zip.addFile('main.jsbundle', bundleBuffer);
152
+ zip.addFile(`metadata-${fileSuffix}.json`, Buffer.from(JSON.stringify(metadata, null, 2)));
153
+ const addAssetsToZip = (dir) => {
154
+ const items = fs.readdirSync(dir);
155
+ for (const item of items) {
156
+ const fullPath = path.join(dir, item);
157
+ const relPath = path.relative(assetsDir, fullPath);
158
+ const normalizedPath = relPath;
159
+ if (fs.statSync(fullPath).isDirectory()) {
160
+ addAssetsToZip(fullPath);
161
+ }
162
+ else {
163
+ const buffer = fs.readFileSync(fullPath);
164
+ zip.addFile(normalizedPath, buffer);
165
+ if (isAndroid) {
166
+ const withAssetsPrefix = `assets/${normalizedPath}`;
167
+ const manifestKey = normalizedPath.replace(/\.[^.]+$/, '');
168
+ const manifestKeyNoPrefix = manifestKey.replace(/^assets\//, '');
169
+ const baseNameKey = manifestKey.split('/').pop() || manifestKey;
170
+ const baseWithExt = normalizedPath.split('/').pop() || normalizedPath;
171
+ imageManifest[manifestKey] = normalizedPath;
172
+ imageManifest[manifestKeyNoPrefix] = normalizedPath;
173
+ imageManifest[withAssetsPrefix.replace(/\.[^.]+$/, '')] = normalizedPath;
174
+ imageManifest[baseNameKey] = normalizedPath;
175
+ imageManifest[baseWithExt] = normalizedPath;
176
+ }
152
177
  }
153
178
  }
179
+ };
180
+ addAssetsToZip(assetsDir);
181
+ if (isAndroid && Object.keys(imageManifest).length > 0) {
182
+ zip.addFile('image-manifest.json', Buffer.from(JSON.stringify(imageManifest, null, 2)));
183
+ console.log(`🧩 Injected image-manifest.json with ${Object.keys(imageManifest).length} entries`);
154
184
  }
185
+ zip.writeZip(zipPath);
186
+ console.log(`✅ OTA bundle zipped: ${zipPath}`);
187
+ return {
188
+ projectRoot,
189
+ outputDir,
190
+ bundlePath,
191
+ metadataPath,
192
+ zipPath,
193
+ runtimeVersion,
194
+ hash,
195
+ };
155
196
  }
156
- addAssetsToZip(assetsDir);
157
- // 🧩 Inject manifest (Android only)
158
- if (isAndroid && Object.keys(imageManifest).length > 0) {
159
- zip.addFile('image-manifest.json', Buffer.from(JSON.stringify(imageManifest, null, 2)));
160
- console.log(`🧩 Injected image-manifest.json with ${Object.keys(imageManifest).length} entries`);
197
+ if (require.main === module) {
198
+ runBundleScript();
161
199
  }
162
- zip.writeZip(zipPath);
163
- console.log(`✅ OTA bundle zipped: ${zipPath}`);
@@ -1,2 +1,5 @@
1
1
  #!/usr/bin/env node
2
- export {};
2
+ export declare function runDownloadBundle(options?: {
3
+ argv?: string[];
4
+ cwd?: string;
5
+ }): Promise<string>;
@@ -37,41 +37,46 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
37
37
  return (mod && mod.__esModule) ? mod : { "default": mod };
38
38
  };
39
39
  Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.runDownloadBundle = runDownloadBundle;
40
41
  const axios_1 = __importDefault(require("axios"));
41
42
  const fs = __importStar(require("fs"));
42
43
  const path = __importStar(require("path"));
43
- const packageRoot = path.resolve(__dirname, '..', '..');
44
- const outputDir = path.join(packageRoot, 'dist');
45
- const platform = process.argv[2];
46
- if (!platform || !['ios', 'android'].includes(platform)) {
47
- console.error('❌ Please provide platform: ios or android');
48
- process.exit(1);
49
- }
50
- // Dynamically load config from project root
51
- const projectRoot = process.cwd();
52
- const configPath = path.resolve(projectRoot, 'bundle.drop.config.js');
53
- if (!fs.existsSync(configPath)) {
54
- console.error('❌ bundle.drop.config.js not found in project root');
55
- process.exit(1);
56
- }
57
- // eslint-disable-next-line
58
- const config = require(configPath);
59
- const { serverUrl, project } = config;
60
- if (!project?.slug) {
61
- console.error('❌ Missing "project.slug" in bundle.drop.config.js');
62
- process.exit(1);
63
- }
64
- const runtimeVersion = config?.runtimeVersion?.[platform] || config?.runtimeVersion?.[platform];
65
- const channelName = process.argv[3] || config?.defaultChannel || 'General';
66
- const resolveEndpoint = `${serverUrl}/projects/${encodeURIComponent(project.slug)}/ota/resolve`;
67
- const outputPath = path.join(outputDir, `main.${platform}.jsbundle`);
68
- if (!fs.existsSync(outputDir)) {
69
- fs.mkdirSync(outputDir, { recursive: true });
70
- }
71
- const authHeaders = {
72
- ...(project?.apiKey ? { 'x-api-key': project.apiKey } : {}),
73
- };
74
- async function downloadLatestBundle() {
44
+ const getPackageRoot = () => process.env.BUNDLE_DROP_PACKAGE_ROOT_OVERRIDE || path.resolve(__dirname, '..', '..');
45
+ async function runDownloadBundle(options) {
46
+ const outputDir = path.join(getPackageRoot(), 'dist');
47
+ const argv = options?.argv || process.argv;
48
+ const platform = argv[2];
49
+ if (!platform || !['ios', 'android'].includes(platform)) {
50
+ console.error('❌ Please provide platform: ios or android');
51
+ process.exit(1);
52
+ }
53
+ const projectRoot = options?.cwd || process.cwd();
54
+ const configPath = path.resolve(projectRoot, 'bundle.drop.config.js');
55
+ if (!fs.existsSync(configPath)) {
56
+ console.error('❌ bundle.drop.config.js not found in project root');
57
+ process.exit(1);
58
+ }
59
+ // eslint-disable-next-line
60
+ const config = require(configPath);
61
+ const { serverUrl, project } = config;
62
+ if (!serverUrl) {
63
+ console.error('❌ Missing "serverUrl" in bundle.drop.config.js');
64
+ process.exit(1);
65
+ }
66
+ if (!project?.slug) {
67
+ console.error('❌ Missing "project.slug" in bundle.drop.config.js');
68
+ process.exit(1);
69
+ }
70
+ const runtimeVersion = config?.runtimeVersion?.[platform] || config?.runtimeVersion?.[platform];
71
+ const channelName = argv[3] || config?.defaultChannel || 'General';
72
+ const resolveEndpoint = `${serverUrl}/projects/${encodeURIComponent(project.slug)}/ota/resolve`;
73
+ const outputPath = path.join(outputDir, `main.${platform}.jsbundle`);
74
+ if (!fs.existsSync(outputDir)) {
75
+ fs.mkdirSync(outputDir, { recursive: true });
76
+ }
77
+ const authHeaders = {
78
+ ...(project?.apiKey ? { 'x-api-key': project.apiKey } : {}),
79
+ };
75
80
  try {
76
81
  console.log(`⬇️ Resolving OTA target from: ${resolveEndpoint}`);
77
82
  const resolveResponse = await axios_1.default.post(resolveEndpoint, {
@@ -98,10 +103,13 @@ async function downloadLatestBundle() {
98
103
  const bundleResponse = await axios_1.default.get(bundleDownloadUrl, { responseType: 'arraybuffer' });
99
104
  await fs.promises.writeFile(outputPath, Buffer.from(bundleResponse.data));
100
105
  console.log(`✅ Bundle downloaded and saved to: ${outputPath}`);
106
+ return outputPath;
101
107
  }
102
108
  catch (err) {
103
109
  console.error('❌ Download failed:', err.response?.data || err.message || err);
104
110
  process.exit(1);
105
111
  }
106
112
  }
107
- downloadLatestBundle();
113
+ if (require.main === module) {
114
+ runDownloadBundle();
115
+ }
@@ -1,2 +1,8 @@
1
1
  #!/usr/bin/env node
2
- export {};
2
+ export declare function findProjectRoot(startDir: string): string;
3
+ export declare function parseAndroidVersionFromGradle(filePath: string): string;
4
+ export declare const cleanupArtifacts: (platform: string, zipPath: string) => void;
5
+ export declare function runUploadBundle(options?: {
6
+ argv?: string[];
7
+ cwd?: string;
8
+ }): Promise<any>;