@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,6 +37,10 @@ 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.cleanupArtifacts = void 0;
41
+ exports.findProjectRoot = findProjectRoot;
42
+ exports.parseAndroidVersionFromGradle = parseAndroidVersionFromGradle;
43
+ exports.runUploadBundle = runUploadBundle;
40
44
  const axios_1 = __importDefault(require("axios"));
41
45
  const child_process_1 = require("child_process");
42
46
  const form_data_1 = __importDefault(require("form-data"));
@@ -44,8 +48,7 @@ const fs = __importStar(require("fs"));
44
48
  const os_1 = __importDefault(require("os"));
45
49
  const path = __importStar(require("path"));
46
50
  const plist = __importStar(require("plist"));
47
- const packageRoot = path.resolve(__dirname, '..', '..');
48
- const outputDir = path.join(packageRoot, 'dist');
51
+ const getPackageRoot = () => process.env.BUNDLE_DROP_PACKAGE_ROOT_OVERRIDE || path.resolve(__dirname, '..', '..');
49
52
  function findProjectRoot(startDir) {
50
53
  let dir = path.resolve(startDir);
51
54
  const MAX_UP = 12;
@@ -62,75 +65,6 @@ function findProjectRoot(startDir) {
62
65
  }
63
66
  return startDir;
64
67
  }
65
- // --- CONFIG LOADING ---
66
- const projectRoot = findProjectRoot(process.cwd());
67
- const configPath = path.resolve(projectRoot, 'bundle.drop.config.js');
68
- if (!fs.existsSync(configPath)) {
69
- console.error('❌ bundle.drop.config.js not found in project root');
70
- process.exit(1);
71
- }
72
- // eslint-disable-next-line
73
- const config = require(configPath);
74
- if (!config.project?.slug) {
75
- console.error('❌ Missing "project.slug" in bundle.drop.config.js');
76
- process.exit(1);
77
- }
78
- if (!config.org?.slug) {
79
- console.error('❌ Missing "org.slug" in bundle.drop.config.js');
80
- process.exit(1);
81
- }
82
- const serverUrl = config.serverUrl;
83
- const orgSlug = config.org.slug;
84
- const projectSlug = config.project.slug;
85
- // --- AUTH ---
86
- const authPath = path.join(os_1.default.homedir(), '.bundle-drop', 'auth.json');
87
- if (!fs.existsSync(authPath)) {
88
- console.error('❌ Not authenticated. Please run `bundle-drop login` first.');
89
- process.exit(1);
90
- }
91
- let token;
92
- try {
93
- const parsedAuth = JSON.parse(fs.readFileSync(authPath, 'utf-8'));
94
- token = parsedAuth.token;
95
- if (!token) {
96
- throw new Error('Token missing in auth file');
97
- }
98
- }
99
- catch (err) {
100
- console.error(`❌ Invalid auth file at ${authPath}:`, err.message);
101
- console.error('ℹ️ Please log in again with `bundle-drop login`.');
102
- process.exit(1);
103
- }
104
- // --- PARSE ARGS ---
105
- const platform = process.argv[2];
106
- const args = process.argv.slice(3);
107
- const plistArg = args.find(arg => arg.startsWith('--plist-file='));
108
- const plistFile = plistArg?.split('=')[1];
109
- const versionArg = args.find(arg => arg.startsWith('--version='));
110
- const versionFromFlag = versionArg?.split('=')[1];
111
- const buildGradleArg = args.find(arg => arg.startsWith('--buildgradle-path='));
112
- const buildGradlePath = buildGradleArg?.split('=')[1];
113
- const channelArg = args.find(arg => arg.startsWith('--channel='));
114
- const channelName = channelArg?.split('=')[1];
115
- const runtimeVersionArg = args.find(arg => arg.startsWith('--runtimeVersion='));
116
- const runtimeVersionOverride = runtimeVersionArg?.split('=')[1];
117
- const releaseNotesArg = args.find(arg => arg.startsWith('--release-notes='));
118
- let releaseNotes = releaseNotesArg ? releaseNotesArg.split('=')[1] : undefined;
119
- const MAX_NOTES = 2000;
120
- if (releaseNotes && releaseNotes.length > MAX_NOTES) {
121
- console.warn(`⚠️ Release notes too long (${releaseNotes.length}); truncating to ${MAX_NOTES} chars.`);
122
- releaseNotes = releaseNotes.slice(0, MAX_NOTES);
123
- }
124
- if (!platform || !['ios', 'android'].includes(platform)) {
125
- console.error('❌ Please pass a platform: ios or android');
126
- process.exit(1);
127
- }
128
- if (!channelName) {
129
- console.error('❌ Missing required --channel=name');
130
- process.exit(1);
131
- }
132
- // --- RESOLVE VERSION ---
133
- let version;
134
68
  function parseAndroidVersionFromGradle(filePath) {
135
69
  if (!fs.existsSync(filePath)) {
136
70
  console.error(`❌ build.gradle not found at ${filePath}`);
@@ -144,39 +78,139 @@ function parseAndroidVersionFromGradle(filePath) {
144
78
  }
145
79
  return match[1];
146
80
  }
147
- if (platform === 'ios') {
148
- if (versionFromFlag) {
149
- version = versionFromFlag;
81
+ const cleanupArtifacts = (platform, zipPath) => {
82
+ const outputDir = path.join(getPackageRoot(), 'dist');
83
+ try {
84
+ if (fs.existsSync(zipPath)) {
85
+ fs.unlinkSync(zipPath);
86
+ console.log(`🧹 Deleted: ${zipPath}`);
87
+ }
88
+ const suffix = platform === 'ios' ? 'ios' : 'android';
89
+ const metadataPath = path.join(outputDir, `metadata-${suffix}.json`);
90
+ const assetsPath = path.join(outputDir, 'assets');
91
+ if (fs.existsSync(metadataPath)) {
92
+ fs.unlinkSync(metadataPath);
93
+ console.log(`🧹 Deleted: ${metadataPath}`);
94
+ }
95
+ if (fs.existsSync(assetsPath)) {
96
+ fs.rmSync(assetsPath, { recursive: true, force: true });
97
+ console.log(`🧹 Deleted: ${assetsPath}`);
98
+ }
99
+ const bundlePath = path.join(outputDir, 'main.jsbundle');
100
+ if (fs.existsSync(bundlePath)) {
101
+ fs.unlinkSync(bundlePath);
102
+ console.log(`🧹 Deleted: ${bundlePath}`);
103
+ }
150
104
  }
151
- else {
152
- if (!plistFile) {
153
- console.error('❌ Please provide --plist-file=path/to/Info.plist or --version for iOS');
154
- process.exit(1);
105
+ catch (err) {
106
+ console.warn('⚠️ Cleanup failed:', err);
107
+ }
108
+ };
109
+ exports.cleanupArtifacts = cleanupArtifacts;
110
+ async function runUploadBundle(options) {
111
+ const packageRoot = getPackageRoot();
112
+ const outputDir = path.join(packageRoot, 'dist');
113
+ const argv = options?.argv || process.argv;
114
+ const projectRoot = findProjectRoot(options?.cwd || process.cwd());
115
+ const configPath = path.resolve(projectRoot, 'bundle.drop.config.js');
116
+ if (!fs.existsSync(configPath)) {
117
+ console.error('❌ bundle.drop.config.js not found in project root');
118
+ process.exit(1);
119
+ }
120
+ // eslint-disable-next-line
121
+ const config = require(configPath);
122
+ if (!config.serverUrl) {
123
+ console.error('❌ Missing "serverUrl" in bundle.drop.config.js');
124
+ process.exit(1);
125
+ }
126
+ if (!config.project?.slug) {
127
+ console.error('❌ Missing "project.slug" in bundle.drop.config.js');
128
+ process.exit(1);
129
+ }
130
+ if (!config.org?.slug) {
131
+ console.error('❌ Missing "org.slug" in bundle.drop.config.js');
132
+ process.exit(1);
133
+ }
134
+ const serverUrl = config.serverUrl;
135
+ const orgSlug = config.org.slug;
136
+ const projectSlug = config.project.slug;
137
+ const authPath = path.join(os_1.default.homedir(), '.bundle-drop', 'auth.json');
138
+ if (!fs.existsSync(authPath)) {
139
+ console.error('❌ Not authenticated. Please run `bundle-drop login` first.');
140
+ process.exit(1);
141
+ }
142
+ let token;
143
+ try {
144
+ const parsedAuth = JSON.parse(fs.readFileSync(authPath, 'utf-8'));
145
+ token = parsedAuth.token;
146
+ if (!token) {
147
+ throw new Error('Token missing in auth file');
155
148
  }
156
- try {
157
- const plistContent = fs.readFileSync(plistFile, 'utf-8');
158
- const parsed = plist.parse(plistContent);
159
- version = parsed.CFBundleShortVersionString;
160
- if (!version) {
161
- console.error('❌ Could not find CFBundleShortVersionString in plist');
149
+ }
150
+ catch (err) {
151
+ console.error(`❌ Invalid auth file at ${authPath}:`, err.message);
152
+ console.error('ℹ️ Please log in again with `bundle-drop login`.');
153
+ process.exit(1);
154
+ }
155
+ const platform = argv[2];
156
+ const args = argv.slice(3);
157
+ const plistArg = args.find(arg => arg.startsWith('--plist-file='));
158
+ const plistFile = plistArg?.split('=')[1];
159
+ const versionArg = args.find(arg => arg.startsWith('--version='));
160
+ const versionFromFlag = versionArg?.split('=')[1];
161
+ const buildGradleArg = args.find(arg => arg.startsWith('--buildgradle-path='));
162
+ const buildGradlePath = buildGradleArg?.split('=')[1];
163
+ const channelArg = args.find(arg => arg.startsWith('--channel='));
164
+ const channelName = channelArg?.split('=')[1];
165
+ const runtimeVersionArg = args.find(arg => arg.startsWith('--runtimeVersion='));
166
+ const runtimeVersionOverride = runtimeVersionArg?.split('=')[1];
167
+ const releaseNotesArg = args.find(arg => arg.startsWith('--release-notes='));
168
+ let releaseNotes = releaseNotesArg ? releaseNotesArg.split('=')[1] : undefined;
169
+ const MAX_NOTES = 2000;
170
+ if (releaseNotes && releaseNotes.length > MAX_NOTES) {
171
+ console.warn(`⚠️ Release notes too long (${releaseNotes.length}); truncating to ${MAX_NOTES} chars.`);
172
+ releaseNotes = releaseNotes.slice(0, MAX_NOTES);
173
+ }
174
+ if (!platform || !['ios', 'android'].includes(platform)) {
175
+ console.error('❌ Please pass a platform: ios or android');
176
+ process.exit(1);
177
+ }
178
+ if (!channelName) {
179
+ console.error('❌ Missing required --channel=name');
180
+ process.exit(1);
181
+ }
182
+ let version;
183
+ if (platform === 'ios') {
184
+ if (versionFromFlag) {
185
+ version = versionFromFlag;
186
+ }
187
+ else {
188
+ if (!plistFile) {
189
+ console.error('❌ Please provide --plist-file=path/to/Info.plist or --version for iOS');
190
+ process.exit(1);
191
+ }
192
+ try {
193
+ const plistContent = fs.readFileSync(plistFile, 'utf-8');
194
+ const parsed = plist.parse(plistContent);
195
+ version = parsed.CFBundleShortVersionString;
196
+ if (!version) {
197
+ console.error('❌ Could not find CFBundleShortVersionString in plist');
198
+ process.exit(1);
199
+ }
200
+ }
201
+ catch (err) {
202
+ console.error('❌ Failed to read plist file:', err);
162
203
  process.exit(1);
163
204
  }
164
- }
165
- catch (err) {
166
- console.error('❌ Failed to read plist file:', err);
167
- process.exit(1);
168
205
  }
169
206
  }
170
- }
171
- else {
172
- if (versionFromFlag) {
207
+ else if (versionFromFlag) {
173
208
  version = versionFromFlag;
174
209
  }
175
210
  else if (buildGradlePath) {
176
211
  version = parseAndroidVersionFromGradle(path.resolve(projectRoot, buildGradlePath));
177
212
  }
178
213
  else {
179
- // default to android/app/build.gradle when available
180
214
  const defaultGradlePath = path.join(projectRoot, 'android', 'app', 'build.gradle');
181
215
  if (fs.existsSync(defaultGradlePath)) {
182
216
  version = parseAndroidVersionFromGradle(defaultGradlePath);
@@ -186,96 +220,66 @@ else {
186
220
  process.exit(1);
187
221
  }
188
222
  }
189
- }
190
- let runtimeVersion;
191
- // --- BUNDLE STEP ---
192
- const compiledBundleScript = path.join(packageRoot, 'lib', 'scripts', 'bundle.js');
193
- const tsBundleScript = path.join(packageRoot, 'src', 'scripts', 'bundle.ts');
194
- const bundleCommand = fs.existsSync(compiledBundleScript) ? `node ${compiledBundleScript}` : `ts-node ${tsBundleScript}`;
195
- try {
196
- console.log(`📦 Running bundler for ${platform}...`);
197
- (0, child_process_1.execSync)(`${bundleCommand} ${platform}`, {
198
- stdio: 'inherit',
199
- });
200
- const suffix = platform === 'ios' ? 'ios' : 'android';
201
- const metadataPath = path.join(outputDir, `metadata-${suffix}.json`);
202
- try {
203
- const parsed = JSON.parse(fs.readFileSync(metadataPath, 'utf-8'));
204
- runtimeVersion = parsed.runtimeVersion;
205
- if (runtimeVersion) {
206
- console.log(`🆔 Runtime Version: ${runtimeVersion}`);
207
- }
208
- }
209
- catch {
210
- // ignore; backend can derive from metadata in zip
211
- }
212
- if (runtimeVersionOverride) {
213
- runtimeVersion = runtimeVersionOverride;
214
- console.log(`🆔 Runtime Version (override flag): ${runtimeVersion}`);
215
- }
216
- else if (!runtimeVersion) {
217
- runtimeVersion = config.runtimeVersion?.[platform];
218
- if (runtimeVersion) {
219
- console.log(`🆔 Runtime Version (from config): ${runtimeVersion}`);
220
- }
221
- }
222
- if (!runtimeVersion) {
223
- console.error('❌ runtimeVersion could not be determined; aborting upload.');
224
- process.exit(1);
225
- }
226
- }
227
- catch (err) {
228
- console.error('❌ Failed to bundle:', err);
229
- process.exit(1);
230
- }
231
- // --- UPLOAD STEP ---
232
- const zipPath = path.join(outputDir, `bundle-${platform}.zip`);
233
- if (!fs.existsSync(zipPath)) {
234
- console.error(`❌ Bundle ZIP not found at ${zipPath}`);
235
- process.exit(1);
236
- }
237
- const form = new form_data_1.default();
238
- // Prefer the new server key; keep legacy for compatibility.
239
- form.append('orgSlug', orgSlug);
240
- form.append('projectSlug', projectSlug);
241
- form.append('project', projectSlug);
242
- form.append('platform', platform);
243
- form.append('version', version);
244
- form.append('channelName', channelName);
245
- form.append('runtimeVersion', runtimeVersion);
246
- if (releaseNotes) {
247
- form.append('releaseNotes', releaseNotes);
248
- }
249
- form.append('file', fs.createReadStream(zipPath));
250
- console.log(`⬆️ Uploading ${platform} bundle (v${version}) to project "${projectSlug}" at ${serverUrl}...`);
251
- const cleanupArtifacts = () => {
223
+ let runtimeVersion;
224
+ const compiledBundleScript = path.join(packageRoot, 'lib', 'scripts', 'bundle.js');
225
+ const tsBundleScript = path.join(packageRoot, 'src', 'scripts', 'bundle.ts');
226
+ const bundleCommand = fs.existsSync(compiledBundleScript)
227
+ ? `node ${compiledBundleScript}`
228
+ : `ts-node ${tsBundleScript}`;
252
229
  try {
253
- if (fs.existsSync(zipPath)) {
254
- fs.unlinkSync(zipPath);
255
- console.log(`🧹 Deleted: ${zipPath}`);
256
- }
230
+ console.log(`📦 Running bundler for ${platform}...`);
231
+ (0, child_process_1.execSync)(`${bundleCommand} ${platform}`, {
232
+ stdio: 'inherit',
233
+ });
257
234
  const suffix = platform === 'ios' ? 'ios' : 'android';
258
235
  const metadataPath = path.join(outputDir, `metadata-${suffix}.json`);
259
- const assetsPath = path.join(outputDir, 'assets');
260
- if (fs.existsSync(metadataPath)) {
261
- fs.unlinkSync(metadataPath);
262
- console.log(`🧹 Deleted: ${metadataPath}`);
236
+ try {
237
+ const parsed = JSON.parse(fs.readFileSync(metadataPath, 'utf-8'));
238
+ runtimeVersion = parsed.runtimeVersion;
239
+ if (runtimeVersion) {
240
+ console.log(`🆔 Runtime Version: ${runtimeVersion}`);
241
+ }
263
242
  }
264
- if (fs.existsSync(assetsPath)) {
265
- fs.rmSync(assetsPath, { recursive: true, force: true });
266
- console.log(`🧹 Deleted: ${assetsPath}`);
243
+ catch {
244
+ // ignore; backend can derive from metadata in zip
267
245
  }
268
- const bundlePath = path.join(outputDir, 'main.jsbundle');
269
- if (fs.existsSync(bundlePath)) {
270
- fs.unlinkSync(bundlePath);
271
- console.log(`🧹 Deleted: ${bundlePath}`);
246
+ if (runtimeVersionOverride) {
247
+ runtimeVersion = runtimeVersionOverride;
248
+ console.log(`🆔 Runtime Version (override flag): ${runtimeVersion}`);
249
+ }
250
+ else if (!runtimeVersion) {
251
+ runtimeVersion = config.runtimeVersion?.[platform];
252
+ if (runtimeVersion) {
253
+ console.log(`🆔 Runtime Version (from config): ${runtimeVersion}`);
254
+ }
255
+ }
256
+ if (!runtimeVersion) {
257
+ console.error('❌ runtimeVersion could not be determined; aborting upload.');
258
+ process.exit(1);
272
259
  }
273
260
  }
274
261
  catch (err) {
275
- console.warn('⚠️ Cleanup failed:', err);
262
+ console.error('❌ Failed to bundle:', err);
263
+ process.exit(1);
276
264
  }
277
- };
278
- (async () => {
265
+ const zipPath = path.join(outputDir, `bundle-${platform}.zip`);
266
+ if (!fs.existsSync(zipPath)) {
267
+ console.error(`❌ Bundle ZIP not found at ${zipPath}`);
268
+ process.exit(1);
269
+ }
270
+ const form = new form_data_1.default();
271
+ form.append('orgSlug', orgSlug);
272
+ form.append('projectSlug', projectSlug);
273
+ form.append('project', projectSlug);
274
+ form.append('platform', platform);
275
+ form.append('version', version);
276
+ form.append('channelName', channelName);
277
+ form.append('runtimeVersion', runtimeVersion);
278
+ if (releaseNotes) {
279
+ form.append('releaseNotes', releaseNotes);
280
+ }
281
+ form.append('file', fs.createReadStream(zipPath));
282
+ console.log(`⬆️ Uploading ${platform} bundle (v${version}) to project "${projectSlug}" at ${serverUrl}...`);
279
283
  try {
280
284
  const res = await axios_1.default.post(`${serverUrl}/bundle/upload`, form, {
281
285
  headers: {
@@ -286,12 +290,16 @@ const cleanupArtifacts = () => {
286
290
  maxBodyLength: Infinity,
287
291
  });
288
292
  console.log('✅ Upload complete:', res.data);
293
+ return res.data;
289
294
  }
290
295
  catch (err) {
291
296
  console.error('❌ Upload failed:', err?.response?.data || err.message);
292
297
  throw err;
293
298
  }
294
299
  finally {
295
- cleanupArtifacts();
300
+ (0, exports.cleanupArtifacts)(platform, zipPath);
296
301
  }
297
- })().catch(() => process.exit(1));
302
+ }
303
+ if (require.main === module) {
304
+ runUploadBundle().catch(() => process.exit(1));
305
+ }
@@ -1,17 +1,20 @@
1
1
  import type { BundleInfo } from './bundleInfo';
2
2
  import type { AvailableBundlesPage, GetAvailableBundlesOptions } from './manager/updateCheck';
3
- import { DownloadUpdateResult } from './manager/downloadAndInstall';
4
- import { ApplyUpdateResult } from './manager/updateState';
3
+ import type { DownloadUpdateResult } from './manager/downloadAndInstall';
4
+ import type { ApplyUpdateResult } from './manager/updateState';
5
5
  import type { UpdateCheckResponse, BundleListItem } from './api/types';
6
- type UseBundleDropOptions = {
7
- /** Channel to target; defaults to config.defaultChannel or "General". */
8
- channelName?: string;
9
- };
10
- type UseBundleDropReturn = {
6
+ /**
7
+ * Live BundleDrop runtime state plus UI-facing actions for manual OTA flows.
8
+ */
9
+ export type UseBundleDropReturn = {
11
10
  /** Last human-readable status message (downloads, checks, applies). */
12
11
  status: string;
12
+ /** Whether BundleDrop is active for this runtime. */
13
+ isEnabled: boolean;
13
14
  /** True while any bundle-drop action is running; use to disable UI. */
14
15
  isBusy: boolean;
16
+ /** Active runtime channel used by singleton OTA actions. */
17
+ channelName: string;
15
18
  /** Locally stored bundle metadata (bundleVersion, hash, etc.), if any. */
16
19
  installedInfo: BundleInfo | null;
17
20
  /** True when a downloaded bundle is waiting to be applied. */
@@ -37,6 +40,8 @@ type UseBundleDropReturn = {
37
40
  fetchAvailableChannels: () => Promise<string[]>;
38
41
  /** Last fetched list of channel names. */
39
42
  availableChannels: string[];
43
+ /** Update the active runtime channel for singleton OTA actions. */
44
+ setChannel: (channelName: string) => void;
40
45
  /** Fetch a paginated list of downloadable bundles for a channel. */
41
46
  fetchBundles: (options?: GetAvailableBundlesOptions) => Promise<AvailableBundlesPage>;
42
47
  /** Download and stage a specific bundle by its metadata from fetchBundles. */
@@ -45,5 +50,10 @@ type UseBundleDropReturn = {
45
50
  status?: string;
46
51
  }>;
47
52
  };
48
- export declare function useBundleDrop(options?: UseBundleDropOptions): UseBundleDropReturn;
49
- export {};
53
+ /**
54
+ * React hook for subscribing to the singleton BundleDrop runtime.
55
+ *
56
+ * It is safe to call even before `BundleDrop.init(...)` runs. In that case the hook
57
+ * warns once and exposes a disabled no-op snapshot until runtime init happens.
58
+ */
59
+ export declare function useBundleDrop(): UseBundleDropReturn;
@@ -2,178 +2,32 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.useBundleDrop = useBundleDrop;
4
4
  const react_1 = require("react");
5
- const context_1 = require("./context");
6
- const updateCheck_1 = require("./manager/updateCheck");
7
- const downloadAndInstall_1 = require("./manager/downloadAndInstall");
8
- const updateState_1 = require("./manager/updateState");
9
- const rollbackState_1 = require("./manager/rollbackState");
10
- const initUpdateManager_1 = require("./manager/initUpdateManager");
11
- function useBundleDrop(options) {
12
- const channelName = options?.channelName || context_1.defaultChannel;
13
- const [status, setStatus] = (0, react_1.useState)('Click the button to check for updates');
14
- const [installedInfo, setInstalledInfo] = (0, react_1.useState)(null);
15
- const [pendingApply, setPendingApply] = (0, react_1.useState)(false);
16
- const [hasBundle, setHasBundle] = (0, react_1.useState)(false);
17
- const [isBusy, setIsBusy] = (0, react_1.useState)(false);
18
- const [availableChannels, setAvailableChannels] = (0, react_1.useState)([]);
19
- const refresh = (0, react_1.useCallback)(async () => {
20
- const state = await (0, updateState_1.getUpdateState)();
21
- setInstalledInfo(state.info || null);
22
- setPendingApply(state.pendingApply);
23
- setHasBundle(state.hasBundle);
24
- }, []);
25
- const withBusy = (0, react_1.useCallback)(async (fn) => {
26
- if (!(0, initUpdateManager_1.acquireUpdateLock)()) {
27
- throw new Error('Another update flow is already in progress');
28
- }
29
- setIsBusy(true);
30
- try {
31
- const result = await fn();
32
- await refresh();
33
- return result;
34
- }
35
- finally {
36
- setIsBusy(false);
37
- (0, initUpdateManager_1.releaseUpdateLock)();
38
- }
39
- }, [refresh]);
40
- const checkLatest = (0, react_1.useCallback)(async () => {
41
- return withBusy(async () => {
42
- const res = await (0, updateCheck_1.checkForUpdate)(channelName, msg => setStatus(msg));
43
- if (!res) {
44
- const nextStatus = '⚠️ Unable to check for updates. Try again.';
45
- setStatus(nextStatus);
46
- return { response: null, status: nextStatus };
47
- }
48
- if (res.action === 'ROLLBACK') {
49
- const nextStatus = res.reason ? `↩️ Rollback requested: ${res.reason}` : '↩️ Rollback requested';
50
- setStatus(nextStatus);
51
- return { response: res, status: nextStatus };
52
- }
53
- if (res.incompatible) {
54
- const nextStatus = '⛔️ No compatible update for this binary';
55
- setStatus(nextStatus);
56
- return { response: res, status: nextStatus };
57
- }
58
- if (res.action === 'NOOP') {
59
- const nextStatus = '✅ You have the latest version';
60
- setStatus(nextStatus);
61
- return { response: res, status: nextStatus };
62
- }
63
- const nextLabel = res.bundleVersion
64
- ? `⬇️ Update available${res.bundleVersion ? ` (v${res.bundleVersion})` : ''}`
65
- : '⬇️ Update available';
66
- setStatus(nextLabel);
67
- return { response: res, status: nextLabel };
68
- });
69
- }, [channelName, withBusy]);
70
- const downloadAndStage = (0, react_1.useCallback)(async () => {
71
- return withBusy(async () => {
72
- const result = await (0, downloadAndInstall_1.downloadUpdate)({ channelName }, msg => setStatus(msg));
73
- if (result.status === 'upToDate') {
74
- const nextStatus = '✅ You have the latest version';
75
- setStatus(nextStatus);
76
- return { result, status: nextStatus };
77
- }
78
- if (result.status === 'rollback') {
79
- const nextStatus = result.reason ? `↩️ Rollback requested: ${result.reason}` : '↩️ Rollback requested';
80
- setStatus(nextStatus);
81
- return { result, status: nextStatus };
82
- }
83
- if (result.status === 'incompatible') {
84
- const nextStatus = '⛔️ No compatible update for this binary';
85
- setStatus(nextStatus);
86
- return { result, status: nextStatus };
87
- }
88
- const nextStatus = '✅ Update downloaded. Will apply on next launch or when you call applyUpdate.';
89
- setStatus(nextStatus);
90
- return { result, status: nextStatus };
91
- });
92
- }, [channelName, withBusy]);
93
- const applyUpdate = (0, react_1.useCallback)(async () => {
94
- return withBusy(async () => {
95
- const applied = await (0, updateState_1.applyUpdate)(msg => setStatus(msg));
96
- let nextStatus;
97
- if (applied.status === 'applied') {
98
- nextStatus = '✅ Update applied, reloading...';
99
- setStatus(nextStatus);
100
- }
101
- if (applied.status === 'noBundle') {
102
- nextStatus = '⚠️ No downloaded bundle to apply';
103
- setStatus(nextStatus);
104
- }
105
- if (applied.status === 'alreadyApplied') {
106
- nextStatus = 'ℹ️ Bundle already applied';
107
- setStatus(nextStatus);
108
- }
109
- return { result: applied, status: nextStatus };
110
- });
111
- }, [withBusy]);
112
- const fetchAvailableChannels = (0, react_1.useCallback)(async () => {
113
- setIsBusy(true);
114
- try {
115
- const channels = await (0, updateCheck_1.getAvailableChannels)();
116
- setAvailableChannels(channels);
117
- return channels;
118
- }
119
- catch (e) {
120
- setStatus('⚠️ Unable to fetch channels.');
121
- return [];
122
- }
123
- finally {
124
- setIsBusy(false);
125
- }
126
- }, [setAvailableChannels, setStatus]);
127
- const fetchBundles = (0, react_1.useCallback)(async (options) => {
128
- setIsBusy(true);
129
- try {
130
- return await (0, updateCheck_1.getAvailableBundles)({
131
- channelName: options?.channelName || channelName,
132
- ...options,
133
- });
134
- }
135
- catch (e) {
136
- setStatus('⚠️ Unable to fetch bundles.');
137
- return { items: [], nextCursor: null, hasMore: false };
138
- }
139
- finally {
140
- setIsBusy(false);
141
- }
142
- }, [channelName]);
143
- const installBundleFromItem = (0, react_1.useCallback)(async (bundle) => {
144
- if (!bundle.downloadUrl) {
145
- const nextStatus = '⚠️ Bundle is not downloadable (expired or unavailable)';
146
- setStatus(nextStatus);
147
- return { result: { status: 'incompatible' }, status: nextStatus };
148
- }
149
- return withBusy(async () => {
150
- const result = await (0, downloadAndInstall_1.installBundle)(bundle.hash, bundle.downloadUrl, bundle.bundleVersion, bundle.version, bundle.runtimeVersion, { channelName, onStatusUpdate: msg => setStatus(msg) });
151
- if (result.status === 'staged') {
152
- const nextStatus = `✅ v${bundle.bundleVersion} downloaded. Will apply on next launch or when you call applyUpdate.`;
153
- setStatus(nextStatus);
154
- return { result, status: nextStatus };
155
- }
156
- return { result, status: undefined };
157
- });
158
- }, [channelName, withBusy]);
159
- (0, react_1.useEffect)(() => {
160
- refresh();
161
- if (!(0, initUpdateManager_1.isUpdateFlowActive)()) {
162
- (0, rollbackState_1.commitActiveBundle)();
163
- }
164
- }, [refresh]);
5
+ const initState_1 = require("./runtime/initState");
6
+ const service_1 = require("./runtime/service");
7
+ /**
8
+ * React hook for subscribing to the singleton BundleDrop runtime.
9
+ *
10
+ * It is safe to call even before `BundleDrop.init(...)` runs. In that case the hook
11
+ * warns once and exposes a disabled no-op snapshot until runtime init happens.
12
+ */
13
+ function useBundleDrop() {
14
+ (0, initState_1.getBundleDropRuntimeConfigOrWarn)();
15
+ const state = (0, react_1.useSyncExternalStore)(service_1.subscribeBundleDropState, service_1.getBundleDropSnapshot, service_1.getBundleDropSnapshot);
165
16
  return {
166
- status,
167
- isBusy,
168
- installedInfo,
169
- pendingApply,
170
- hasBundle,
171
- checkLatest,
172
- downloadUpdate: downloadAndStage,
173
- applyUpdate,
174
- fetchAvailableChannels,
175
- availableChannels,
176
- fetchBundles,
177
- installBundle: installBundleFromItem,
17
+ status: state.status,
18
+ isEnabled: state.isEnabled,
19
+ isBusy: state.isBusy,
20
+ channelName: state.channelName,
21
+ installedInfo: state.installedInfo,
22
+ pendingApply: state.pendingApply,
23
+ hasBundle: state.hasBundle,
24
+ checkLatest: service_1.checkLatest,
25
+ downloadUpdate: service_1.downloadAndStage,
26
+ applyUpdate: service_1.applyDownloadedUpdate,
27
+ fetchAvailableChannels: service_1.fetchAvailableChannels,
28
+ availableChannels: state.availableChannels,
29
+ setChannel: service_1.setChannel,
30
+ fetchBundles: service_1.fetchAvailableBundles,
31
+ installBundle: service_1.installBundleFromListItem,
178
32
  };
179
33
  }