@proxylayer/cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,640 @@
1
+ #!/usr/bin/env node
2
+ import { realpathSync } from "node:fs";
3
+ import readline from "node:readline";
4
+ import { fileURLToPath } from "node:url";
5
+ import { ProxyLayer, ProxyLayerError, } from "./client.js";
6
+ import { clearConfig } from "./config.js";
7
+ import { runStdioMcpServer } from "./mcp.js";
8
+ const CLI_VERSION = "0.1.1";
9
+ const HELP_TEXT = `ProxyLayer CLI (${CLI_VERSION})
10
+
11
+ Usage:
12
+ proxylayer <command> [options] (or \`pl\` when installed globally)
13
+
14
+ Commands:
15
+ mcp Start local stdio MCP server (auto-saves API key on OTP verify)
16
+ login [email] Sign in or register via Email OTP and save API key locally
17
+ [--code <6-digits>] [--key-name <name>] [--access full|read]
18
+ whoami Show stored config path, email, baseUrl, and masked API key
19
+ logout Remove saved local credentials
20
+ catalog [product] List products, durations, countries, and USD prices
21
+ quote <product> ... Calculate USD price (e.g. quote residential 10gb | quote isp US 2 30d)
22
+ balance Show prepaid USD wallet balance
23
+ buy <product> ... Create checkout (e.g. buy residential 10gb [--method stripe|crypto|balance])
24
+ checkout <session-id> Poll checkout payment and provisioning status
25
+ orders [--limit 20] List order and top-up history
26
+ proxies [product] List static proxies (isp|datacenter|mobile, --raw prints host:port:user:pass)
27
+ residential [options] Generate residential proxy strings (--country us --qty 1 --raw)
28
+
29
+ Global options:
30
+ --json Print raw JSON response
31
+ --raw Print one proxy string per line (proxies, residential)
32
+ --api-key <pl_live_...> Override API key for this command
33
+ --base-url <url> Override API base URL (default: https://app.proxy-layer.com)
34
+ --config <path> Override config file path
35
+ -h, --help Show help
36
+ -v, --version Show CLI version
37
+ `;
38
+ function parseArgs(argv) {
39
+ const positionals = [];
40
+ const flags = new Map();
41
+ for (let i = 0; i < argv.length; i++) {
42
+ const token = argv[i];
43
+ if (token === "--") {
44
+ positionals.push(...argv.slice(i + 1));
45
+ break;
46
+ }
47
+ if (token === "-h" || token === "--help") {
48
+ flags.set("help", true);
49
+ continue;
50
+ }
51
+ if (token === "-v" || token === "--version") {
52
+ flags.set("version", true);
53
+ continue;
54
+ }
55
+ if (token.startsWith("--")) {
56
+ const eq = token.indexOf("=");
57
+ if (eq !== -1) {
58
+ flags.set(token.slice(2, eq), token.slice(eq + 1));
59
+ continue;
60
+ }
61
+ const key = token.slice(2);
62
+ if (key === "json" || key === "raw") {
63
+ flags.set(key, true);
64
+ continue;
65
+ }
66
+ const next = argv[i + 1];
67
+ if (next !== undefined && !next.startsWith("-")) {
68
+ flags.set(key, next);
69
+ i++;
70
+ }
71
+ else {
72
+ flags.set(key, true);
73
+ }
74
+ continue;
75
+ }
76
+ positionals.push(token);
77
+ }
78
+ return { positionals, flags };
79
+ }
80
+ function strFlag(flags, name) {
81
+ const value = flags.get(name);
82
+ return typeof value === "string" ? value.trim() : undefined;
83
+ }
84
+ function intFlag(flags, name, fallback) {
85
+ const raw = strFlag(flags, name);
86
+ if (raw === undefined)
87
+ return fallback;
88
+ const parsed = Number(raw);
89
+ if (!Number.isInteger(parsed))
90
+ throw new Error(`--${name} must be an integer (got "${raw}")`);
91
+ return parsed;
92
+ }
93
+ function boolFlag(flags, name) {
94
+ return flags.get(name) === true;
95
+ }
96
+ function maskKey(key) {
97
+ if (!key)
98
+ return null;
99
+ if (key.length <= 16)
100
+ return `${key.slice(0, 8)}...`;
101
+ return `${key.slice(0, 12)}...${key.slice(-4)}`;
102
+ }
103
+ function formatUsd(cents) {
104
+ return `$${(cents / 100).toFixed(2)}`;
105
+ }
106
+ function validateEmailInput(value) {
107
+ const email = (value ?? "").trim().toLowerCase();
108
+ if (!email)
109
+ return { email, error: "Enter your email address." };
110
+ if (email.length > 320 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
111
+ return { email, error: "Enter a valid email address." };
112
+ }
113
+ return { email };
114
+ }
115
+ function normalizeOtpCode(raw) {
116
+ const normalized = raw.replace(/[\s-]+/g, "");
117
+ return /^\d{6}$/.test(normalized) ? normalized : null;
118
+ }
119
+ function isCancelCommand(raw) {
120
+ const lower = raw.trim().toLowerCase();
121
+ return lower === "q" || lower === "quit" || lower === "exit";
122
+ }
123
+ async function runInteractiveLogin(options) {
124
+ const { client, keyName, access, stdin, stdout, errOut } = options;
125
+ const terminal = Boolean(stdin.isTTY);
126
+ const rl = readline.createInterface({ input: stdin, output: stdout, terminal });
127
+ const bufferedLines = [];
128
+ let waitingResolver = null;
129
+ let cancelled = false;
130
+ let closed = false;
131
+ const closePrompt = () => {
132
+ closed = true;
133
+ if (waitingResolver) {
134
+ const resolve = waitingResolver;
135
+ waitingResolver = null;
136
+ resolve(null);
137
+ }
138
+ };
139
+ rl.on("line", (line) => {
140
+ if (waitingResolver) {
141
+ const resolve = waitingResolver;
142
+ waitingResolver = null;
143
+ resolve(line);
144
+ }
145
+ else {
146
+ bufferedLines.push(line);
147
+ }
148
+ });
149
+ rl.on("SIGINT", () => {
150
+ cancelled = true;
151
+ rl.close();
152
+ });
153
+ rl.on("close", closePrompt);
154
+ const ask = (prompt) => {
155
+ if (bufferedLines.length > 0) {
156
+ stdout.write(prompt);
157
+ return Promise.resolve(bufferedLines.shift());
158
+ }
159
+ if (cancelled || closed)
160
+ return Promise.resolve(null);
161
+ if (terminal) {
162
+ rl.setPrompt(prompt);
163
+ rl.prompt();
164
+ }
165
+ else {
166
+ stdout.write(prompt);
167
+ }
168
+ return new Promise((resolve) => {
169
+ waitingResolver = resolve;
170
+ });
171
+ };
172
+ const promptForEmail = async (seed) => {
173
+ if (seed !== undefined) {
174
+ const checked = validateEmailInput(seed);
175
+ if (!checked.error)
176
+ return checked.email;
177
+ errOut(checked.error);
178
+ }
179
+ while (true) {
180
+ const answer = await ask('Email (or "q" to cancel): ');
181
+ if (answer === null || isCancelCommand(answer))
182
+ return null;
183
+ const checked = validateEmailInput(answer);
184
+ if (!checked.error)
185
+ return checked.email;
186
+ errOut(checked.error);
187
+ }
188
+ };
189
+ try {
190
+ let email = await promptForEmail(options.initialEmail);
191
+ if (!email)
192
+ return null;
193
+ const requested = await client.requestOtp(email);
194
+ email = requested.email;
195
+ errOut(`Sent a 6-digit verification code to ${email}.`);
196
+ errOut('Type "r" to resend, "e" to change email, or press Ctrl+C to cancel.');
197
+ while (true) {
198
+ const rawAnswer = await ask("6-digit code: ");
199
+ if (rawAnswer === null || isCancelCommand(rawAnswer))
200
+ return null;
201
+ const trimmed = rawAnswer.trim();
202
+ const lower = trimmed.toLowerCase();
203
+ if (lower === "r" || lower === "resend") {
204
+ try {
205
+ await client.requestOtp(email);
206
+ errOut(`Sent a new 6-digit code to ${email}.`);
207
+ }
208
+ catch (err) {
209
+ if (err instanceof ProxyLayerError) {
210
+ errOut(err.message);
211
+ }
212
+ else {
213
+ throw err;
214
+ }
215
+ }
216
+ continue;
217
+ }
218
+ if (lower === "e" || lower === "email") {
219
+ const nextEmail = await promptForEmail();
220
+ if (!nextEmail)
221
+ return null;
222
+ try {
223
+ const nextReq = await client.requestOtp(nextEmail);
224
+ email = nextReq.email;
225
+ errOut(`Sent a 6-digit verification code to ${email}.`);
226
+ }
227
+ catch (err) {
228
+ if (err instanceof ProxyLayerError) {
229
+ errOut(err.message);
230
+ }
231
+ else {
232
+ throw err;
233
+ }
234
+ }
235
+ continue;
236
+ }
237
+ if (!trimmed) {
238
+ errOut("Enter the 6-digit code from your email.");
239
+ continue;
240
+ }
241
+ const normalized = normalizeOtpCode(trimmed);
242
+ if (!normalized) {
243
+ errOut("Enter a 6-digit numeric code (for example: 123456).");
244
+ continue;
245
+ }
246
+ try {
247
+ return await client.verifyOtp({ email, code: normalized, keyName, access, save: true });
248
+ }
249
+ catch (err) {
250
+ if (err instanceof ProxyLayerError && err.code === "INVALID_OTP") {
251
+ errOut('Incorrect code. Try again, or type "r" to resend a new code.');
252
+ continue;
253
+ }
254
+ if (err instanceof ProxyLayerError && err.code === "OTP_EXPIRED") {
255
+ errOut('That code has expired. Type "r" to send a new code.');
256
+ continue;
257
+ }
258
+ throw err;
259
+ }
260
+ }
261
+ }
262
+ finally {
263
+ rl.close();
264
+ }
265
+ }
266
+ function parseSuffixedInt(raw, unitRegex, label) {
267
+ const cleaned = raw.trim().replace(unitRegex, "");
268
+ const parsed = Number(cleaned);
269
+ if (!Number.isInteger(parsed) || parsed <= 0) {
270
+ throw new Error(`${label} must be a positive integer (got "${raw}")`);
271
+ }
272
+ return parsed;
273
+ }
274
+ function buildPurchase(flags, positionals, allowTopUp) {
275
+ const supported = allowTopUp ? "isp | datacenter | mobile | residential | balance-topup" : "isp | datacenter | mobile | residential";
276
+ const product = strFlag(flags, "product") ?? positionals[1];
277
+ if (!product) {
278
+ throw new Error(`Specify a product (${supported}), for example: residential 10gb`);
279
+ }
280
+ if (product === "residential") {
281
+ const trafficGb = intFlag(flags, "gb") ?? (positionals[2] ? parseSuffixedInt(positionals[2], /gb$/i, "Traffic GB") : undefined);
282
+ if (!trafficGb || trafficGb <= 0) {
283
+ throw new Error("Traffic in GB is required (for example: residential 10gb or --gb 10)");
284
+ }
285
+ return { productSlug: "residential", trafficGb };
286
+ }
287
+ if (product === "balance-topup") {
288
+ if (!allowTopUp)
289
+ throw new Error("balance-topup cannot be quoted with quote; pass amount to buy");
290
+ const amountCents = intFlag(flags, "amount-cents") ?? (positionals[2] ? parseSuffixedInt(positionals[2], /^$/, "Amount cents") : undefined);
291
+ if (!amountCents || amountCents <= 0) {
292
+ throw new Error("Amount in USD cents is required for balance-topup (for example: balance-topup 2500)");
293
+ }
294
+ return { productSlug: "balance-topup", amountCents };
295
+ }
296
+ if (product === "isp" || product === "datacenter" || product === "mobile") {
297
+ const countryCode = (strFlag(flags, "country") ?? positionals[2] ?? "US").toUpperCase();
298
+ const quantity = intFlag(flags, "qty") ?? (positionals[3] ? parseSuffixedInt(positionals[3], /^$/, "Quantity") : 1);
299
+ const durationDays = intFlag(flags, "days") ?? (positionals[4] ? parseSuffixedInt(positionals[4], /d$/i, "Duration days") : 30);
300
+ const targetIdsRaw = strFlag(flags, "target-proxy-ids");
301
+ const targetProxyIds = targetIdsRaw
302
+ ? targetIdsRaw.split(",").map((id) => id.trim()).filter(Boolean)
303
+ : undefined;
304
+ return {
305
+ productSlug: product,
306
+ durationDays,
307
+ items: [{ countryCode, quantity, ...(targetProxyIds?.length ? { targetProxyIds } : {}) }],
308
+ };
309
+ }
310
+ throw new Error(`Unsupported product "${product}". Choose: ${supported} (for example: residential 10gb)`);
311
+ }
312
+ export async function runCli(argv, deps) {
313
+ const stdout = deps?.stdout ?? process.stdout;
314
+ const stderr = deps?.stderr ?? process.stderr;
315
+ const stdin = deps?.stdin ?? process.stdin;
316
+ const out = (line) => stdout.write(`${line}\n`);
317
+ const errOut = (line) => stderr.write(`${line}\n`);
318
+ try {
319
+ const { positionals, flags } = parseArgs(argv);
320
+ if (boolFlag(flags, "version")) {
321
+ out(CLI_VERSION);
322
+ return 0;
323
+ }
324
+ const command = positionals[0];
325
+ if (!command || boolFlag(flags, "help") || command === "help") {
326
+ out(HELP_TEXT.trimEnd());
327
+ return 0;
328
+ }
329
+ const asJson = boolFlag(flags, "json");
330
+ const asRaw = boolFlag(flags, "raw");
331
+ const configPath = strFlag(flags, "config") ?? deps?.configPath;
332
+ const apiKey = strFlag(flags, "api-key");
333
+ const baseUrl = strFlag(flags, "base-url");
334
+ if (command === "mcp") {
335
+ await runStdioMcpServer({ apiKey, baseUrl, configPath, input: stdin, output: stdout, fetch: deps?.fetch });
336
+ return 0;
337
+ }
338
+ const client = new ProxyLayer({ apiKey, baseUrl, configPath, fetch: deps?.fetch });
339
+ const isTty = deps?.isTTY ?? Boolean(stdin.isTTY);
340
+ const ensureInteractiveAuth = async () => {
341
+ if (client.getResolvedConfig().apiKey || !isTty || asJson || asRaw)
342
+ return true;
343
+ errOut("Sign in to ProxyLayer to continue:");
344
+ const interactive = await runInteractiveLogin({ client, stdin, stdout, errOut });
345
+ if (!interactive) {
346
+ errOut("Login cancelled.");
347
+ return false;
348
+ }
349
+ errOut(`Signed in as ${interactive.user.email} (${interactive.keyPrefix}...)`);
350
+ return true;
351
+ };
352
+ if (command === "whoami") {
353
+ const resolved = client.getResolvedConfig();
354
+ const payload = {
355
+ authenticated: Boolean(resolved.apiKey),
356
+ email: resolved.email ?? null,
357
+ apiKeyMasked: maskKey(resolved.apiKey),
358
+ baseUrl: resolved.baseUrl,
359
+ configPath: resolved.configPath,
360
+ };
361
+ if (asJson) {
362
+ out(JSON.stringify(payload, null, 2));
363
+ }
364
+ else {
365
+ out(`Base URL: ${payload.baseUrl}`);
366
+ out(`Config: ${payload.configPath}`);
367
+ out(`Email: ${payload.email ?? "(none)"}`);
368
+ out(`API key: ${payload.apiKeyMasked ?? "(not signed in)"}`);
369
+ }
370
+ return resolved.apiKey ? 0 : 1;
371
+ }
372
+ if (command === "logout") {
373
+ const removed = clearConfig(configPath);
374
+ if (asJson)
375
+ out(JSON.stringify({ cleared: removed }, null, 2));
376
+ else
377
+ out(removed ? "Removed saved ProxyLayer credentials." : "No saved credentials found.");
378
+ return 0;
379
+ }
380
+ if (command === "login") {
381
+ const rawEmail = strFlag(flags, "email") ?? positionals[1] ?? (flags.has("email") ? "" : undefined);
382
+ const rawCode = strFlag(flags, "code");
383
+ const keyName = strFlag(flags, "key-name");
384
+ const access = strFlag(flags, "access");
385
+ if (access && access !== "read" && access !== "full") {
386
+ throw new Error("--access must be 'read' or 'full'");
387
+ }
388
+ let verified;
389
+ if (!rawCode && isTty && !asJson) {
390
+ const interactive = await runInteractiveLogin({
391
+ client,
392
+ initialEmail: rawEmail,
393
+ keyName,
394
+ access,
395
+ stdin,
396
+ stdout,
397
+ errOut,
398
+ });
399
+ if (!interactive) {
400
+ errOut("Login cancelled.");
401
+ return 130;
402
+ }
403
+ verified = interactive;
404
+ }
405
+ else {
406
+ const checkedEmail = validateEmailInput(rawEmail);
407
+ if (checkedEmail.error)
408
+ throw new Error(checkedEmail.error);
409
+ const email = checkedEmail.email;
410
+ if (!rawCode) {
411
+ const requested = await client.requestOtp(email);
412
+ if (asJson) {
413
+ out(JSON.stringify(requested, null, 2));
414
+ }
415
+ else {
416
+ out(`Sent 6-digit verification code to ${requested.email} (valid ${requested.expiresInSeconds}s).`);
417
+ out(`Complete login with:\n npx @proxylayer/cli login --email ${requested.email} --code <6-digits>`);
418
+ }
419
+ return 0;
420
+ }
421
+ const code = normalizeOtpCode(rawCode);
422
+ if (!code)
423
+ throw new Error("Enter a 6-digit numeric code.");
424
+ verified = await client.verifyOtp({ email, code, keyName, access, save: true });
425
+ }
426
+ const resolved = client.getResolvedConfig();
427
+ if (asJson) {
428
+ out(JSON.stringify({
429
+ saved: true,
430
+ configPath: resolved.configPath,
431
+ keyId: verified.keyId,
432
+ keyPrefix: verified.keyPrefix,
433
+ scopes: verified.scopes,
434
+ user: verified.user,
435
+ }, null, 2));
436
+ }
437
+ else {
438
+ out(`Signed in as ${verified.user.email} (${verified.keyPrefix}...)`);
439
+ out(`Saved API key to ${resolved.configPath}`);
440
+ }
441
+ return 0;
442
+ }
443
+ if (command === "catalog") {
444
+ const productFilter = strFlag(flags, "product") ?? positionals[1];
445
+ if (productFilter && productFilter !== "isp" && productFilter !== "datacenter" && productFilter !== "mobile" && productFilter !== "residential") {
446
+ throw new Error("--product must be 'isp', 'datacenter', 'mobile', or 'residential'");
447
+ }
448
+ const catalog = await client.getCatalog(productFilter ? { product: productFilter } : undefined);
449
+ if (asJson) {
450
+ out(JSON.stringify(catalog, null, 2));
451
+ }
452
+ else {
453
+ for (const product of catalog.products) {
454
+ const durations = product.durationsDays.length ? `${product.durationsDays.join("/")}d` : "traffic";
455
+ out(`${product.slug.padEnd(12)} ${product.name} (${durations}, ${product.countries.length} countries)`);
456
+ }
457
+ }
458
+ return 0;
459
+ }
460
+ if (command === "quote") {
461
+ const quote = await client.quote(buildPurchase(flags, positionals, false));
462
+ if (asJson) {
463
+ out(JSON.stringify(quote, null, 2));
464
+ }
465
+ else {
466
+ out(`${quote.productName}: ${formatUsd(quote.amountCents)} (${quote.amountCents} cents USD)`);
467
+ }
468
+ return 0;
469
+ }
470
+ if (command === "balance") {
471
+ if (!(await ensureInteractiveAuth()))
472
+ return 130;
473
+ const summary = await client.getBalance();
474
+ if (asJson) {
475
+ out(JSON.stringify(summary, null, 2));
476
+ }
477
+ else {
478
+ out(`Balance: ${formatUsd(summary.balanceCents)} (${summary.balanceCents} cents USD)`);
479
+ }
480
+ return 0;
481
+ }
482
+ if (command === "buy") {
483
+ const paymentMethod = (strFlag(flags, "method") || "stripe");
484
+ if (paymentMethod !== "stripe" && paymentMethod !== "crypto" && paymentMethod !== "balance") {
485
+ throw new Error("--method must be 'stripe', 'crypto', or 'balance'");
486
+ }
487
+ const purchase = buildPurchase(flags, positionals, true);
488
+ if (!(await ensureInteractiveAuth()))
489
+ return 130;
490
+ const checkout = await client.createCheckout({
491
+ purchase,
492
+ paymentMethod,
493
+ cryptoCurrency: strFlag(flags, "crypto-currency"),
494
+ cryptoNetwork: strFlag(flags, "crypto-network"),
495
+ clientOperationId: strFlag(flags, "idempotency-key"),
496
+ });
497
+ if (asJson) {
498
+ out(JSON.stringify(checkout, null, 2));
499
+ }
500
+ else {
501
+ out(`Checkout ${checkout.checkoutSessionId} [${checkout.paymentMethod}] — ${checkout.status} (${formatUsd(checkout.amountCents)})`);
502
+ if (checkout.paymentUrl)
503
+ out(`Payment URL: ${checkout.paymentUrl}`);
504
+ if (checkout.crypto) {
505
+ out(`Pay ${checkout.crypto.payerAmount} ${checkout.crypto.payerCurrency} (${checkout.crypto.network}) -> ${checkout.crypto.address}`);
506
+ }
507
+ if (checkout.orderId)
508
+ out(`Order ID: ${checkout.orderId}`);
509
+ }
510
+ return 0;
511
+ }
512
+ if (command === "checkout") {
513
+ const sessionId = positionals[1] ?? strFlag(flags, "id");
514
+ if (!sessionId)
515
+ throw new Error("checkout <checkoutSessionId> is required");
516
+ if (!(await ensureInteractiveAuth()))
517
+ return 130;
518
+ const status = await client.getCheckoutStatus(sessionId);
519
+ if (asJson) {
520
+ out(JSON.stringify(status, null, 2));
521
+ }
522
+ else {
523
+ out(`Checkout ${status.checkoutSessionId}: status=${status.status}, provisioningPending=${status.provisioningPending}${status.orderId ? `, orderId=${status.orderId}` : ""}${status.fulfillmentStatus ? ` (${status.fulfillmentStatus})` : ""}`);
524
+ if (status.failureMessage)
525
+ out(`Message: ${status.failureMessage}`);
526
+ }
527
+ return 0;
528
+ }
529
+ if (command === "orders") {
530
+ if (!(await ensureInteractiveAuth()))
531
+ return 130;
532
+ const orders = await client.listOrders({
533
+ limit: intFlag(flags, "limit"),
534
+ cursor: strFlag(flags, "cursor"),
535
+ });
536
+ if (asJson) {
537
+ out(JSON.stringify(orders, null, 2));
538
+ }
539
+ else {
540
+ for (const order of orders.items) {
541
+ out(`${order.id} ${order.occurredAt} ${order.paymentStatus}/${order.fulfillmentStatus} ${formatUsd(order.totalAmount)}`);
542
+ }
543
+ }
544
+ return 0;
545
+ }
546
+ if (command === "proxies") {
547
+ const product = (strFlag(flags, "product") ?? positionals[1] ?? "isp");
548
+ if (product !== "isp" && product !== "datacenter" && product !== "mobile") {
549
+ throw new Error("--product must be 'isp', 'datacenter', or 'mobile'");
550
+ }
551
+ if (!(await ensureInteractiveAuth()))
552
+ return 130;
553
+ const res = await client.listStaticProxies({
554
+ product,
555
+ checkoutSessionId: strFlag(flags, "checkout-session-id"),
556
+ limit: intFlag(flags, "limit"),
557
+ cursor: strFlag(flags, "cursor"),
558
+ });
559
+ if (asJson) {
560
+ out(JSON.stringify(res, null, 2));
561
+ }
562
+ else if (asRaw) {
563
+ for (const row of res.data)
564
+ out(row.proxy);
565
+ }
566
+ else {
567
+ for (const row of res.data) {
568
+ out(`${row.proxy} [${row.countryCode}, ${row.daysLeft}d left]`);
569
+ }
570
+ if (res.data.length === 0 && res.pendingCheckout) {
571
+ out(`Checkout ${res.pendingCheckout.checkoutSessionId} is awaiting payment/provisioning (${res.pendingCheckout.quantity}).`);
572
+ }
573
+ }
574
+ return 0;
575
+ }
576
+ if (command === "residential") {
577
+ const session = strFlag(flags, "session");
578
+ if (session && session !== "sticky" && session !== "rotating") {
579
+ throw new Error("--session must be 'sticky' or 'rotating'");
580
+ }
581
+ if (!(await ensureInteractiveAuth()))
582
+ return 130;
583
+ const res = await client.getResidentialProxies({
584
+ country: strFlag(flags, "country"),
585
+ city: strFlag(flags, "city"),
586
+ region: strFlag(flags, "region"),
587
+ asn: strFlag(flags, "asn"),
588
+ session,
589
+ ttl: intFlag(flags, "ttl"),
590
+ quantity: intFlag(flags, "qty"),
591
+ format: strFlag(flags, "format"),
592
+ });
593
+ if (asJson) {
594
+ out(JSON.stringify(res, null, 2));
595
+ }
596
+ else if (asRaw) {
597
+ for (const proxy of res.proxies)
598
+ out(proxy);
599
+ }
600
+ else {
601
+ if (res.trafficBalance.balanceFormatted) {
602
+ out(`Traffic remaining: ${res.trafficBalance.balanceFormatted}`);
603
+ }
604
+ for (const proxy of res.proxies)
605
+ out(proxy);
606
+ }
607
+ return 0;
608
+ }
609
+ throw new Error(`Unknown command "${command}". Run with --help to see usage.`);
610
+ }
611
+ catch (error) {
612
+ if (error instanceof ProxyLayerError) {
613
+ const firstIssue = error.issues?.[0];
614
+ const detail = error.message === "Invalid request payload" && typeof firstIssue?.message === "string"
615
+ ? firstIssue.message
616
+ : error.message;
617
+ errOut(error.code === "VALIDATION_ERROR"
618
+ ? `Error: ${detail}`
619
+ : `Error: ${detail} (${error.code}, HTTP ${error.status})`);
620
+ }
621
+ else {
622
+ errOut(`Error: ${error instanceof Error ? error.message : String(error)}`);
623
+ }
624
+ return 1;
625
+ }
626
+ }
627
+ const isEntrypoint = Boolean(process.argv[1] &&
628
+ (() => {
629
+ try {
630
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
631
+ }
632
+ catch {
633
+ return false;
634
+ }
635
+ })());
636
+ if (isEntrypoint) {
637
+ runCli(process.argv.slice(2)).then((code) => {
638
+ process.exitCode = code;
639
+ });
640
+ }