@gfean/react-native-bundle-drop 0.4.6 → 0.5.1

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.
package/lib/CLI/cli.js CHANGED
@@ -12,6 +12,7 @@ const fs_1 = __importDefault(require("fs"));
12
12
  const os_1 = __importDefault(require("os"));
13
13
  const path_1 = __importDefault(require("path"));
14
14
  const upload_cli_1 = __importDefault(require("./scripts/upload-cli"));
15
+ const sight_cli_1 = require("./scripts/sight-cli");
15
16
  const post_init_1 = require("./scripts/post-init");
16
17
  const logo_1 = require("./logo");
17
18
  const package_json_1 = __importDefault(require("../../package.json"));
@@ -20,10 +21,23 @@ const DEFAULT_SERVER_URL = 'https://api.bundledrop.app';
20
21
  const DOCS_CLI_URL = 'https://bundledrop.app/docs/cli';
21
22
  const DOCS_UPLOADING_URL = 'https://bundledrop.app/docs/uploading';
22
23
  const DOCS_CI_CD_URL = 'https://bundledrop.app/docs/ci-cd';
23
- const DOCS_INSTALLATION_URL = 'https://bundledrop.app/docs/installation';
24
- const setupErrorWithManualInstallation = (error) => {
24
+ const DOCS_MANUAL_SETUP_URL = 'https://bundledrop.app/docs/manual-setup';
25
+ const setupErrorWithManualSetup = (error) => {
25
26
  const message = error instanceof Error ? error.message : String(error);
26
- return new Error(`${message}\nManual installation: ${DOCS_INSTALLATION_URL}`);
27
+ return new Error(`${message}\nManual setup: ${DOCS_MANUAL_SETUP_URL}`);
28
+ };
29
+ const runSetupWithManualFallback = async (params) => {
30
+ try {
31
+ await (0, post_init_1.runPostInitPrompts)(params.options);
32
+ }
33
+ catch (error) {
34
+ if (params.preservePendingConfig &&
35
+ params.pendingConfig &&
36
+ !fs_1.default.existsSync(params.pendingConfig.configPath)) {
37
+ await fs_1.default.promises.writeFile(params.pendingConfig.configPath, params.pendingConfig.content, 'utf8');
38
+ }
39
+ throw setupErrorWithManualSetup(error);
40
+ }
27
41
  };
28
42
  const getTokenPath = () => path_1.default.join(os_1.default.homedir(), '.bundle-drop', 'auth.json');
29
43
  const normalizeServerUrl = (url) => url?.replace(/\/$/, '') || DEFAULT_SERVER_URL;
@@ -96,6 +110,7 @@ ${chalk_1.default.bold.cyan('Common Usage:')}
96
110
  ${chalk_1.default.gray('bundle-drop login')}
97
111
  ${chalk_1.default.gray('bundle-drop init')}
98
112
  ${chalk_1.default.gray('bundle-drop doctor')}
113
+ ${chalk_1.default.gray('bundle-drop sight')}
99
114
  ${chalk_1.default.gray('bundle-drop doctor --project-type bare --platform android')}
100
115
  ${chalk_1.default.gray('bundle-drop upload android --version 1.2.3 --channel develop')}
101
116
  ${chalk_1.default.gray('bundle-drop upload ios --plist-file ios/Info.plist --channel develop')}
@@ -104,6 +119,23 @@ ${chalk_1.default.bold.cyan('Common Usage:')}
104
119
  ${chalk_1.default.gray('Docs →')} ${chalk_1.default.underline.gray(DOCS_CLI_URL)}
105
120
  ${chalk_1.default.gray('Uploading →')} ${chalk_1.default.underline.gray(DOCS_UPLOADING_URL)}
106
121
  ${chalk_1.default.gray('CI/CD →')} ${chalk_1.default.underline.gray(DOCS_CI_CD_URL)}\n`);
122
+ program
123
+ .command('sight')
124
+ .option('--platform <platform>', 'Platform to analyze: ios or android')
125
+ .option('--project-type <type>', 'Force project type: expo or bare')
126
+ .option('--entry-file <path>', 'Override the React Native entry file')
127
+ .option('--no-open', 'Keep the generated files and do not open the browser')
128
+ .option('--keep', 'Keep generated files after the browser loads them')
129
+ .option('--output <path>', 'Generate persistent files in an empty directory')
130
+ .description('Generate a production bundle and inspect it locally in Bundle Drop Sight')
131
+ .addHelpText('after', `
132
+ ${chalk_1.default.bold('Examples:')}
133
+ ${chalk_1.default.gray('bundle-drop sight')}
134
+ ${chalk_1.default.gray('bundle-drop sight --platform android')}
135
+ ${chalk_1.default.gray('bundle-drop sight --platform ios --keep')}
136
+ ${chalk_1.default.gray('bundle-drop sight --no-open --output ./sight-analysis')}
137
+ `)
138
+ .action(sight_cli_1.runSightCommand);
107
139
  program
108
140
  .command('upload <platform>')
109
141
  .option('--plist-file <path>', 'Path to Info.plist for iOS')
@@ -156,91 +188,95 @@ ${chalk_1.default.gray('CI/CD docs →')} ${chalk_1.default.underline.gray(DOCS_
156
188
  .option('--yes', 'Approve ordinary setup changes noninteractively')
157
189
  .description('Configure Bundle Drop for Expo or bare React Native')
158
190
  .action(async (options) => {
159
- try {
160
- if (options.projectType && !['expo', 'bare'].includes(options.projectType)) {
161
- throw new Error('--project-type must be expo or bare.');
162
- }
163
- if (options.token) {
164
- const { detectProjectType } = require('../expo');
165
- const projectType = detectProjectType({
166
- projectRoot: process.cwd(),
167
- explicitType: options.projectType,
168
- });
169
- const serverUrl = normalizeServerUrl(process.env.BUNDLE_DROP_SERVER_URL);
170
- const tokenContext = await fetchFreshAuthContext({
171
- serverUrl,
172
- token: options.token,
173
- });
174
- const initConfigModule = require('../CLI/scripts/init-config');
175
- const hadConfig = initConfigModule.hasExistingBundleDropConfig();
176
- const configResult = await initConfigModule.initConfig({
177
- serverUrl,
178
- projects: tokenContext?.projects || [],
179
- organizations: tokenContext?.organizations || [],
180
- downloadApiKey: '',
181
- authToken: options.token,
182
- dryRun: true,
183
- projectType,
184
- });
185
- await (0, post_init_1.runPostInitPrompts)({
186
- ...options,
187
- projectType,
188
- ...(!hadConfig && configResult
189
- ? {
190
- virtualConfig: {
191
- content: configResult.content,
192
- serverUrl: configResult.serverUrl,
193
- orgSlug: configResult.orgSlug,
194
- projectSlug: configResult.projectSlug,
195
- authToken: options.token,
196
- },
197
- }
198
- : {}),
199
- });
200
- return;
201
- }
202
- const authState = readStoredAuthData();
203
- if (!authState.exists) {
204
- console.log('ℹ️ Not logged in. Please run `bundle-drop login` or use --token.\n' +
205
- `CLI docs: ${DOCS_CLI_URL}\n` +
206
- `CI/CD docs: ${DOCS_CI_CD_URL}`);
207
- return;
208
- }
209
- if (authState.isInvalid || !authState.data) {
210
- logInvalidAuthFile();
211
- return;
212
- }
213
- const data = authState.data;
214
- if (!data.token) {
215
- logInvalidAuthFile();
216
- return;
217
- }
191
+ if (options.projectType && !['expo', 'bare'].includes(options.projectType)) {
192
+ throw new Error('--project-type must be expo or bare.');
193
+ }
194
+ if (options.token) {
218
195
  const { detectProjectType } = require('../expo');
219
196
  const projectType = detectProjectType({
220
197
  projectRoot: process.cwd(),
221
198
  explicitType: options.projectType,
222
199
  });
223
- const serverUrl = normalizeServerUrl(data.serverUrl || data.baseUrl || process.env.BUNDLE_DROP_SERVER_URL);
224
- const freshContext = await fetchFreshAuthContext({
200
+ const serverUrl = normalizeServerUrl(process.env.BUNDLE_DROP_SERVER_URL);
201
+ const tokenContext = await fetchFreshAuthContext({
225
202
  serverUrl,
226
- token: data.token,
203
+ token: options.token,
227
204
  });
228
- const initData = freshContext ? { ...data, ...freshContext } : data;
229
- if (freshContext) {
230
- writeStoredAuthData(authState.tokenPath, initData);
231
- }
232
205
  const initConfigModule = require('../CLI/scripts/init-config');
233
206
  const hadConfig = initConfigModule.hasExistingBundleDropConfig();
234
207
  const configResult = await initConfigModule.initConfig({
235
208
  serverUrl,
236
- projects: initData.projects || [],
237
- organizations: initData.organizations || [],
238
- downloadApiKey: data.downloadApiKey || '',
239
- authToken: data.token,
209
+ projects: tokenContext?.projects || [],
210
+ organizations: tokenContext?.organizations || [],
211
+ downloadApiKey: '',
212
+ authToken: options.token,
240
213
  dryRun: true,
241
214
  projectType,
242
215
  });
243
- await (0, post_init_1.runPostInitPrompts)({
216
+ await runSetupWithManualFallback({
217
+ options: {
218
+ ...options,
219
+ projectType,
220
+ ...(!hadConfig && configResult
221
+ ? {
222
+ virtualConfig: {
223
+ content: configResult.content,
224
+ serverUrl: configResult.serverUrl,
225
+ orgSlug: configResult.orgSlug,
226
+ projectSlug: configResult.projectSlug,
227
+ authToken: options.token,
228
+ },
229
+ }
230
+ : {}),
231
+ },
232
+ pendingConfig: configResult || undefined,
233
+ preservePendingConfig: !hadConfig && !options.dryRun,
234
+ });
235
+ return;
236
+ }
237
+ const authState = readStoredAuthData();
238
+ if (!authState.exists) {
239
+ console.log('ℹ️ Not logged in. Please run `bundle-drop login` or use --token.\n' +
240
+ `CLI docs: ${DOCS_CLI_URL}\n` +
241
+ `CI/CD docs: ${DOCS_CI_CD_URL}`);
242
+ return;
243
+ }
244
+ if (authState.isInvalid || !authState.data) {
245
+ logInvalidAuthFile();
246
+ return;
247
+ }
248
+ const data = authState.data;
249
+ if (!data.token) {
250
+ logInvalidAuthFile();
251
+ return;
252
+ }
253
+ const { detectProjectType } = require('../expo');
254
+ const projectType = detectProjectType({
255
+ projectRoot: process.cwd(),
256
+ explicitType: options.projectType,
257
+ });
258
+ const serverUrl = normalizeServerUrl(data.serverUrl || data.baseUrl || process.env.BUNDLE_DROP_SERVER_URL);
259
+ const freshContext = await fetchFreshAuthContext({
260
+ serverUrl,
261
+ token: data.token,
262
+ });
263
+ const initData = freshContext ? { ...data, ...freshContext } : data;
264
+ if (freshContext) {
265
+ writeStoredAuthData(authState.tokenPath, initData);
266
+ }
267
+ const initConfigModule = require('../CLI/scripts/init-config');
268
+ const hadConfig = initConfigModule.hasExistingBundleDropConfig();
269
+ const configResult = await initConfigModule.initConfig({
270
+ serverUrl,
271
+ projects: initData.projects || [],
272
+ organizations: initData.organizations || [],
273
+ downloadApiKey: data.downloadApiKey || '',
274
+ authToken: data.token,
275
+ dryRun: true,
276
+ projectType,
277
+ });
278
+ await runSetupWithManualFallback({
279
+ options: {
244
280
  ...options,
245
281
  projectType,
246
282
  ...(!hadConfig && configResult
@@ -254,11 +290,10 @@ ${chalk_1.default.gray('CI/CD docs →')} ${chalk_1.default.underline.gray(DOCS_
254
290
  },
255
291
  }
256
292
  : {}),
257
- });
258
- }
259
- catch (error) {
260
- throw setupErrorWithManualInstallation(error);
261
- }
293
+ },
294
+ pendingConfig: configResult || undefined,
295
+ preservePendingConfig: !hadConfig && !options.dryRun,
296
+ });
262
297
  });
263
298
  program
264
299
  .command('doctor')
@@ -22,6 +22,7 @@ const scanner_1 = require("./scanner");
22
22
  const validate_plan_1 = require("./validate-plan");
23
23
  const ui_1 = require("../../utils/ui");
24
24
  const PACKAGE_NAME = '@gfean/react-native-bundle-drop';
25
+ const DOCS_MANUAL_SETUP_URL = 'https://bundledrop.app/docs/manual-setup';
25
26
  const EXPO_RUNTIME_AUTHORITY_PATTERN = /runtimeVersion\s*:\s*\{\s*source\s*:\s*['"]expo['"]\s*\}/;
26
27
  const sha256 = (content) => crypto_1.default.createHash('sha256').update(content).digest('hex');
27
28
  const shouldApplyAiChange = (change) => change.confidence !== 'low' &&
@@ -190,7 +191,15 @@ async function initProjectConfigAi(options = {}) {
190
191
  console.log(chalk_1.default.gray(` - ${action.type}${confirmation}: ${action.reason}`));
191
192
  });
192
193
  if (plan.confidence === 'low') {
193
- console.log(chalk_1.default.yellow('AI confidence is low. No files changed.'));
194
+ if (options.virtualConfig && !options.dryRun) {
195
+ const configPath = path_1.default.join(projectRoot, 'bundle.drop.config.js');
196
+ if (!fs_extra_1.default.existsSync(configPath)) {
197
+ fs_extra_1.default.writeFileSync(configPath, options.virtualConfig.content, 'utf8');
198
+ console.log(chalk_1.default.green(`Project config retained at ${configPath}`));
199
+ }
200
+ }
201
+ console.log(chalk_1.default.yellow('AI confidence is low. Native and Expo setup files were not changed.'));
202
+ console.log(chalk_1.default.gray(`Manual setup: ${DOCS_MANUAL_SETUP_URL}`));
194
203
  return;
195
204
  }
196
205
  if (projectType === 'expo' && scan.request.detected.expoUpdatesStatus === 'active') {
@@ -16,6 +16,50 @@ const DOCS_INSTALLATION_URL = 'https://bundledrop.app/docs/installation';
16
16
  function normalizeServerUrl(url) {
17
17
  return url.replace(/\/$/, '');
18
18
  }
19
+ function createBundleDropConfig(values) {
20
+ const projectTypeConfig = values.projectType
21
+ ? ` projectType: ${JSON.stringify(values.projectType)},\n`
22
+ : '';
23
+ return `module.exports = {
24
+ ${projectTypeConfig} serverUrl: ${JSON.stringify(values.serverUrl)},
25
+ defaultChannel: 'develop',
26
+ runtimeVersion: {
27
+ ios: '1.0.0',
28
+ android: '1.0.0',
29
+ },
30
+ org: {
31
+ slug: ${JSON.stringify(values.orgSlug)},
32
+ },
33
+ project: {
34
+ name: ${JSON.stringify(values.projectName)},
35
+ slug: ${JSON.stringify(values.projectSlug)},
36
+ apiKey: ${JSON.stringify(values.apiKey)},
37
+ },
38
+ };
39
+ `;
40
+ }
41
+ function createRedactedBundleDropConfigPreview(values) {
42
+ const projectTypeConfig = values.projectType
43
+ ? ` projectType: ${JSON.stringify(values.projectType)},\n`
44
+ : '';
45
+ return `module.exports = {
46
+ ${projectTypeConfig} serverUrl: ${JSON.stringify(values.serverUrl)},
47
+ defaultChannel: 'develop',
48
+ runtimeVersion: {
49
+ ios: '1.0.0',
50
+ android: '1.0.0',
51
+ },
52
+ org: {
53
+ slug: ${JSON.stringify(values.orgSlug)},
54
+ },
55
+ project: {
56
+ name: ${JSON.stringify(values.projectName)},
57
+ slug: ${JSON.stringify(values.projectSlug)},
58
+ apiKey: "<redacted>",
59
+ },
60
+ };
61
+ `;
62
+ }
19
63
  async function fetchProjectCredentials(params) {
20
64
  const baseUrl = normalizeServerUrl(params.serverUrl);
21
65
  const url = `${baseUrl}/projects/${encodeURIComponent(params.projectSlug)}/credentials`;
@@ -147,29 +191,24 @@ async function initConfig(params) {
147
191
  else if (projectSlug && !params.authToken && !apiKey) {
148
192
  console.log(chalk_1.default.yellow('⚠️ Missing auth token; cannot fetch project API key.'));
149
193
  }
150
- const projectTypeConfig = params.projectType
151
- ? ` projectType: '${params.projectType}',\n`
152
- : '';
153
- const runtimeVersionConfig = ` runtimeVersion: {
154
- ios: '1.0.0',
155
- android: '1.0.0',
156
- },`;
157
- const content = `module.exports = {
158
- ${projectTypeConfig} serverUrl: '${resolvedServerUrl}',
159
- defaultChannel: 'develop',
160
- ${runtimeVersionConfig}
161
- org: {
162
- slug: '${orgSlug}',
163
- },
164
- project: {
165
- name: '${projectName.replace(/'/g, "\\'")}',
166
- slug: '${projectSlug}',
167
- apiKey: '${apiKey.replace(/'/g, "\\'")}',
168
- },
169
- };
170
- `;
194
+ const configValues = {
195
+ projectType: params.projectType,
196
+ serverUrl: resolvedServerUrl,
197
+ orgSlug,
198
+ projectName,
199
+ projectSlug,
200
+ apiKey,
201
+ };
202
+ const content = createBundleDropConfig(configValues);
171
203
  if (params.dryRun) {
172
- console.log(chalk_1.default.cyan(`Dry-run bundle.drop.config.js preview:\n${content}`));
204
+ const previewContent = createRedactedBundleDropConfigPreview({
205
+ projectType: params.projectType,
206
+ serverUrl: resolvedServerUrl,
207
+ orgSlug,
208
+ projectName,
209
+ projectSlug,
210
+ });
211
+ console.log(chalk_1.default.cyan(`Dry-run bundle.drop.config.js preview:\n${previewContent}`));
173
212
  }
174
213
  else {
175
214
  await fs_extra_1.default.writeFile(configPath, content, 'utf8');
@@ -16,7 +16,7 @@ const init_config_1 = require("./init-config");
16
16
  const post_init_1 = require("./post-init");
17
17
  const expo_1 = require("../../expo");
18
18
  const LOGIN_TIMEOUT_MS = 10 * 60 * 1000;
19
- const DOCS_INSTALLATION_URL = 'https://bundledrop.app/docs/installation';
19
+ const DOCS_MANUAL_SETUP_URL = 'https://bundledrop.app/docs/manual-setup';
20
20
  const getBaseUrl = () => process.env.BUNDLE_DROP_SERVER_URL
21
21
  ? process.env.BUNDLE_DROP_SERVER_URL.replace(/\/$/, '')
22
22
  : 'https://api.bundledrop.app';
@@ -45,7 +45,7 @@ const openBrowser = async (url) => {
45
45
  const command = platform === 'darwin'
46
46
  ? { file: 'open', args: [url] }
47
47
  : platform === 'win32'
48
- ? { file: 'cmd', args: ['/c', 'start', '', url] }
48
+ ? { file: 'explorer.exe', args: [url] }
49
49
  : { file: 'xdg-open', args: [url] };
50
50
  await new Promise((resolve, reject) => {
51
51
  const child = (0, child_process_1.spawn)(command.file, command.args, {
@@ -286,16 +286,16 @@ const login = async () => {
286
286
  await (0, post_init_1.runPostInitPrompts)({ projectType });
287
287
  }
288
288
  catch (error) {
289
- if (createdConfigPath) {
290
- await fs_extra_1.default.remove(createdConfigPath);
291
- }
292
289
  const message = axios_1.default.isAxiosError(error)
293
290
  ? error.response?.data?.error || error.message
294
291
  : error.message;
295
292
  const failureLabel = loginCompleted ? '❌ Setup failed after login:' : '❌ Login failed:';
296
293
  console.error(chalk_1.default.red(failureLabel), message);
297
294
  if (loginCompleted) {
298
- console.error(chalk_1.default.gray(`Manual installation: ${DOCS_INSTALLATION_URL}`));
295
+ if (createdConfigPath) {
296
+ console.error(chalk_1.default.gray(`Project config retained at ${createdConfigPath}`));
297
+ }
298
+ console.error(chalk_1.default.gray(`Manual setup: ${DOCS_MANUAL_SETUP_URL}`));
299
299
  }
300
300
  process.exitCode = 1;
301
301
  }
@@ -0,0 +1,17 @@
1
+ import type { MobilePlatform, ProjectType } from '../../expo';
2
+ export type SightArtifacts = {
3
+ outputDirectory: string;
4
+ bundlePath: string;
5
+ sourceMapPath: string;
6
+ temporary: boolean;
7
+ };
8
+ export type GenerateSightArtifactsOptions = {
9
+ projectRoot: string;
10
+ projectType: ProjectType;
11
+ platform: MobilePlatform;
12
+ output?: string;
13
+ keep?: boolean;
14
+ entryFile?: string;
15
+ };
16
+ export declare function validateSightArtifacts(bundlePath: string, sourceMapPath: string): void;
17
+ export declare function generateSightArtifacts({ projectRoot, projectType, platform, output, keep, entryFile: explicitEntryFile, }: GenerateSightArtifactsOptions): Promise<SightArtifacts>;
@@ -0,0 +1,204 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.validateSightArtifacts = validateSightArtifacts;
7
+ exports.generateSightArtifacts = generateSightArtifacts;
8
+ const child_process_1 = require("child_process");
9
+ const fs_1 = __importDefault(require("fs"));
10
+ const os_1 = __importDefault(require("os"));
11
+ const path_1 = __importDefault(require("path"));
12
+ const module_1 = require("module");
13
+ const HERMES_BYTECODE_MAGIC = Buffer.from([0xc6, 0x1f, 0xbc, 0x03, 0xc1, 0x03, 0x19, 0x1f]);
14
+ function ensureOutputDirectory(projectRoot, requestedOutput, keep) {
15
+ if (!requestedOutput && !keep) {
16
+ return {
17
+ outputDirectory: fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), 'bundle-drop-sight-')),
18
+ temporary: true,
19
+ };
20
+ }
21
+ const outputDirectory = requestedOutput
22
+ ? path_1.default.resolve(projectRoot, requestedOutput)
23
+ : path_1.default.join(projectRoot, '.bundle-drop', 'sight', new Date().toISOString().replace(/[:.]/g, '-'));
24
+ if (fs_1.default.existsSync(outputDirectory)) {
25
+ const stats = fs_1.default.lstatSync(outputDirectory);
26
+ if (!stats.isDirectory() || stats.isSymbolicLink()) {
27
+ throw new Error(`Sight output must be a real directory: ${outputDirectory}`);
28
+ }
29
+ if (fs_1.default.readdirSync(outputDirectory).length > 0) {
30
+ throw new Error(`Sight output directory must be empty: ${outputDirectory}`);
31
+ }
32
+ }
33
+ else {
34
+ fs_1.default.mkdirSync(outputDirectory, { recursive: true, mode: 0o755 });
35
+ }
36
+ return { outputDirectory, temporary: false };
37
+ }
38
+ function resolveProjectModule(projectRoot, moduleId) {
39
+ const manifestPath = path_1.default.join(projectRoot, 'package.json');
40
+ if (!fs_1.default.existsSync(manifestPath)) {
41
+ throw new Error(`No package.json was found at ${manifestPath}.`);
42
+ }
43
+ try {
44
+ return (0, module_1.createRequire)(manifestPath).resolve(moduleId);
45
+ }
46
+ catch {
47
+ throw new Error(`Could not resolve ${moduleId} from ${projectRoot}. Install dependencies and try again.`);
48
+ }
49
+ }
50
+ function resolveExpoModule(projectRoot, moduleId) {
51
+ const expoManifest = resolveProjectModule(projectRoot, 'expo/package.json');
52
+ try {
53
+ return (0, module_1.createRequire)(expoManifest).resolve(moduleId);
54
+ }
55
+ catch {
56
+ throw new Error(`The project-local Expo installation could not resolve ${moduleId}.`);
57
+ }
58
+ }
59
+ function resolveBareEntryFile(projectRoot, explicitEntryFile) {
60
+ const candidates = explicitEntryFile
61
+ ? [explicitEntryFile]
62
+ : ['index.js', 'index.ts', 'index.tsx', 'index.jsx'];
63
+ const entryFile = candidates
64
+ .map(candidate => path_1.default.resolve(projectRoot, candidate))
65
+ .find(candidate => fs_1.default.existsSync(candidate) && fs_1.default.statSync(candidate).isFile());
66
+ if (!entryFile) {
67
+ throw new Error('Could not find a React Native entry file. Pass it explicitly with --entry-file <path>.');
68
+ }
69
+ return entryFile;
70
+ }
71
+ function resolveExpoEntryFile(projectRoot, platform) {
72
+ const configPathsPath = resolveExpoModule(projectRoot, '@expo/config/paths');
73
+ const configPaths = (0, module_1.createRequire)(path_1.default.join(projectRoot, 'package.json'))(configPathsPath);
74
+ const entryFile = configPaths.resolveEntryPoint?.(projectRoot, { platform });
75
+ if (!entryFile) {
76
+ throw new Error(`Expo could not resolve the ${platform} entrypoint.`);
77
+ }
78
+ return path_1.default.isAbsolute(entryFile) ? entryFile : path_1.default.resolve(projectRoot, entryFile);
79
+ }
80
+ function runMetroCommand(projectRoot, cliPath, args) {
81
+ return new Promise((resolve, reject) => {
82
+ const child = (0, child_process_1.spawn)(process.execPath, [cliPath, ...args], {
83
+ cwd: projectRoot,
84
+ env: { ...process.env, NODE_ENV: 'production' },
85
+ stdio: 'inherit',
86
+ });
87
+ child.once('error', reject);
88
+ child.once('exit', (code, signal) => {
89
+ if (code === 0) {
90
+ resolve();
91
+ return;
92
+ }
93
+ reject(new Error(`Metro bundle generation failed${signal ? ` with signal ${signal}` : ` with exit code ${code}`}.`));
94
+ });
95
+ });
96
+ }
97
+ function sourceMapDebugId(sourceMap) {
98
+ const value = sourceMap.debugId ?? sourceMap.debug_id;
99
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
100
+ }
101
+ function bundleDebugId(bundle) {
102
+ return bundle.match(/^\/\/[#@]\s*debugId=([^\s]+)\s*$/m)?.[1] ?? null;
103
+ }
104
+ function validateSightArtifacts(bundlePath, sourceMapPath) {
105
+ for (const artifactPath of [bundlePath, sourceMapPath]) {
106
+ if (!fs_1.default.existsSync(artifactPath) ||
107
+ !fs_1.default.lstatSync(artifactPath).isFile() ||
108
+ fs_1.default.lstatSync(artifactPath).isSymbolicLink()) {
109
+ throw new Error(`Sight generation did not create ${artifactPath}.`);
110
+ }
111
+ }
112
+ const bundleBuffer = fs_1.default.readFileSync(bundlePath);
113
+ if (bundleBuffer.length === 0) {
114
+ throw new Error('Sight cannot analyze an empty JavaScript bundle.');
115
+ }
116
+ if (bundleBuffer.subarray(0, HERMES_BYTECODE_MAGIC.length).equals(HERMES_BYTECODE_MAGIC)) {
117
+ throw new Error('Sight requires a JavaScript bundle, but Metro generated Hermes bytecode.');
118
+ }
119
+ let sourceMap;
120
+ try {
121
+ sourceMap = JSON.parse(fs_1.default.readFileSync(sourceMapPath, 'utf8'));
122
+ }
123
+ catch {
124
+ throw new Error('Metro generated an invalid source-map JSON file.');
125
+ }
126
+ if (sourceMap.version !== 3 ||
127
+ !Array.isArray(sourceMap.sources) ||
128
+ typeof sourceMap.mappings !== 'string') {
129
+ throw new Error('Sight requires a source-map version 3 file with sources and mappings.');
130
+ }
131
+ const bundle = bundleBuffer.toString('utf8');
132
+ const sourceMapReference = bundle.match(/^[/#@\s]*sourceMappingURL=([^\s]+)\s*$/m)?.[1];
133
+ if (sourceMapReference && path_1.default.basename(sourceMapReference) !== path_1.default.basename(sourceMapPath)) {
134
+ throw new Error('The generated bundle references a different source-map file.');
135
+ }
136
+ if (typeof sourceMap.file === 'string' &&
137
+ sourceMap.file.trim() &&
138
+ path_1.default.basename(sourceMap.file) !== path_1.default.basename(bundlePath)) {
139
+ throw new Error('The generated source map references a different bundle file.');
140
+ }
141
+ const mapDebugId = sourceMapDebugId(sourceMap);
142
+ const generatedBundleDebugId = bundleDebugId(bundle);
143
+ if (mapDebugId && generatedBundleDebugId && mapDebugId !== generatedBundleDebugId) {
144
+ throw new Error('The generated bundle and source map have different debug IDs.');
145
+ }
146
+ }
147
+ async function generateSightArtifacts({ projectRoot, projectType, platform, output, keep = false, entryFile: explicitEntryFile, }) {
148
+ const absoluteProjectRoot = path_1.default.resolve(projectRoot);
149
+ const { outputDirectory, temporary } = ensureOutputDirectory(absoluteProjectRoot, output, keep);
150
+ const bundlePath = path_1.default.join(outputDirectory, `main.${platform}.jsbundle`);
151
+ const sourceMapPath = `${bundlePath}.map`;
152
+ try {
153
+ if (projectType === 'expo') {
154
+ const cliPath = resolveExpoModule(absoluteProjectRoot, '@expo/cli');
155
+ const entryFile = explicitEntryFile
156
+ ? path_1.default.resolve(absoluteProjectRoot, explicitEntryFile)
157
+ : resolveExpoEntryFile(absoluteProjectRoot, platform);
158
+ const assetsDirectory = path_1.default.join(outputDirectory, 'assets');
159
+ fs_1.default.mkdirSync(assetsDirectory, { recursive: true, mode: 0o755 });
160
+ await runMetroCommand(absoluteProjectRoot, cliPath, [
161
+ 'export:embed',
162
+ '--platform',
163
+ platform,
164
+ '--entry-file',
165
+ entryFile,
166
+ '--bundle-output',
167
+ bundlePath,
168
+ '--sourcemap-output',
169
+ sourceMapPath,
170
+ '--assets-dest',
171
+ assetsDirectory,
172
+ '--dev',
173
+ 'false',
174
+ '--minify',
175
+ 'true',
176
+ ]);
177
+ }
178
+ else {
179
+ const cliPath = resolveProjectModule(absoluteProjectRoot, 'react-native/cli.js');
180
+ const entryFile = resolveBareEntryFile(absoluteProjectRoot, explicitEntryFile);
181
+ await runMetroCommand(absoluteProjectRoot, cliPath, [
182
+ 'bundle',
183
+ '--platform',
184
+ platform,
185
+ '--dev',
186
+ 'false',
187
+ '--entry-file',
188
+ entryFile,
189
+ '--bundle-output',
190
+ bundlePath,
191
+ '--sourcemap-output',
192
+ sourceMapPath,
193
+ ]);
194
+ }
195
+ validateSightArtifacts(bundlePath, sourceMapPath);
196
+ return { outputDirectory, bundlePath, sourceMapPath, temporary };
197
+ }
198
+ catch (error) {
199
+ if (temporary) {
200
+ fs_1.default.rmSync(outputDirectory, { recursive: true, force: true });
201
+ }
202
+ throw error;
203
+ }
204
+ }
@@ -0,0 +1,10 @@
1
+ import type { MobilePlatform, ProjectType } from '../../expo';
2
+ export type SightCommandOptions = {
3
+ platform?: MobilePlatform;
4
+ projectType?: ProjectType;
5
+ open?: boolean;
6
+ keep?: boolean;
7
+ output?: string;
8
+ entryFile?: string;
9
+ };
10
+ export declare function runSightCommand(options: SightCommandOptions): Promise<void>;
@@ -0,0 +1,127 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.runSightCommand = runSightCommand;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const chalk_1 = __importDefault(require("chalk"));
10
+ const prompts_1 = __importDefault(require("prompts"));
11
+ const expo_1 = require("../../expo");
12
+ const sight_artifacts_1 = require("./sight-artifacts");
13
+ const sight_session_1 = require("./sight-session");
14
+ const DEFAULT_SIGHT_URL = 'https://bundledrop.app/sight';
15
+ function detectAvailablePlatforms(projectRoot) {
16
+ return ['ios', 'android'].filter(platform => fs_1.default.existsSync(path_1.default.join(projectRoot, platform)));
17
+ }
18
+ async function resolvePlatform(projectRoot, explicitPlatform) {
19
+ if (explicitPlatform) {
20
+ return explicitPlatform;
21
+ }
22
+ const availablePlatforms = detectAvailablePlatforms(projectRoot);
23
+ if (availablePlatforms.length === 1) {
24
+ return availablePlatforms[0];
25
+ }
26
+ const answer = await (0, prompts_1.default)({
27
+ type: 'select',
28
+ name: 'platform',
29
+ message: 'Which platform should Sight analyze?',
30
+ choices: [
31
+ { title: 'iOS', value: 'ios' },
32
+ { title: 'Android', value: 'android' },
33
+ ],
34
+ });
35
+ if (answer.platform !== 'ios' && answer.platform !== 'android') {
36
+ throw new Error('No platform was selected. Pass --platform ios or --platform android.');
37
+ }
38
+ return answer.platform;
39
+ }
40
+ function printArtifactPaths(artifacts, heading) {
41
+ console.log(chalk_1.default.green(`\n${heading}`));
42
+ console.log(` Bundle: ${artifacts.bundlePath}`);
43
+ console.log(` Source map: ${artifacts.sourceMapPath}`);
44
+ }
45
+ function printManualInstructions(artifacts) {
46
+ printArtifactPaths(artifacts, 'Source files have been generated here:');
47
+ console.log(chalk_1.default.cyan(`\nOpen ${DEFAULT_SIGHT_URL} and attach both files for analysis.`));
48
+ }
49
+ function removeTemporaryArtifacts(artifacts) {
50
+ if (artifacts.temporary) {
51
+ fs_1.default.rmSync(artifacts.outputDirectory, { recursive: true, force: true });
52
+ }
53
+ }
54
+ async function runSightCommand(options) {
55
+ if (options.platform && !['ios', 'android'].includes(options.platform)) {
56
+ throw new Error('--platform must be ios or android.');
57
+ }
58
+ if (options.projectType && !['expo', 'bare'].includes(options.projectType)) {
59
+ throw new Error('--project-type must be expo or bare.');
60
+ }
61
+ const projectRoot = process.cwd();
62
+ const projectType = (0, expo_1.detectProjectType)({
63
+ projectRoot,
64
+ explicitType: options.projectType,
65
+ });
66
+ const platform = await resolvePlatform(projectRoot, options.platform);
67
+ console.log(chalk_1.default.bold.cyan('\nBundle Drop Sight'));
68
+ console.log(chalk_1.default.gray(`Detected ${projectType === 'expo' ? 'Expo' : 'bare React Native'} project`));
69
+ console.log(chalk_1.default.gray(`Generating a production ${platform} bundle and source map…`));
70
+ const artifacts = await (0, sight_artifacts_1.generateSightArtifacts)({
71
+ projectRoot,
72
+ projectType,
73
+ platform,
74
+ output: options.output,
75
+ keep: options.keep,
76
+ entryFile: options.entryFile,
77
+ });
78
+ console.log(chalk_1.default.green(`✓ Generated ${platform} production bundle`));
79
+ console.log(chalk_1.default.green('✓ Generated matching source map'));
80
+ const shouldOpen = options.open === false
81
+ ? false
82
+ : (await (0, prompts_1.default)({
83
+ type: 'confirm',
84
+ name: 'openSight',
85
+ message: 'Open Bundle Drop Sight and start the local analysis?',
86
+ initial: true,
87
+ })).openSight === true;
88
+ if (!shouldOpen) {
89
+ printManualInstructions(artifacts);
90
+ return;
91
+ }
92
+ const sightPageUrl = process.env.BUNDLE_DROP_SIGHT_URL || DEFAULT_SIGHT_URL;
93
+ let session;
94
+ try {
95
+ session = await (0, sight_session_1.startSightSession)({ artifacts, sightPageUrl });
96
+ }
97
+ catch (error) {
98
+ printManualInstructions(artifacts);
99
+ throw error;
100
+ }
101
+ let transferSucceeded = false;
102
+ try {
103
+ console.log(chalk_1.default.gray('Opening Bundle Drop Sight…'));
104
+ try {
105
+ await (0, sight_session_1.openSightInBrowser)(session.sightUrl);
106
+ }
107
+ catch {
108
+ console.log(chalk_1.default.yellow('Could not open the browser automatically.'));
109
+ console.log(chalk_1.default.gray(`Open this one-time URL manually:\n${session.sightUrl}`));
110
+ }
111
+ await session.waitForTransfer();
112
+ transferSucceeded = true;
113
+ console.log(chalk_1.default.green('✓ Bundle and source map loaded into Sight'));
114
+ }
115
+ finally {
116
+ await session.close();
117
+ if (transferSucceeded && !options.keep && !options.output) {
118
+ removeTemporaryArtifacts(artifacts);
119
+ }
120
+ else if (transferSucceeded) {
121
+ printArtifactPaths(artifacts, 'Generated files were kept here:');
122
+ }
123
+ else {
124
+ printManualInstructions(artifacts);
125
+ }
126
+ }
127
+ }
@@ -0,0 +1,14 @@
1
+ import type { SightArtifacts } from './sight-artifacts';
2
+ export type SightSession = {
3
+ sightUrl: string;
4
+ waitForTransfer: () => Promise<void>;
5
+ close: () => Promise<void>;
6
+ };
7
+ type StartSightSessionOptions = {
8
+ artifacts: SightArtifacts;
9
+ sightPageUrl: string;
10
+ timeoutMs?: number;
11
+ };
12
+ export declare function openSightInBrowser(url: string): Promise<void>;
13
+ export declare function startSightSession({ artifacts, sightPageUrl, timeoutMs, }: StartSightSessionOptions): Promise<SightSession>;
14
+ export {};
@@ -0,0 +1,192 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.openSightInBrowser = openSightInBrowser;
7
+ exports.startSightSession = startSightSession;
8
+ const child_process_1 = require("child_process");
9
+ const crypto_1 = require("crypto");
10
+ const fs_1 = __importDefault(require("fs"));
11
+ const http_1 = __importDefault(require("http"));
12
+ const path_1 = __importDefault(require("path"));
13
+ const SESSION_TIMEOUT_MS = 5 * 60 * 1000;
14
+ const LOOPBACK_HOST = '127.0.0.1';
15
+ function sessionFragment(port, token) {
16
+ const payload = Buffer.from(JSON.stringify({ version: 1, port, token }), 'utf8')
17
+ .toString('base64url');
18
+ return `sight-session=${payload}`;
19
+ }
20
+ function multipartHeader(boundary, field, filePath) {
21
+ const filename = path_1.default.basename(filePath).replace(/["\r\n]/g, '_');
22
+ return Buffer.from(`--${boundary}\r\n` +
23
+ `Content-Disposition: form-data; name="${field}"; filename="${filename}"\r\n` +
24
+ 'Content-Type: application/octet-stream\r\n\r\n', 'utf8');
25
+ }
26
+ function writeFilePart(response, header, filePath, signal) {
27
+ return new Promise((resolve, reject) => {
28
+ const input = fs_1.default.createReadStream(filePath);
29
+ const cleanup = () => signal.removeEventListener('abort', abort);
30
+ const abort = () => {
31
+ const reason = signal.reason instanceof Error
32
+ ? signal.reason
33
+ : new Error('Sight closed the local artifact transfer.');
34
+ input.destroy(reason);
35
+ };
36
+ input.once('error', error => {
37
+ cleanup();
38
+ reject(error);
39
+ });
40
+ input.once('end', () => {
41
+ cleanup();
42
+ resolve();
43
+ });
44
+ signal.addEventListener('abort', abort, { once: true });
45
+ response.write(header);
46
+ input.pipe(response, { end: false });
47
+ });
48
+ }
49
+ function closeServer(server, sockets, force = false) {
50
+ return new Promise(resolve => {
51
+ if (!server.listening) {
52
+ resolve();
53
+ return;
54
+ }
55
+ server.close(() => resolve());
56
+ if (force) {
57
+ sockets.forEach(socket => socket.destroy());
58
+ }
59
+ });
60
+ }
61
+ function openSightInBrowser(url) {
62
+ const command = process.platform === 'darwin'
63
+ ? { file: 'open', args: [url] }
64
+ : process.platform === 'win32'
65
+ ? { file: 'explorer.exe', args: [url] }
66
+ : { file: 'xdg-open', args: [url] };
67
+ return new Promise((resolve, reject) => {
68
+ const child = (0, child_process_1.spawn)(command.file, command.args, {
69
+ detached: true,
70
+ stdio: 'ignore',
71
+ windowsHide: true,
72
+ });
73
+ child.once('error', reject);
74
+ child.once('spawn', () => {
75
+ child.unref();
76
+ resolve();
77
+ });
78
+ });
79
+ }
80
+ async function startSightSession({ artifacts, sightPageUrl, timeoutMs = SESSION_TIMEOUT_MS, }) {
81
+ const pageUrl = new URL(sightPageUrl);
82
+ const isOfficialSightPage = pageUrl.origin === 'https://bundledrop.app' && pageUrl.pathname === '/sight';
83
+ const isLocalSightPage = ['http:', 'https:'].includes(pageUrl.protocol) &&
84
+ ['localhost', LOOPBACK_HOST].includes(pageUrl.hostname) &&
85
+ pageUrl.pathname === '/sight';
86
+ if (!isOfficialSightPage && !isLocalSightPage) {
87
+ throw new Error('Sight URL must be https://bundledrop.app/sight or a localhost development page.');
88
+ }
89
+ const allowedOrigin = pageUrl.origin;
90
+ const token = (0, crypto_1.randomBytes)(32).toString('hex');
91
+ const boundary = `bundle-drop-sight-${(0, crypto_1.randomBytes)(12).toString('hex')}`;
92
+ const sockets = new Set();
93
+ let consumed = false;
94
+ let settleTransfer;
95
+ let rejectTransfer;
96
+ const transfer = new Promise((resolve, reject) => {
97
+ settleTransfer = resolve;
98
+ rejectTransfer = reject;
99
+ });
100
+ const server = http_1.default.createServer(async (request, response) => {
101
+ const origin = request.headers.origin;
102
+ const isAllowedOrigin = origin === allowedOrigin;
103
+ if (origin && !isAllowedOrigin) {
104
+ response.writeHead(403).end('Origin not allowed');
105
+ return;
106
+ }
107
+ if (request.method === 'OPTIONS') {
108
+ if (!isAllowedOrigin) {
109
+ response.writeHead(403).end('Origin not allowed');
110
+ return;
111
+ }
112
+ response.writeHead(204, {
113
+ 'Access-Control-Allow-Origin': allowedOrigin,
114
+ 'Access-Control-Allow-Methods': 'GET, OPTIONS',
115
+ 'Access-Control-Allow-Headers': 'Authorization',
116
+ 'Access-Control-Allow-Private-Network': 'true',
117
+ Vary: 'Origin',
118
+ }).end();
119
+ return;
120
+ }
121
+ if (request.method !== 'GET' || request.url !== '/session') {
122
+ response.writeHead(404).end('Not found');
123
+ return;
124
+ }
125
+ if (!isAllowedOrigin) {
126
+ response.writeHead(403).end('Origin not allowed');
127
+ return;
128
+ }
129
+ if (request.headers.authorization !== `Bearer ${token}`) {
130
+ response.writeHead(401).end('Unauthorized');
131
+ return;
132
+ }
133
+ if (consumed) {
134
+ response.writeHead(410).end('Session already used');
135
+ return;
136
+ }
137
+ consumed = true;
138
+ const transferAbort = new AbortController();
139
+ const rejectPrematureClose = () => {
140
+ const error = new Error('Bundle Drop Sight closed before the generated files finished loading.');
141
+ transferAbort.abort(error);
142
+ rejectTransfer?.(error);
143
+ void closeServer(server, sockets, true);
144
+ };
145
+ request.once('aborted', rejectPrematureClose);
146
+ response.once('close', rejectPrematureClose);
147
+ response.writeHead(200, {
148
+ 'Access-Control-Allow-Origin': allowedOrigin,
149
+ 'Cache-Control': 'no-store',
150
+ Connection: 'close',
151
+ 'Content-Type': `multipart/form-data; boundary=${boundary}`,
152
+ Vary: 'Origin',
153
+ 'X-Content-Type-Options': 'nosniff',
154
+ });
155
+ try {
156
+ await writeFilePart(response, multipartHeader(boundary, 'bundle', artifacts.bundlePath), artifacts.bundlePath, transferAbort.signal);
157
+ response.write('\r\n');
158
+ await writeFilePart(response, multipartHeader(boundary, 'sourceMap', artifacts.sourceMapPath), artifacts.sourceMapPath, transferAbort.signal);
159
+ response.once('finish', () => {
160
+ request.removeListener('aborted', rejectPrematureClose);
161
+ response.removeListener('close', rejectPrematureClose);
162
+ settleTransfer?.();
163
+ });
164
+ response.end(`\r\n--${boundary}--\r\n`);
165
+ }
166
+ catch (error) {
167
+ response.destroy(error instanceof Error ? error : undefined);
168
+ rejectTransfer?.(error instanceof Error ? error : new Error('Failed to transfer Sight artifacts.'));
169
+ }
170
+ });
171
+ server.on('connection', socket => {
172
+ sockets.add(socket);
173
+ socket.once('close', () => sockets.delete(socket));
174
+ });
175
+ await new Promise((resolve, reject) => {
176
+ server.once('error', reject);
177
+ server.listen(0, LOOPBACK_HOST, resolve);
178
+ });
179
+ const timeout = setTimeout(() => {
180
+ rejectTransfer?.(new Error('Timed out waiting for Bundle Drop Sight to load the generated files.'));
181
+ void closeServer(server, sockets, true);
182
+ }, timeoutMs);
183
+ timeout.unref();
184
+ void transfer.finally(() => clearTimeout(timeout)).catch(() => undefined);
185
+ const address = server.address();
186
+ pageUrl.hash = sessionFragment(address.port, token);
187
+ return {
188
+ sightUrl: pageUrl.toString(),
189
+ waitForTransfer: () => transfer,
190
+ close: () => closeServer(server, sockets),
191
+ };
192
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gfean/react-native-bundle-drop",
3
- "version": "0.4.6",
3
+ "version": "0.5.1",
4
4
  "nativeVersion": "0.4.5",
5
5
  "description": "Over-the-air updates for Expo and bare React Native apps, with channels, staged rollouts, patch delivery, and rollback.",
6
6
  "main": "lib/index.js",