@gfean/react-native-bundle-drop 0.6.0 → 0.8.0

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.
Files changed (86) hide show
  1. package/BundleDrop.podspec +96 -0
  2. package/README.md +249 -9
  3. package/android/build.gradle +72 -5
  4. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +137 -13
  5. package/android/src/main/java/com/bundledrop/BundleDropNativePaths.kt +43 -13
  6. package/android/src/main/java/com/bundledrop/BundleDropOtaResolver.kt +35 -0
  7. package/android/src/main/java/com/bundledrop/BundleDropStartupRecovery.kt +1117 -0
  8. package/ios/BundleDropBridge.m +27 -0
  9. package/ios/BundleDropLocator.swift +31 -15
  10. package/ios/BundleDropModule.swift +106 -3
  11. package/ios/BundleDropOtaResolver.swift +137 -29
  12. package/ios/BundleDropStartupRecovery.swift +1108 -0
  13. package/ios/BundleDropStartupRecoveryAdapter.swift +301 -0
  14. package/lib/CLI/cli.js +9 -5
  15. package/lib/CLI/scripts/doctor.js +28 -9
  16. package/lib/CLI/scripts/expo/configure-expo.js +2 -1
  17. package/lib/CLI/scripts/init-config.d.ts +2 -2
  18. package/lib/CLI/scripts/init-config.js +23 -14
  19. package/lib/CLI/scripts/login-cli.js +2 -3
  20. package/lib/CLI/scripts/native/write-runtime-identity.d.ts +19 -0
  21. package/lib/CLI/scripts/native/write-runtime-identity.js +92 -0
  22. package/lib/CLI/scripts/sight-artifacts.d.ts +9 -1
  23. package/lib/CLI/scripts/sight-artifacts.js +20 -8
  24. package/lib/CLI/scripts/sight-assets.d.ts +15 -0
  25. package/lib/CLI/scripts/sight-assets.js +71 -0
  26. package/lib/CLI/scripts/sight-cli.d.ts +3 -0
  27. package/lib/CLI/scripts/sight-cli.js +50 -4
  28. package/lib/CLI/scripts/sight-compare/assets.d.ts +6 -0
  29. package/lib/CLI/scripts/sight-compare/assets.js +73 -0
  30. package/lib/CLI/scripts/sight-compare/dependencies.d.ts +22 -0
  31. package/lib/CLI/scripts/sight-compare/dependencies.js +289 -0
  32. package/lib/CLI/scripts/sight-compare/git.d.ts +22 -0
  33. package/lib/CLI/scripts/sight-compare/git.js +116 -0
  34. package/lib/CLI/scripts/sight-compare/inspect-project.d.ts +37 -0
  35. package/lib/CLI/scripts/sight-compare/inspect-project.js +191 -0
  36. package/lib/CLI/scripts/sight-compare/metadata.d.ts +4 -0
  37. package/lib/CLI/scripts/sight-compare/metadata.js +39 -0
  38. package/lib/CLI/scripts/sight-compare/process.d.ts +22 -0
  39. package/lib/CLI/scripts/sight-compare/process.js +221 -0
  40. package/lib/CLI/scripts/sight-compare/run.d.ts +3 -0
  41. package/lib/CLI/scripts/sight-compare/run.js +290 -0
  42. package/lib/CLI/scripts/sight-compare/snapshot.d.ts +26 -0
  43. package/lib/CLI/scripts/sight-compare/snapshot.js +279 -0
  44. package/lib/CLI/scripts/sight-compare/types.d.ts +87 -0
  45. package/lib/CLI/scripts/sight-compare/types.js +2 -0
  46. package/lib/CLI/scripts/sight-ota.d.ts +18 -0
  47. package/lib/CLI/scripts/sight-ota.js +260 -0
  48. package/lib/CLI/scripts/sight-session.d.ts +9 -2
  49. package/lib/CLI/scripts/sight-session.js +58 -20
  50. package/lib/CLI/scripts/upload-cli.d.ts +12 -2
  51. package/lib/CLI/scripts/upload-cli.js +74 -11
  52. package/lib/CLI/serverUrl.d.ts +3 -0
  53. package/lib/CLI/serverUrl.js +31 -0
  54. package/lib/bundleInfo.d.ts +2 -0
  55. package/lib/bundleInfo.js +16 -1
  56. package/lib/context.js +12 -2
  57. package/lib/fs/bundlePointer.d.ts +1 -17
  58. package/lib/fs/bundlePointer.js +5 -93
  59. package/lib/install/bundleInstallShared.js +4 -4
  60. package/lib/manager/downloadAndInstall.js +25 -22
  61. package/lib/manager/reporting.d.ts +8 -1
  62. package/lib/manager/reporting.js +17 -22
  63. package/lib/manager/rollbackState.d.ts +18 -54
  64. package/lib/manager/rollbackState.js +115 -216
  65. package/lib/manager/updateCheck.js +9 -3
  66. package/lib/manager/updateState.d.ts +2 -1
  67. package/lib/manager/updateState.js +59 -6
  68. package/lib/metro.d.ts +1 -1
  69. package/lib/metro.js +4 -3
  70. package/lib/native/bundleDropNative.d.ts +62 -0
  71. package/lib/native/bundleDropNative.js +266 -1
  72. package/lib/patch-engine/installFromPatchSet.js +2 -2
  73. package/lib/runtime/service.js +29 -71
  74. package/lib/runtime-delivery/bootstrapConfig.d.ts +29 -11
  75. package/lib/runtime-delivery/bootstrapConfig.js +83 -22
  76. package/lib/runtime-delivery/manifestState.d.ts +3 -1
  77. package/lib/runtime-delivery/manifestState.js +22 -1
  78. package/lib/runtime-delivery/manifestVerifier.js +7 -1
  79. package/lib/scripts/bundle.d.ts +12 -2
  80. package/lib/scripts/bundle.js +74 -21
  81. package/lib/scripts/download-bundle.d.ts +1 -0
  82. package/lib/scripts/download-bundle.js +2 -2
  83. package/lib/scripts/resolveModule.d.ts +2 -0
  84. package/lib/scripts/resolveModule.js +5 -0
  85. package/package.json +5 -2
  86. package/plugin/xcodeBuildPhase.js +2 -1
@@ -1,14 +1,21 @@
1
1
  import type { SightArtifacts } from './sight-artifacts';
2
+ import type { ComparisonArtifacts } from './sight-compare/types';
2
3
  export type SightSession = {
3
4
  sightUrl: string;
4
5
  waitForTransfer: () => Promise<void>;
5
6
  close: () => Promise<void>;
6
7
  };
7
- type StartSightSessionOptions = {
8
+ type StartSightSessionOptions = ({
8
9
  artifacts: SightArtifacts;
10
+ comparison?: never;
11
+ } | {
12
+ artifacts?: never;
13
+ comparison: ComparisonArtifacts;
14
+ }) & {
9
15
  sightPageUrl: string;
10
16
  timeoutMs?: number;
17
+ signal?: AbortSignal;
11
18
  };
12
19
  export declare function openSightInBrowser(url: string): Promise<void>;
13
- export declare function startSightSession({ artifacts, sightPageUrl, timeoutMs, }: StartSightSessionOptions): Promise<SightSession>;
20
+ export declare function startSightSession({ artifacts, comparison, sightPageUrl, timeoutMs, signal, }: StartSightSessionOptions): Promise<SightSession>;
14
21
  export {};
@@ -10,10 +10,11 @@ const crypto_1 = require("crypto");
10
10
  const fs_1 = __importDefault(require("fs"));
11
11
  const http_1 = __importDefault(require("http"));
12
12
  const path_1 = __importDefault(require("path"));
13
+ const assets_1 = require("./sight-compare/assets");
13
14
  const SESSION_TIMEOUT_MS = 5 * 60 * 1000;
14
15
  const LOOPBACK_HOST = '127.0.0.1';
15
- function sessionFragment(port, token) {
16
- const payload = Buffer.from(JSON.stringify({ version: 1, port, token }), 'utf8')
16
+ function sessionFragment(port, token, version) {
17
+ const payload = Buffer.from(JSON.stringify({ version, port, token }), 'utf8')
17
18
  .toString('base64url');
18
19
  return `sight-session=${payload}`;
19
20
  }
@@ -28,10 +29,8 @@ function writeFilePart(response, header, filePath, signal) {
28
29
  const input = fs_1.default.createReadStream(filePath);
29
30
  const cleanup = () => signal.removeEventListener('abort', abort);
30
31
  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);
32
+ // This private transfer controller is always aborted with an Error below.
33
+ input.destroy(signal.reason);
35
34
  };
36
35
  input.once('error', error => {
37
36
  cleanup();
@@ -46,16 +45,14 @@ function writeFilePart(response, header, filePath, signal) {
46
45
  input.pipe(response, { end: false });
47
46
  });
48
47
  }
49
- function closeServer(server, sockets, force = false) {
48
+ function closeServer(server, sockets) {
50
49
  return new Promise(resolve => {
51
50
  if (!server.listening) {
52
51
  resolve();
53
52
  return;
54
53
  }
55
54
  server.close(() => resolve());
56
- if (force) {
57
- sockets.forEach(socket => socket.destroy());
58
- }
55
+ sockets.forEach(socket => socket.destroy());
59
56
  });
60
57
  }
61
58
  function openSightInBrowser(url) {
@@ -77,7 +74,8 @@ function openSightInBrowser(url) {
77
74
  });
78
75
  });
79
76
  }
80
- async function startSightSession({ artifacts, sightPageUrl, timeoutMs = SESSION_TIMEOUT_MS, }) {
77
+ async function startSightSession({ artifacts, comparison, sightPageUrl, timeoutMs = SESSION_TIMEOUT_MS, signal, }) {
78
+ signal?.throwIfAborted();
81
79
  const pageUrl = new URL(sightPageUrl);
82
80
  const isOfficialSightPage = pageUrl.origin === 'https://bundledrop.app' && pageUrl.pathname === '/sight';
83
81
  const isLocalSightPage = ['http:', 'https:'].includes(pageUrl.protocol) &&
@@ -97,6 +95,8 @@ async function startSightSession({ artifacts, sightPageUrl, timeoutMs = SESSION_
97
95
  settleTransfer = resolve;
98
96
  rejectTransfer = reject;
99
97
  });
98
+ // Cancellation can arrive before the caller starts waiting for the transfer.
99
+ void transfer.catch(() => undefined);
100
100
  const server = http_1.default.createServer(async (request, response) => {
101
101
  const origin = request.headers.origin;
102
102
  const isAllowedOrigin = origin === allowedOrigin;
@@ -140,7 +140,7 @@ async function startSightSession({ artifacts, sightPageUrl, timeoutMs = SESSION_
140
140
  const error = new Error('Bundle Drop Sight closed before the generated files finished loading.');
141
141
  transferAbort.abort(error);
142
142
  rejectTransfer?.(error);
143
- void closeServer(server, sockets, true);
143
+ void closeServer(server, sockets);
144
144
  };
145
145
  request.once('aborted', rejectPrematureClose);
146
146
  response.once('close', rejectPrematureClose);
@@ -153,15 +153,39 @@ async function startSightSession({ artifacts, sightPageUrl, timeoutMs = SESSION_
153
153
  'X-Content-Type-Options': 'nosniff',
154
154
  });
155
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);
156
+ const files = comparison
157
+ ? [
158
+ ['baselineBundle', comparison.baseline.bundlePath],
159
+ ['baselineSourceMap', comparison.baseline.sourceMapPath],
160
+ ['currentBundle', comparison.current.bundlePath],
161
+ ['currentSourceMap', comparison.current.sourceMapPath],
162
+ ]
163
+ : [['bundle', artifacts.bundlePath], ['sourceMap', artifacts.sourceMapPath]];
164
+ const assetManifestPath = comparison?.assetManifestPath ?? artifacts?.assetManifestPath;
165
+ if (assetManifestPath) {
166
+ if (fs_1.default.statSync(assetManifestPath).size > assets_1.MAX_ASSET_MANIFEST_BYTES) {
167
+ throw new Error('Sight asset manifest exceeds 4 MiB.');
168
+ }
169
+ files.push(['assetManifest', assetManifestPath]);
170
+ }
171
+ if (comparison) {
172
+ const metadata = fs_1.default.readFileSync(comparison.metadataPath);
173
+ if (metadata.length > 64 * 1024)
174
+ throw new Error('Sight comparison metadata exceeds 64 KiB.');
175
+ response.write(`--${boundary}\r\nContent-Disposition: form-data; name="metadata"\r\nContent-Type: application/json\r\n\r\n`);
176
+ response.write(metadata);
177
+ response.write('\r\n');
178
+ }
179
+ for (const [field, filePath] of files) {
180
+ await writeFilePart(response, multipartHeader(boundary, field, filePath), filePath, transferAbort.signal);
181
+ response.write('\r\n');
182
+ }
159
183
  response.once('finish', () => {
160
184
  request.removeListener('aborted', rejectPrematureClose);
161
185
  response.removeListener('close', rejectPrematureClose);
162
186
  settleTransfer?.();
163
187
  });
164
- response.end(`\r\n--${boundary}--\r\n`);
188
+ response.end(`--${boundary}--\r\n`);
165
189
  }
166
190
  catch (error) {
167
191
  response.destroy(error instanceof Error ? error : undefined);
@@ -178,15 +202,29 @@ async function startSightSession({ artifacts, sightPageUrl, timeoutMs = SESSION_
178
202
  });
179
203
  const timeout = setTimeout(() => {
180
204
  rejectTransfer?.(new Error('Timed out waiting for Bundle Drop Sight to load the generated files.'));
181
- void closeServer(server, sockets, true);
205
+ void closeServer(server, sockets);
182
206
  }, timeoutMs);
183
207
  timeout.unref();
184
- void transfer.finally(() => clearTimeout(timeout)).catch(() => undefined);
185
208
  const address = server.address();
186
- pageUrl.hash = sessionFragment(address.port, token);
209
+ const abort = () => {
210
+ rejectTransfer?.(new Error('Sight comparison cancelled during local transfer.'));
211
+ void closeServer(server, sockets);
212
+ };
213
+ signal?.addEventListener('abort', abort, { once: true });
214
+ if (signal?.aborted)
215
+ abort();
216
+ const clearSession = () => {
217
+ clearTimeout(timeout);
218
+ signal?.removeEventListener('abort', abort);
219
+ };
220
+ void transfer.finally(clearSession).catch(() => undefined);
221
+ pageUrl.hash = sessionFragment(address.port, token, comparison ? 2 : 1);
187
222
  return {
188
223
  sightUrl: pageUrl.toString(),
189
224
  waitForTransfer: () => transfer,
190
- close: () => closeServer(server, sockets),
225
+ close: () => {
226
+ clearSession();
227
+ return closeServer(server, sockets);
228
+ },
191
229
  };
192
230
  }
@@ -1,4 +1,6 @@
1
- export default function upload(platform: string, options: {
1
+ import { spawnSync } from 'child_process';
2
+ import { type ModuleResolver } from '../../scripts/resolveModule';
3
+ type UploadOptions = {
2
4
  plistFile?: string;
3
5
  version?: string;
4
6
  channel?: string;
@@ -9,4 +11,12 @@ export default function upload(platform: string, options: {
9
11
  sourcemap?: boolean;
10
12
  artifactDir?: string;
11
13
  buildReceipt?: string;
12
- }): Promise<void>;
14
+ };
15
+ type UploadDependencies = {
16
+ packageRoot: string;
17
+ spawnProcess: typeof spawnSync;
18
+ resolveModule: ModuleResolver;
19
+ };
20
+ export declare function runUpload(platform: string, options: UploadOptions, dependencies?: UploadDependencies): Promise<void>;
21
+ export default function upload(platform: string, options: UploadOptions): Promise<void>;
22
+ export {};
@@ -36,6 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.runUpload = runUpload;
39
40
  exports.default = upload;
40
41
  const axios_1 = __importDefault(require("axios"));
41
42
  const child_process_1 = require("child_process");
@@ -46,6 +47,8 @@ const plist = __importStar(require("plist"));
46
47
  const ui_1 = require("../utils/ui");
47
48
  const resolve_ios_version_1 = require("../../scripts/resolve-ios-version");
48
49
  const expo_1 = require("../../expo");
50
+ const resolveModule_1 = require("../../scripts/resolveModule");
51
+ const serverUrl_1 = require("../serverUrl");
49
52
  const DOCS_INSTALLATION_URL = 'https://bundledrop.app/docs/installation';
50
53
  const DOCS_UPLOADING_URL = 'https://bundledrop.app/docs/uploading';
51
54
  const DOCS_CI_CD_URL = 'https://bundledrop.app/docs/ci-cd';
@@ -55,7 +58,23 @@ const BUNDLE_DROP_ARTIFACT_FILES = [
55
58
  'main.jsbundle.map',
56
59
  'bundle-drop-result.json',
57
60
  ];
58
- const getPackageRoot = () => process.env.BUNDLE_DROP_PACKAGE_ROOT_OVERRIDE || path.resolve(__dirname, '..', '..', '..');
61
+ const defaultUploadDependencies = () => ({
62
+ packageRoot: path.resolve(__dirname, '..', '..', '..'),
63
+ spawnProcess: child_process_1.spawnSync,
64
+ resolveModule: resolveModule_1.resolveModuleFrom,
65
+ });
66
+ const assertPathInside = (targetPath, parentPath, label) => {
67
+ const resolvedParent = path.resolve(parentPath);
68
+ const resolvedTarget = path.resolve(targetPath);
69
+ const relative = path.relative(resolvedParent, resolvedTarget);
70
+ const escapesParent = relative === '..' ||
71
+ relative.startsWith(`..${path.sep}`) ||
72
+ path.isAbsolute(relative);
73
+ if (!escapesParent) {
74
+ return;
75
+ }
76
+ throw new Error(`${label} escaped its generated output directory: ${resolvedTarget}`);
77
+ };
59
78
  const readPackageVersion = (packageRoot) => {
60
79
  try {
61
80
  const packageJson = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8'));
@@ -114,7 +133,7 @@ const bareArtifactPaths = (packageRoot, platform) => {
114
133
  zipPath: path.join(outputDir, `bundle-${platform}.zip`),
115
134
  };
116
135
  };
117
- async function upload(platform, options) {
136
+ async function runUpload(platform, options, dependencies = defaultUploadDependencies()) {
118
137
  console.log(); // blank line
119
138
  ui_1.log.info('🚀 React Native OTA Upload Initialized');
120
139
  const projectRoot = process.cwd();
@@ -165,7 +184,26 @@ async function upload(platform, options) {
165
184
  `CI/CD tokens: ${DOCS_CI_CD_URL}`);
166
185
  process.exit(1);
167
186
  }
168
- token = JSON.parse(fs.readFileSync(authPath, 'utf-8')).token;
187
+ let storedAuth;
188
+ try {
189
+ storedAuth = JSON.parse(fs.readFileSync(authPath, 'utf-8'));
190
+ }
191
+ catch {
192
+ ui_1.log.error('❌ Failed to read CLI auth session. Run `bundle-drop login` again or pass --token.');
193
+ process.exit(1);
194
+ }
195
+ if (!storedAuth?.token) {
196
+ ui_1.log.error('❌ CLI auth session is missing a token. Run `bundle-drop login` again or pass --token.');
197
+ process.exit(1);
198
+ }
199
+ try {
200
+ (0, serverUrl_1.assertMatchingServerOrigin)(serverUrl, storedAuth.serverUrl || storedAuth.baseUrl);
201
+ }
202
+ catch (error) {
203
+ ui_1.log.error(`❌ ${error.message}`);
204
+ process.exit(1);
205
+ }
206
+ token = storedAuth.token;
169
207
  }
170
208
  // Validate channel
171
209
  const channel = options.channel;
@@ -271,7 +309,7 @@ async function upload(platform, options) {
271
309
  ui_1.log.label('App Version', version);
272
310
  console.log();
273
311
  ui_1.log.arrow(`Bundling ${platform} app...`);
274
- const packageRoot = getPackageRoot();
312
+ const packageRoot = dependencies.packageRoot;
275
313
  const packageVersion = readPackageVersion(packageRoot);
276
314
  const compiledBundleScript = path.join(packageRoot, 'lib', 'scripts', 'bundle.js');
277
315
  const tsBundleScript = path.join(packageRoot, 'src', 'scripts', 'bundle.ts');
@@ -289,17 +327,30 @@ async function upload(platform, options) {
289
327
  });
290
328
  }
291
329
  else {
292
- const bundleCommand = fs.existsSync(compiledBundleScript)
293
- ? `node "${compiledBundleScript}"`
294
- : `ts-node "${tsBundleScript}"`;
295
- const sourcemapArg = options.sourcemap ? ' --sourcemap' : '';
296
- (0, child_process_1.execSync)(`${bundleCommand} ${platform}${sourcemapArg}`, {
330
+ const useCompiledScript = fs.existsSync(compiledBundleScript);
331
+ const script = useCompiledScript
332
+ ? compiledBundleScript
333
+ : dependencies.resolveModule('ts-node/dist/bin.js', [packageRoot, __dirname]);
334
+ const args = [
335
+ script,
336
+ ...(useCompiledScript ? [] : [tsBundleScript]),
337
+ platform,
338
+ ];
339
+ if (options.sourcemap)
340
+ args.push('--sourcemap');
341
+ const result = dependencies.spawnProcess(process.execPath, args, {
297
342
  stdio: 'inherit',
343
+ shell: false,
298
344
  env: {
299
345
  ...process.env,
300
346
  BUNDLE_DROP_APP_VERSION: version,
301
347
  },
302
348
  });
349
+ if (result.error)
350
+ throw result.error;
351
+ if (result.status !== 0) {
352
+ throw new Error(`Bundle process exited with status ${result.status}`);
353
+ }
303
354
  }
304
355
  }
305
356
  catch (error) {
@@ -425,6 +476,10 @@ async function upload(platform, options) {
425
476
  }
426
477
  finally {
427
478
  try {
479
+ const generatedRoot = isExpoProject
480
+ ? path.join(projectRoot, '.bundle-drop', 'artifacts')
481
+ : path.join(packageRoot, 'dist');
482
+ assertPathInside(artifact.outputDir, generatedRoot, 'Artifact output');
428
483
  const cleanupFiles = [
429
484
  artifact.zipPath,
430
485
  artifact.metadataPath,
@@ -436,12 +491,17 @@ async function upload(platform, options) {
436
491
  const expoExportDirectory = artifact.expoExportDirectory ??
437
492
  path.join(packageRoot, 'dist', `expo-export-${platform}`);
438
493
  for (const file of cleanupFiles) {
439
- if (file && fs.existsSync(file))
440
- fs.unlinkSync(file);
494
+ if (file) {
495
+ assertPathInside(file, artifact.outputDir, 'Artifact file');
496
+ if (fs.existsSync(file))
497
+ fs.unlinkSync(file);
498
+ }
441
499
  }
500
+ assertPathInside(assetsPath, artifact.outputDir, 'Artifact assets');
442
501
  if (fs.existsSync(assetsPath)) {
443
502
  fs.rmSync(assetsPath, { recursive: true, force: true });
444
503
  }
504
+ assertPathInside(expoExportDirectory, generatedRoot, 'Expo export');
445
505
  if (fs.existsSync(expoExportDirectory)) {
446
506
  fs.rmSync(expoExportDirectory, { recursive: true, force: true });
447
507
  }
@@ -456,3 +516,6 @@ async function upload(platform, options) {
456
516
  }
457
517
  }
458
518
  }
519
+ function upload(platform, options) {
520
+ return runUpload(platform, options);
521
+ }
@@ -0,0 +1,3 @@
1
+ export declare const DEFAULT_SERVER_URL = "https://api.bundledrop.app";
2
+ export declare const normalizeServerUrl: (value?: string) => string;
3
+ export declare const assertMatchingServerOrigin: (requestServerUrl: string, authenticatedServerUrl: string | undefined) => void;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.assertMatchingServerOrigin = exports.normalizeServerUrl = exports.DEFAULT_SERVER_URL = void 0;
4
+ exports.DEFAULT_SERVER_URL = 'https://api.bundledrop.app';
5
+ const normalizeServerUrl = (value) => {
6
+ const serverUrl = value || exports.DEFAULT_SERVER_URL;
7
+ let parsed;
8
+ try {
9
+ parsed = new URL(serverUrl);
10
+ }
11
+ catch {
12
+ throw new Error('Bundle Drop serverUrl must be an HTTP(S) URL without embedded credentials.');
13
+ }
14
+ if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password) {
15
+ throw new Error('Bundle Drop serverUrl must be an HTTP(S) URL without embedded credentials.');
16
+ }
17
+ return serverUrl.replace(/\/+$/, '');
18
+ };
19
+ exports.normalizeServerUrl = normalizeServerUrl;
20
+ const assertMatchingServerOrigin = (requestServerUrl, authenticatedServerUrl) => {
21
+ if (!authenticatedServerUrl) {
22
+ throw new Error('The stored CLI login is not bound to a server. Run `bundle-drop login` again or pass --token explicitly.');
23
+ }
24
+ const requestOrigin = new URL((0, exports.normalizeServerUrl)(requestServerUrl)).origin;
25
+ const authenticatedOrigin = new URL((0, exports.normalizeServerUrl)(authenticatedServerUrl)).origin;
26
+ if (requestOrigin !== authenticatedOrigin) {
27
+ throw new Error(`The stored CLI login belongs to ${authenticatedOrigin}, but this project targets ${requestOrigin}. ` +
28
+ 'Run `bundle-drop login` for this server or pass --token explicitly.');
29
+ }
30
+ };
31
+ exports.assertMatchingServerOrigin = assertMatchingServerOrigin;
@@ -24,5 +24,7 @@ export type BundleInfo = {
24
24
  runtimeVersion?: string;
25
25
  };
26
26
  export declare function readBundleInfo(): Promise<BundleInfo | null>;
27
+ export declare function writeBundleInfoDurably(info: BundleInfo): Promise<void>;
27
28
  export declare function writeBundleInfo(info: BundleInfo): Promise<void>;
28
29
  export declare function updateBundleInfo(partial: Partial<BundleInfo>): Promise<void>;
30
+ export declare function deleteBundleInfo(): Promise<void>;
package/lib/bundleInfo.js CHANGED
@@ -4,8 +4,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.readBundleInfo = readBundleInfo;
7
+ exports.writeBundleInfoDurably = writeBundleInfoDurably;
7
8
  exports.writeBundleInfo = writeBundleInfo;
8
9
  exports.updateBundleInfo = updateBundleInfo;
10
+ exports.deleteBundleInfo = deleteBundleInfo;
9
11
  const fs_1 = __importDefault(require("./native/fs"));
10
12
  const BUNDLE_INFO_PATH = `${fs_1.default.DocumentDirectoryPath}/bundle-info.json`;
11
13
  async function readBundleInfo() {
@@ -20,9 +22,12 @@ async function readBundleInfo() {
20
22
  return null;
21
23
  }
22
24
  }
25
+ async function writeBundleInfoDurably(info) {
26
+ await fs_1.default.writeFile(BUNDLE_INFO_PATH, JSON.stringify(info, null, 2), 'utf8');
27
+ }
23
28
  async function writeBundleInfo(info) {
24
29
  try {
25
- await fs_1.default.writeFile(BUNDLE_INFO_PATH, JSON.stringify(info, null, 2), 'utf8');
30
+ await writeBundleInfoDurably(info);
26
31
  }
27
32
  catch (e) {
28
33
  console.warn('⚠️ Failed to write bundle-info.json', e);
@@ -32,3 +37,13 @@ async function updateBundleInfo(partial) {
32
37
  const existing = (await readBundleInfo()) || {};
33
38
  await writeBundleInfo({ ...existing, ...partial });
34
39
  }
40
+ async function deleteBundleInfo() {
41
+ try {
42
+ if (await fs_1.default.exists(BUNDLE_INFO_PATH)) {
43
+ await fs_1.default.unlink(BUNDLE_INFO_PATH);
44
+ }
45
+ }
46
+ catch (e) {
47
+ console.warn('⚠️ Failed to delete bundle-info.json', e);
48
+ }
49
+ }
package/lib/context.js CHANGED
@@ -29,6 +29,16 @@ exports.runtimeVersion = typeof platformRuntimeVersion === 'string'
29
29
  : (0, nativeIdentity_1.resolveExpoNativeRuntimeVersion)(platformRuntimeVersion.source)
30
30
  : undefined;
31
31
  exports.defaultChannel = exports.config.defaultChannel || 'develop';
32
+ const configuredMaxCrashCount = exports.config.rollback?.maxCrashCount ?? 3;
33
+ if (!Number.isSafeInteger(configuredMaxCrashCount) ||
34
+ configuredMaxCrashCount < 0 ||
35
+ configuredMaxCrashCount > 2147483647) {
36
+ throw new Error('[BundleDrop] rollback.maxCrashCount must be a non-negative 32-bit integer.');
37
+ }
38
+ const configuredHealthyAfterSec = exports.config.rollback?.healthyAfterSec ?? 0;
39
+ if (!Number.isFinite(configuredHealthyAfterSec) || configuredHealthyAfterSec < 0) {
40
+ throw new Error('[BundleDrop] rollback.healthyAfterSec must be a finite non-negative number.');
41
+ }
32
42
  exports.BUNDLE_DROP_ROOT = exports.isIOS
33
43
  ? `${fs_1.default.LibraryDirectoryPath}/bundle-drop`
34
44
  : `${fs_1.default.DocumentDirectoryPath}/bundle-drop`;
@@ -43,8 +53,8 @@ exports.bundleDropConfig = {
43
53
  org: { slug: exports.config.org.slug },
44
54
  project: { name: exports.config.project.name, slug: exports.config.project.slug },
45
55
  rollback: {
46
- maxCrashCount: exports.config.rollback?.maxCrashCount ?? 3,
56
+ maxCrashCount: configuredMaxCrashCount,
47
57
  healthCheckMode: exports.config.rollback?.healthCheckMode === 'manual' ? 'manual' : 'auto',
48
- healthyAfterSec: exports.config.rollback?.healthyAfterSec ?? 0,
58
+ healthyAfterSec: configuredHealthyAfterSec,
49
59
  },
50
60
  };
@@ -1,17 +1 @@
1
- export type BundlePointer = {
2
- hash: string;
3
- bundlePath: string;
4
- updatedAt: string;
5
- };
6
- export declare function readCurrentBundlePointer(): Promise<BundlePointer | null>;
7
- export declare function readPreviousBundlePointer(): Promise<BundlePointer | null>;
8
- export declare function writeCurrentBundlePointer(pointer: BundlePointer): Promise<void>;
9
- export declare function writePreviousBundlePointer(pointer: BundlePointer): Promise<void>;
10
- export declare function restorePreviousBundlePointer(pointer: BundlePointer | null): Promise<void>;
11
- export declare function setCurrentBundlePointer(_bundlePath: string, hash: string, options?: {
12
- setPrevious?: boolean;
13
- }): Promise<void>;
14
- export declare function rollbackToPreviousPointer(): Promise<BundlePointer | null>;
15
- export declare function deleteCurrentBundlePointer(): Promise<void>;
16
- export declare function deletePreviousBundlePointer(): Promise<void>;
17
- export declare function clearCurrentBundlePointer(): Promise<void>;
1
+ export declare function readCurrentBundleHash(): Promise<string | null>;
@@ -3,24 +3,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.readCurrentBundlePointer = readCurrentBundlePointer;
7
- exports.readPreviousBundlePointer = readPreviousBundlePointer;
8
- exports.writeCurrentBundlePointer = writeCurrentBundlePointer;
9
- exports.writePreviousBundlePointer = writePreviousBundlePointer;
10
- exports.restorePreviousBundlePointer = restorePreviousBundlePointer;
11
- exports.setCurrentBundlePointer = setCurrentBundlePointer;
12
- exports.rollbackToPreviousPointer = rollbackToPreviousPointer;
13
- exports.deleteCurrentBundlePointer = deleteCurrentBundlePointer;
14
- exports.deletePreviousBundlePointer = deletePreviousBundlePointer;
15
- exports.clearCurrentBundlePointer = clearCurrentBundlePointer;
6
+ exports.readCurrentBundleHash = readCurrentBundleHash;
16
7
  const fs_1 = __importDefault(require("../native/fs"));
17
8
  const context_1 = require("../context");
18
- const fsUtils_1 = require("./fsUtils");
19
9
  const CURRENT_POINTER_PATH = `${context_1.BUNDLE_DROP_ROOT}/current.json`;
20
- const PREVIOUS_POINTER_PATH = `${context_1.BUNDLE_DROP_ROOT}/previous.json`;
21
10
  const BUNDLE_HASH_PATTERN = /^[a-f0-9]{64}$/;
22
- const bundlePathForHash = (hash) => `${context_1.BUNDLE_DROP_ROOT}/bundles/${hash}/main.jsbundle`;
23
- async function readPointer(path) {
11
+ async function readPointerHash(path) {
24
12
  try {
25
13
  if (!(await fs_1.default.exists(path)))
26
14
  return null;
@@ -28,88 +16,12 @@ async function readPointer(path) {
28
16
  const parsed = JSON.parse(raw);
29
17
  if (!BUNDLE_HASH_PATTERN.test(parsed?.hash ?? ''))
30
18
  return null;
31
- return {
32
- hash: parsed.hash,
33
- bundlePath: bundlePathForHash(parsed.hash),
34
- updatedAt: typeof parsed.updatedAt === 'string' ? parsed.updatedAt : '',
35
- };
19
+ return parsed.hash;
36
20
  }
37
21
  catch {
38
22
  return null;
39
23
  }
40
24
  }
41
- async function readCurrentBundlePointer() {
42
- return readPointer(CURRENT_POINTER_PATH);
43
- }
44
- async function readPreviousBundlePointer() {
45
- return readPointer(PREVIOUS_POINTER_PATH);
46
- }
47
- async function writeCurrentBundlePointer(pointer) {
48
- assertCanonicalPointerHash(pointer.hash);
49
- const root = context_1.BUNDLE_DROP_ROOT;
50
- await (0, fsUtils_1.ensureDir)(root);
51
- await (0, fsUtils_1.atomicWriteJson)(CURRENT_POINTER_PATH, pointerJson(pointer));
52
- }
53
- async function writePreviousBundlePointer(pointer) {
54
- assertCanonicalPointerHash(pointer.hash);
55
- const root = context_1.BUNDLE_DROP_ROOT;
56
- await (0, fsUtils_1.ensureDir)(root);
57
- await (0, fsUtils_1.atomicWriteJson)(PREVIOUS_POINTER_PATH, pointerJson(pointer));
58
- }
59
- async function restorePreviousBundlePointer(pointer) {
60
- if (pointer) {
61
- await writePreviousBundlePointer({ ...pointer, updatedAt: new Date().toISOString() });
62
- return;
63
- }
64
- await deletePreviousBundlePointer();
65
- }
66
- async function setCurrentBundlePointer(_bundlePath, hash, options) {
67
- assertCanonicalPointerHash(hash);
68
- const root = context_1.BUNDLE_DROP_ROOT;
69
- await (0, fsUtils_1.ensureDir)(root);
70
- const current = await readCurrentBundlePointer();
71
- if (options?.setPrevious !== false && current?.hash && current?.bundlePath) {
72
- await writePreviousBundlePointer({ ...current, updatedAt: new Date().toISOString() });
73
- }
74
- await writeCurrentBundlePointer({
75
- hash,
76
- bundlePath: bundlePathForHash(hash),
77
- updatedAt: new Date().toISOString(),
78
- });
79
- }
80
- function pointerJson(pointer) {
81
- return {
82
- hash: pointer.hash,
83
- updatedAt: pointer.updatedAt,
84
- };
85
- }
86
- function assertCanonicalPointerHash(hash) {
87
- if (!BUNDLE_HASH_PATTERN.test(hash)) {
88
- throw new Error('Bundle pointer hash must be a canonical 64-character lowercase SHA-256 hash');
89
- }
90
- }
91
- async function rollbackToPreviousPointer() {
92
- const previous = await readPreviousBundlePointer();
93
- if (!previous)
94
- return null;
95
- await writeCurrentBundlePointer({ ...previous, updatedAt: new Date().toISOString() });
96
- return previous;
97
- }
98
- async function deleteCurrentBundlePointer() {
99
- if (await fs_1.default.exists(CURRENT_POINTER_PATH)) {
100
- await fs_1.default.unlink(CURRENT_POINTER_PATH);
101
- }
102
- }
103
- async function deletePreviousBundlePointer() {
104
- if (await fs_1.default.exists(PREVIOUS_POINTER_PATH)) {
105
- await fs_1.default.unlink(PREVIOUS_POINTER_PATH);
106
- }
107
- }
108
- async function clearCurrentBundlePointer() {
109
- try {
110
- await deleteCurrentBundlePointer();
111
- }
112
- catch {
113
- // Best-effort cleanup for callers that do not need strict rollback semantics.
114
- }
25
+ async function readCurrentBundleHash() {
26
+ return readPointerHash(CURRENT_POINTER_PATH);
115
27
  }
@@ -68,8 +68,8 @@ const finalizeInstall = async (verifiedTempDir, fileNames, hash, platform, statu
68
68
  existingManifest = await (0, bundleVerification_1.verifyBundleDir)(bundleDir, hash, platform);
69
69
  }
70
70
  catch (e) {
71
- const currentPointer = await (0, bundlePointer_1.readCurrentBundlePointer)();
72
- if (currentPointer?.hash === hash) {
71
+ const currentHash = await (0, bundlePointer_1.readCurrentBundleHash)();
72
+ if (currentHash === hash) {
73
73
  throw new Error('Active bundle folder failed verification');
74
74
  }
75
75
  }
@@ -82,8 +82,8 @@ const finalizeInstall = async (verifiedTempDir, fileNames, hash, platform, statu
82
82
  catch { /* best-effort cleanup */ }
83
83
  return { bundlePath, metadataFromZip };
84
84
  }
85
- const currentPointer = await (0, bundlePointer_1.readCurrentBundlePointer)();
86
- if (currentPointer?.hash === hash) {
85
+ const currentHash = await (0, bundlePointer_1.readCurrentBundleHash)();
86
+ if (currentHash === hash) {
87
87
  throw new Error('Active bundle folder failed verification');
88
88
  }
89
89
  await fs_1.default.unlink(bundleDir);