@gfean/react-native-bundle-drop 0.1.97 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gfean/react-native-bundle-drop",
3
- "version": "0.1.97",
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",