@gfean/react-native-bundle-drop 0.1.95 → 0.2.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.
@@ -8,6 +8,8 @@ type Org = {
8
8
  orgId: string;
9
9
  name: string;
10
10
  };
11
+ export declare function getBundleDropConfigPath(startDir?: string): string;
12
+ export declare function hasExistingBundleDropConfig(startDir?: string): boolean;
11
13
  export declare function initConfig(params: {
12
14
  serverUrl: string;
13
15
  projects: Project[];
@@ -3,6 +3,8 @@ 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.getBundleDropConfigPath = getBundleDropConfigPath;
7
+ exports.hasExistingBundleDropConfig = hasExistingBundleDropConfig;
6
8
  exports.initConfig = initConfig;
7
9
  const axios_1 = __importDefault(require("axios"));
8
10
  const chalk_1 = __importDefault(require("chalk"));
@@ -43,9 +45,15 @@ function findProjectRoot(startDir) {
43
45
  }
44
46
  return startDir;
45
47
  }
48
+ function getBundleDropConfigPath(startDir = process.cwd()) {
49
+ const projectRoot = findProjectRoot(startDir);
50
+ return path_1.default.join(projectRoot, 'bundle.drop.config.js');
51
+ }
52
+ function hasExistingBundleDropConfig(startDir = process.cwd()) {
53
+ return fs_extra_1.default.existsSync(getBundleDropConfigPath(startDir));
54
+ }
46
55
  async function initConfig(params) {
47
- const projectRoot = findProjectRoot(process.cwd());
48
- const configPath = path_1.default.join(projectRoot, 'bundle.drop.config.js');
56
+ const configPath = getBundleDropConfigPath();
49
57
  if (fs_extra_1.default.existsSync(configPath)) {
50
58
  console.log(chalk_1.default.yellow(`ℹ️ bundle.drop.config.js already exists at ${configPath}. If this is accidental, delete it and rerun the init/login.`));
51
59
  return;
@@ -3,58 +3,277 @@ 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
- // src/CLI/scripts/login-cli.ts
7
6
  const axios_1 = __importDefault(require("axios"));
8
7
  const chalk_1 = __importDefault(require("chalk"));
9
8
  const fs_extra_1 = __importDefault(require("fs-extra"));
9
+ const http_1 = __importDefault(require("http"));
10
10
  const os_1 = __importDefault(require("os"));
11
11
  const path_1 = __importDefault(require("path"));
12
12
  const prompts_1 = __importDefault(require("prompts"));
13
+ const child_process_1 = require("child_process");
13
14
  const init_config_1 = require("./init-config");
14
15
  const post_init_1 = require("./post-init");
15
- const login = async () => {
16
- const { email, password } = await (0, prompts_1.default)([
17
- {
18
- type: 'text',
19
- name: 'email',
20
- message: 'Enter your email:',
21
- },
22
- {
23
- type: 'password',
24
- name: 'password',
25
- message: 'Enter your password:',
16
+ const LOGIN_TIMEOUT_MS = 10 * 60 * 1000;
17
+ const getBaseUrl = () => process.env.BUNDLE_DROP_SERVER_URL
18
+ ? process.env.BUNDLE_DROP_SERVER_URL.replace(/\/$/, '')
19
+ : 'https://api.bundledrop.app';
20
+ const getClientName = () => {
21
+ const hostname = os_1.default.hostname();
22
+ const termProgram = (process.env.TERM_PROGRAM || '').toLowerCase();
23
+ const term = (process.env.TERM || '').toLowerCase();
24
+ if (process.env.CURSOR_TRACE_ID || process.env.CURSOR_AGENT) {
25
+ return `Cursor on ${hostname}`;
26
+ }
27
+ if (process.env.VSCODE_GIT_IPC_HANDLE || termProgram === 'vscode') {
28
+ return `VS Code on ${hostname}`;
29
+ }
30
+ if (termProgram.includes('warp')) {
31
+ return `Warp on ${hostname}`;
32
+ }
33
+ if (term.includes('windsurf')) {
34
+ return `Windsurf on ${hostname}`;
35
+ }
36
+ return `your IDE on ${hostname}`;
37
+ };
38
+ const openBrowser = async (url) => {
39
+ const platform = process.platform;
40
+ const command = platform === 'darwin'
41
+ ? { file: 'open', args: [url] }
42
+ : platform === 'win32'
43
+ ? { file: 'cmd', args: ['/c', 'start', '', url] }
44
+ : { file: 'xdg-open', args: [url] };
45
+ await new Promise((resolve, reject) => {
46
+ const child = (0, child_process_1.spawn)(command.file, command.args, {
47
+ detached: true,
48
+ stdio: 'ignore',
49
+ });
50
+ child.once('error', reject);
51
+ child.once('spawn', () => resolve());
52
+ child.unref();
53
+ });
54
+ };
55
+ const writeAuthFile = async ({ payload, serverUrl, }) => {
56
+ const tokenPath = path_1.default.join(os_1.default.homedir(), '.bundle-drop', 'auth.json');
57
+ const authFile = {
58
+ token: payload.token,
59
+ user: {
60
+ email: payload.email,
61
+ firstName: payload.firstName,
62
+ lastName: payload.lastName,
26
63
  },
27
- ]);
64
+ projects: payload.projects || [],
65
+ organizations: payload.organizations || [],
66
+ memberships: payload.memberships || [],
67
+ downloadApiKey: payload.downloadApiKey || '',
68
+ serverUrl,
69
+ };
70
+ await fs_extra_1.default.ensureDir(path_1.default.dirname(tokenPath));
71
+ await fs_extra_1.default.writeJson(tokenPath, authFile, { spaces: 2 });
72
+ return authFile;
73
+ };
74
+ const respondJson = (res, statusCode, body) => {
75
+ res.writeHead(statusCode, {
76
+ 'Content-Type': 'application/json',
77
+ Connection: 'close',
78
+ 'Access-Control-Allow-Origin': '*',
79
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
80
+ 'Access-Control-Allow-Headers': 'Content-Type',
81
+ });
82
+ res.end(JSON.stringify(body));
83
+ };
84
+ const readJsonBody = (req) => new Promise((resolve, reject) => {
85
+ let raw = '';
86
+ req.setEncoding('utf8');
87
+ req.on('data', chunk => {
88
+ raw += chunk;
89
+ if (raw.length > 20000) {
90
+ reject(new Error('CLI callback payload is too large'));
91
+ req.destroy();
92
+ }
93
+ });
94
+ req.on('end', () => resolve(raw));
95
+ req.on('error', reject);
96
+ });
97
+ const createLoginSession = async ({ baseUrl, clientName, callbackUrl, }) => {
98
+ const response = await axios_1.default.post(`${baseUrl}/auth/cli/sessions`, {
99
+ clientName,
100
+ callbackUrl,
101
+ });
102
+ return response.data;
103
+ };
104
+ const exchangeSession = async ({ baseUrl, payload, }) => {
105
+ const response = await axios_1.default.post(`${baseUrl}/auth/cli/exchange`, payload);
106
+ return response.data;
107
+ };
108
+ const waitForExchangeWithTimeout = (exchangePromise) => new Promise((resolve, reject) => {
109
+ const timeout = setTimeout(() => {
110
+ reject(new Error('Timed out waiting for browser authorization'));
111
+ }, LOGIN_TIMEOUT_MS);
112
+ timeout.unref();
113
+ exchangePromise.then(payload => {
114
+ clearTimeout(timeout);
115
+ resolve(payload);
116
+ }, error => {
117
+ clearTimeout(timeout);
118
+ reject(error);
119
+ });
120
+ });
121
+ const startCallbackServer = ({ baseUrl, }) => new Promise((resolve, reject) => {
122
+ let settled = false;
123
+ let exchangeInFlight = false;
124
+ let exchangeResolve = null;
125
+ let exchangeReject = null;
126
+ const sockets = new Set();
127
+ const exchangePromise = new Promise((innerResolve, innerReject) => {
128
+ exchangeResolve = innerResolve;
129
+ exchangeReject = innerReject;
130
+ });
131
+ const server = http_1.default.createServer(async (req, res) => {
132
+ if (req.method === 'OPTIONS') {
133
+ res.writeHead(204, {
134
+ 'Access-Control-Allow-Origin': '*',
135
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
136
+ 'Access-Control-Allow-Headers': 'Content-Type',
137
+ });
138
+ res.end();
139
+ return;
140
+ }
141
+ if (req.method !== 'POST' || req.url !== '/callback') {
142
+ respondJson(res, 404, { error: 'Not found' });
143
+ return;
144
+ }
145
+ if (exchangeInFlight) {
146
+ respondJson(res, 409, { error: 'CLI login is already being completed' });
147
+ return;
148
+ }
149
+ exchangeInFlight = true;
150
+ try {
151
+ const rawBody = await readJsonBody(req);
152
+ const parsed = JSON.parse(rawBody || '{}');
153
+ const sessionId = typeof parsed.sessionId === 'string' ? parsed.sessionId.trim() : '';
154
+ const state = typeof parsed.state === 'string' ? parsed.state.trim() : '';
155
+ const exchangeCode = typeof parsed.exchangeCode === 'string' ? parsed.exchangeCode.trim() : '';
156
+ if (!sessionId || !state || !exchangeCode) {
157
+ throw new Error('Missing CLI login callback payload');
158
+ }
159
+ const authPayload = await exchangeSession({
160
+ baseUrl,
161
+ payload: { sessionId, state, exchangeCode },
162
+ });
163
+ respondJson(res, 200, { ok: true });
164
+ exchangeResolve?.(authPayload);
165
+ }
166
+ catch (error) {
167
+ const message = axios_1.default.isAxiosError(error)
168
+ ? error.response?.data?.error || error.message
169
+ : error.message;
170
+ respondJson(res, 400, { error: message });
171
+ exchangeReject?.(new Error(message));
172
+ }
173
+ finally {
174
+ exchangeInFlight = false;
175
+ }
176
+ });
177
+ server.on('error', reject);
178
+ server.on('connection', socket => {
179
+ sockets.add(socket);
180
+ socket.on('close', () => {
181
+ sockets.delete(socket);
182
+ });
183
+ });
184
+ server.keepAliveTimeout = 1;
185
+ server.listen(0, '127.0.0.1', () => {
186
+ const address = server.address();
187
+ if (!address) {
188
+ reject(new Error('Unable to start the local CLI callback server'));
189
+ return;
190
+ }
191
+ settled = true;
192
+ const callbackUrl = `http://127.0.0.1:${address.port}/callback`;
193
+ resolve({
194
+ callbackUrl,
195
+ waitForExchange: () => exchangePromise,
196
+ close: () => new Promise((innerResolve, innerReject) => {
197
+ server.close(error => {
198
+ if (error) {
199
+ innerReject(error);
200
+ return;
201
+ }
202
+ innerResolve();
203
+ });
204
+ sockets.forEach(socket => {
205
+ socket.destroy();
206
+ });
207
+ }),
208
+ });
209
+ });
210
+ const startupTimeout = setTimeout(() => {
211
+ if (!settled) {
212
+ reject(new Error('Timed out while starting the local CLI callback server'));
213
+ }
214
+ }, 5000);
215
+ startupTimeout.unref();
216
+ });
217
+ const login = async () => {
218
+ const { shouldOpenBrowser } = await (0, prompts_1.default)({
219
+ type: 'confirm',
220
+ name: 'shouldOpenBrowser',
221
+ message: 'Open the browser to sign in?',
222
+ initial: true,
223
+ });
224
+ if (shouldOpenBrowser === false) {
225
+ console.log(chalk_1.default.gray('A sign-in URL will be printed. Open it manually in your browser.'));
226
+ }
227
+ const baseUrl = getBaseUrl();
228
+ const clientName = getClientName();
229
+ let serverHandle;
28
230
  try {
29
- const baseUrl = process.env.BUNDLE_DROP_SERVER_URL
30
- ? process.env.BUNDLE_DROP_SERVER_URL.replace(/\/$/, '')
31
- : 'https://api.bundledrop.app';
32
- const loginUrl = `${baseUrl}/auth/login`;
33
- const res = await axios_1.default.post(loginUrl, {
34
- email,
35
- password,
231
+ serverHandle = await startCallbackServer({ baseUrl });
232
+ const session = await createLoginSession({
233
+ baseUrl,
234
+ clientName,
235
+ callbackUrl: serverHandle.callbackUrl,
36
236
  });
37
- const { token, email: userEmail, firstName, lastName, projects = [], organizations = [], memberships = [], } = res.data;
38
- const downloadApiKey = res.data?.downloadApiKey;
39
- const tokenPath = path_1.default.join(os_1.default.homedir(), '.bundle-drop', 'auth.json');
40
- await fs_extra_1.default.ensureDir(path_1.default.dirname(tokenPath));
41
- await fs_extra_1.default.writeJson(tokenPath, {
42
- token,
43
- user: { email: userEmail, firstName, lastName },
44
- projects,
45
- organizations,
46
- memberships,
47
- downloadApiKey,
237
+ console.log(chalk_1.default.cyan(`Signing in for ${clientName}`));
238
+ console.log(chalk_1.default.gray(`If the browser does not open, use this URL:\n${session.authorizeUrl}`));
239
+ if (shouldOpenBrowser !== false) {
240
+ try {
241
+ await openBrowser(session.authorizeUrl);
242
+ }
243
+ catch (error) {
244
+ console.log(chalk_1.default.yellow(`Could not open the browser automatically. Open this URL manually:\n${session.authorizeUrl}`));
245
+ }
246
+ }
247
+ const exchangePromise = serverHandle.waitForExchange();
248
+ const authPayload = await waitForExchangeWithTimeout(exchangePromise);
249
+ const authFile = await writeAuthFile({
250
+ payload: authPayload,
48
251
  serverUrl: baseUrl,
49
252
  });
50
- console.log(chalk_1.default.green('✅ Logged in successfully as:'), chalk_1.default.cyan(`${firstName} ${lastName}`));
51
- // Attempt to scaffold bundle.drop.config.js if missing
52
- const serverUrl = new URL(loginUrl).origin;
53
- await (0, init_config_1.initConfig)({ serverUrl, projects, organizations, downloadApiKey, authToken: token });
253
+ console.log(chalk_1.default.green('✅ Logged in successfully as:'), chalk_1.default.cyan(`${authFile.user.firstName} ${authFile.user.lastName}`));
254
+ if ((0, init_config_1.hasExistingBundleDropConfig)()) {
255
+ console.log(chalk_1.default.gray(`ℹ️ Found existing bundle.drop.config.js at ${(0, init_config_1.getBundleDropConfigPath)()}. Skipping setup prompts.`));
256
+ return;
257
+ }
258
+ await (0, init_config_1.initConfig)({
259
+ serverUrl: baseUrl,
260
+ projects: authFile.projects,
261
+ organizations: authFile.organizations,
262
+ downloadApiKey: authFile.downloadApiKey,
263
+ authToken: authFile.token,
264
+ });
54
265
  await (0, post_init_1.runPostInitPrompts)();
55
266
  }
56
- catch (err) {
57
- console.error(chalk_1.default.red('❌ Login failed:'), err.response?.data?.error || err.message);
267
+ catch (error) {
268
+ const message = axios_1.default.isAxiosError(error)
269
+ ? error.response?.data?.error || error.message
270
+ : error.message;
271
+ console.error(chalk_1.default.red('❌ Login failed:'), message);
272
+ }
273
+ finally {
274
+ if (serverHandle) {
275
+ await serverHandle.close().catch(() => undefined);
276
+ }
58
277
  }
59
278
  };
60
279
  exports.default = login;
package/lib/index.d.ts CHANGED
@@ -2,7 +2,7 @@ import './bootstrap';
2
2
  export { getAvailableChannels, checkForUpdate, getInstalledBundleInfo } from './manager/updateCheck';
3
3
  export { downloadUpdate } from './manager/downloadAndInstall';
4
4
  export { getUpdateState, applyUpdate } from './manager/updateState';
5
- export { initUpdateManager } from './manager/initUpdateManager';
5
+ export { initUpdateManager, isUpdateFlowActive } from './manager/initUpdateManager';
6
6
  export { BundleDropError, isBundleDropError } from './errors';
7
7
  export { getCurrentUserProperties, getUserProperties, setUserProperty, setUserPropery, removeUserProperty, resetUserProperties, } from './fs/userProperties';
8
8
  export type { BundleInfo } from './bundleInfo';
package/lib/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.useBundleDrop = exports.resetUserProperties = exports.removeUserProperty = exports.setUserPropery = exports.setUserProperty = exports.getUserProperties = exports.getCurrentUserProperties = exports.isBundleDropError = exports.BundleDropError = exports.initUpdateManager = exports.applyUpdate = exports.getUpdateState = exports.downloadUpdate = exports.getInstalledBundleInfo = exports.checkForUpdate = exports.getAvailableChannels = void 0;
3
+ exports.useBundleDrop = exports.resetUserProperties = exports.removeUserProperty = exports.setUserPropery = exports.setUserProperty = exports.getUserProperties = exports.getCurrentUserProperties = exports.isBundleDropError = exports.BundleDropError = exports.isUpdateFlowActive = exports.initUpdateManager = exports.applyUpdate = exports.getUpdateState = exports.downloadUpdate = exports.getInstalledBundleInfo = exports.checkForUpdate = exports.getAvailableChannels = void 0;
4
4
  require("./bootstrap");
5
5
  var updateCheck_1 = require("./manager/updateCheck");
6
6
  Object.defineProperty(exports, "getAvailableChannels", { enumerable: true, get: function () { return updateCheck_1.getAvailableChannels; } });
@@ -13,6 +13,7 @@ Object.defineProperty(exports, "getUpdateState", { enumerable: true, get: functi
13
13
  Object.defineProperty(exports, "applyUpdate", { enumerable: true, get: function () { return updateState_1.applyUpdate; } });
14
14
  var initUpdateManager_1 = require("./manager/initUpdateManager");
15
15
  Object.defineProperty(exports, "initUpdateManager", { enumerable: true, get: function () { return initUpdateManager_1.initUpdateManager; } });
16
+ Object.defineProperty(exports, "isUpdateFlowActive", { enumerable: true, get: function () { return initUpdateManager_1.isUpdateFlowActive; } });
16
17
  var errors_1 = require("./errors");
17
18
  Object.defineProperty(exports, "BundleDropError", { enumerable: true, get: function () { return errors_1.BundleDropError; } });
18
19
  Object.defineProperty(exports, "isBundleDropError", { enumerable: true, get: function () { return errors_1.isBundleDropError; } });
@@ -1,4 +1,7 @@
1
1
  import { UpdatePolicy } from '../types';
2
+ export declare function isUpdateFlowActive(): boolean;
3
+ export declare function acquireUpdateLock(): boolean;
4
+ export declare function releaseUpdateLock(): void;
2
5
  export declare function initUpdateManager(opts?: {
3
6
  channelName?: string;
4
7
  policy?: UpdatePolicy;
@@ -1,5 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isUpdateFlowActive = isUpdateFlowActive;
4
+ exports.acquireUpdateLock = acquireUpdateLock;
5
+ exports.releaseUpdateLock = releaseUpdateLock;
3
6
  exports.initUpdateManager = initUpdateManager;
4
7
  const downloadAndInstall_1 = require("./downloadAndInstall");
5
8
  const updateCheck_1 = require("./updateCheck");
@@ -9,7 +12,30 @@ const bundleInfo_1 = require("../bundleInfo");
9
12
  const context_1 = require("../context");
10
13
  const bundlePointer_1 = require("../fs/bundlePointer");
11
14
  const bundleDropNative_1 = require("../native/bundleDropNative");
15
+ let _updateFlowActive = false;
16
+ function isUpdateFlowActive() {
17
+ return _updateFlowActive;
18
+ }
19
+ function acquireUpdateLock() {
20
+ if (_updateFlowActive)
21
+ return false;
22
+ _updateFlowActive = true;
23
+ return true;
24
+ }
25
+ function releaseUpdateLock() {
26
+ _updateFlowActive = false;
27
+ }
12
28
  async function initUpdateManager(opts) {
29
+ if (!acquireUpdateLock())
30
+ return;
31
+ try {
32
+ await _initUpdateManagerInner(opts);
33
+ }
34
+ finally {
35
+ releaseUpdateLock();
36
+ }
37
+ }
38
+ async function _initUpdateManagerInner(opts) {
13
39
  const policy = opts?.policy || 'manual';
14
40
  const channelName = opts?.channelName || context_1.defaultChannel;
15
41
  const statusCb = opts?.onStatusUpdate;
@@ -7,6 +7,7 @@ const updateCheck_1 = require("./manager/updateCheck");
7
7
  const downloadAndInstall_1 = require("./manager/downloadAndInstall");
8
8
  const updateState_1 = require("./manager/updateState");
9
9
  const rollbackState_1 = require("./manager/rollbackState");
10
+ const initUpdateManager_1 = require("./manager/initUpdateManager");
10
11
  function useBundleDrop(options) {
11
12
  const channelName = options?.channelName || context_1.defaultChannel;
12
13
  const [status, setStatus] = (0, react_1.useState)('Click the button to check for updates');
@@ -22,6 +23,9 @@ function useBundleDrop(options) {
22
23
  setHasBundle(state.hasBundle);
23
24
  }, []);
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
+ }
25
29
  setIsBusy(true);
26
30
  try {
27
31
  const result = await fn();
@@ -30,6 +34,7 @@ function useBundleDrop(options) {
30
34
  }
31
35
  finally {
32
36
  setIsBusy(false);
37
+ (0, initUpdateManager_1.releaseUpdateLock)();
33
38
  }
34
39
  }, [refresh]);
35
40
  const checkLatest = (0, react_1.useCallback)(async () => {
@@ -121,7 +126,9 @@ function useBundleDrop(options) {
121
126
  }, [setAvailableChannels, setStatus]);
122
127
  (0, react_1.useEffect)(() => {
123
128
  refresh();
124
- (0, rollbackState_1.commitActiveBundle)();
129
+ if (!(0, initUpdateManager_1.isUpdateFlowActive)()) {
130
+ (0, rollbackState_1.commitActiveBundle)();
131
+ }
125
132
  }, [refresh]);
126
133
  return {
127
134
  status,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gfean/react-native-bundle-drop",
3
- "version": "0.1.95",
3
+ "version": "0.2.0",
4
4
  "description": "react native ota by gFean",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",