@zapier/zapier-sdk-cli 0.52.10 → 0.53.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 (71) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +39 -1
  3. package/dist/cli.cjs +972 -473
  4. package/dist/cli.mjs +973 -474
  5. package/dist/experimental.cjs +914 -424
  6. package/dist/experimental.d.mts +1 -1
  7. package/dist/experimental.d.ts +1 -1
  8. package/dist/experimental.mjs +910 -420
  9. package/dist/index.cjs +914 -424
  10. package/dist/index.d.mts +1 -1
  11. package/dist/index.d.ts +1 -1
  12. package/dist/index.mjs +910 -420
  13. package/dist/login.cjs +8 -10
  14. package/dist/login.d.mts +2 -10
  15. package/dist/login.d.ts +2 -10
  16. package/dist/login.mjs +5 -9
  17. package/dist/package.json +1 -1
  18. package/dist/{sdk-B3nKAZdN.d.mts → sdk-SOLizjno.d.mts} +54 -16
  19. package/dist/{sdk-B3nKAZdN.d.ts → sdk-SOLizjno.d.ts} +54 -16
  20. package/dist/src/experimental.js +30 -27
  21. package/dist/src/login/index.d.ts +1 -9
  22. package/dist/src/login/index.js +12 -14
  23. package/dist/src/plugins/add/index.d.ts +15 -15
  24. package/dist/src/plugins/add/index.js +1 -1
  25. package/dist/src/plugins/buildManifest/index.d.ts +2 -2
  26. package/dist/src/plugins/bundleCode/index.d.ts +1 -1
  27. package/dist/src/plugins/bundleCode/index.js +2 -1
  28. package/dist/src/plugins/cliOverrides/index.d.ts +5 -10
  29. package/dist/src/plugins/cliOverrides/index.js +2 -6
  30. package/dist/src/plugins/curl/index.d.ts +2 -2
  31. package/dist/src/plugins/curl/schemas.d.ts +2 -2
  32. package/dist/src/plugins/feedback/index.d.ts +1 -1
  33. package/dist/src/plugins/generateAppTypes/index.d.ts +11 -11
  34. package/dist/src/plugins/getLoginConfigPath/index.d.ts +1 -1
  35. package/dist/src/plugins/index.d.ts +2 -1
  36. package/dist/src/plugins/index.js +2 -1
  37. package/dist/src/plugins/init/index.d.ts +1 -1
  38. package/dist/src/plugins/login/index.d.ts +3 -16
  39. package/dist/src/plugins/login/index.js +3 -191
  40. package/dist/src/plugins/logout/index.d.ts +1 -1
  41. package/dist/src/plugins/mcp/index.d.ts +1 -1
  42. package/dist/src/plugins/signup/index.d.ts +25 -0
  43. package/dist/src/plugins/signup/index.js +12 -0
  44. package/dist/src/plugins/signup/schemas.d.ts +9 -0
  45. package/dist/src/plugins/signup/schemas.js +26 -0
  46. package/dist/src/plugins/signup/test-harness.d.ts +34 -0
  47. package/dist/src/plugins/signup/test-harness.js +74 -0
  48. package/dist/src/sdk.js +32 -20
  49. package/dist/src/types/sdk.d.ts +2 -1
  50. package/dist/src/utils/auth/account-auth.d.ts +32 -0
  51. package/dist/src/utils/auth/account-auth.js +265 -0
  52. package/dist/src/utils/auth/oauth-callback.d.ts +6 -0
  53. package/dist/src/utils/auth/oauth-callback.js +28 -0
  54. package/dist/src/utils/auth/oauth-errors.d.ts +2 -0
  55. package/dist/src/utils/auth/oauth-errors.js +39 -0
  56. package/dist/src/utils/auth/oauth-flow.d.ts +31 -6
  57. package/dist/src/utils/auth/oauth-flow.js +258 -106
  58. package/dist/src/utils/auth/oauth-transaction.d.ts +35 -0
  59. package/dist/src/utils/auth/oauth-transaction.js +69 -0
  60. package/dist/src/utils/cli-generator.js +14 -7
  61. package/dist/src/utils/cli-renderer.d.ts +13 -3
  62. package/dist/src/utils/cli-renderer.js +27 -20
  63. package/dist/src/utils/log.js +9 -4
  64. package/dist/src/utils/non-interactive.d.ts +5 -4
  65. package/dist/src/utils/non-interactive.js +6 -5
  66. package/dist/src/utils/parameter-resolver.js +3 -1
  67. package/dist/src/utils/schema-formatter.d.ts +2 -2
  68. package/dist/src/utils/schema-formatter.js +4 -30
  69. package/dist/src/utils/version-checker.js +8 -3
  70. package/dist/tsconfig.tsbuildinfo +1 -1
  71. package/package.json +3 -3
package/dist/cli.cjs CHANGED
@@ -18,8 +18,9 @@ var crypto = require('crypto');
18
18
  var path = require('path');
19
19
  var lockfile = require('proper-lockfile');
20
20
  var os = require('os');
21
- var open = require('open');
22
21
  var express = require('express');
22
+ var promises$1 = require('readline/promises');
23
+ var open = require('open');
23
24
  var pkceChallenge = require('pkce-challenge');
24
25
  var zapierSdkMcp = require('@zapier/zapier-sdk-mcp');
25
26
  var esbuild = require('esbuild');
@@ -66,8 +67,8 @@ var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
66
67
  var crypto__default = /*#__PURE__*/_interopDefault(crypto);
67
68
  var path__namespace = /*#__PURE__*/_interopNamespace(path);
68
69
  var lockfile__namespace = /*#__PURE__*/_interopNamespace(lockfile);
69
- var open__default = /*#__PURE__*/_interopDefault(open);
70
70
  var express__default = /*#__PURE__*/_interopDefault(express);
71
+ var open__default = /*#__PURE__*/_interopDefault(open);
71
72
  var pkceChallenge__default = /*#__PURE__*/_interopDefault(pkceChallenge);
72
73
  var ts__namespace = /*#__PURE__*/_interopNamespace(ts);
73
74
  var isInstalledGlobally__default = /*#__PURE__*/_interopDefault(isInstalledGlobally);
@@ -200,7 +201,7 @@ var SchemaParameterResolver = class {
200
201
  debugLog(message) {
201
202
  if (this.debug) {
202
203
  this.stopSpinner();
203
- console.log(chalk__default.default.gray(`[Zapier CLI] ${message}`));
204
+ console.error(chalk__default.default.gray(`[Zapier CLI] ${message}`));
204
205
  }
205
206
  }
206
207
  startSpinner() {
@@ -1572,7 +1573,7 @@ var SHARED_COMMAND_CLI_OPTIONS = [
1572
1573
 
1573
1574
  // package.json
1574
1575
  var package_default = {
1575
- version: "0.52.10"};
1576
+ version: "0.53.0"};
1576
1577
 
1577
1578
  // src/telemetry/builders.ts
1578
1579
  function createCliBaseEvent(context = {}) {
@@ -1626,12 +1627,6 @@ function buildCliCommandExecutedEvent({
1626
1627
  subprocess_count: data.subprocess_count ?? null
1627
1628
  };
1628
1629
  }
1629
- function getFormatMetadata(schema) {
1630
- return schema?._zod?.def?.formatMeta;
1631
- }
1632
- function getOutputSchema(schema) {
1633
- return schema?._zod?.def?.outputSchema;
1634
- }
1635
1630
  function formatJsonOutput(data) {
1636
1631
  if (data === void 0) {
1637
1632
  return;
@@ -1640,21 +1635,26 @@ function formatJsonOutput(data) {
1640
1635
  util__default.default.inspect(data, { colors: true, depth: null, breakLength: 80 })
1641
1636
  );
1642
1637
  }
1643
- async function formatItemsFromSchema(functionInfo, items, startingNumber = 0, options) {
1644
- const outputSchema = functionInfo.outputSchema || getOutputSchema(functionInfo.inputSchema);
1645
- if (!outputSchema) {
1646
- formatItemsGeneric(items, startingNumber);
1647
- return;
1648
- }
1649
- const formatMeta = getFormatMetadata(outputSchema);
1650
- if (!formatMeta) {
1651
- formatItemsGeneric(items, startingNumber);
1638
+ async function formatItemsFromSchema(_functionInfo, items, startingNumber = 0, options) {
1639
+ if (options?.formatter) {
1640
+ let context;
1641
+ if (options.formatter.fetch && options.sdk && options.params) {
1642
+ for (const item of items) {
1643
+ context = await options.formatter.fetch(
1644
+ options.sdk,
1645
+ options.params,
1646
+ item,
1647
+ context
1648
+ );
1649
+ }
1650
+ }
1651
+ items.forEach((item, index) => {
1652
+ const formatted = options.formatter.format(item, context);
1653
+ formatSingleItem(formatted, startingNumber + index);
1654
+ });
1652
1655
  return;
1653
1656
  }
1654
- items.forEach((item, index) => {
1655
- const formatted = formatMeta.format(item);
1656
- formatSingleItem(formatted, startingNumber + index);
1657
- });
1657
+ formatItemsGeneric(items, startingNumber);
1658
1658
  }
1659
1659
  function formatSingleItem(formatted, itemNumber) {
1660
1660
  let titleLine = `${chalk__default.default.gray(`${itemNumber + 1}.`)} ${chalk__default.default.cyan(formatted.title)}`;
@@ -1814,7 +1814,7 @@ function createJsonRenderer() {
1814
1814
  errors: []
1815
1815
  });
1816
1816
  },
1817
- renderCollectedList(items, _options) {
1817
+ async renderCollectedList(items, _options) {
1818
1818
  outputJson({ data: items, errors: [] });
1819
1819
  },
1820
1820
  renderItem(value, options) {
@@ -1846,27 +1846,32 @@ function getListTitle(functionInfo) {
1846
1846
  if (functionInfo.itemType) return `Available ${functionInfo.itemType} items`;
1847
1847
  return "items";
1848
1848
  }
1849
- function renderItemsForDisplay(items, functionInfo, startingNumber = 0) {
1850
- if (functionInfo?.inputSchema) {
1851
- formatItemsFromSchema(
1852
- functionInfo,
1853
- items,
1854
- startingNumber
1855
- );
1856
- } else {
1857
- items.forEach((item, index) => {
1858
- const obj = item;
1859
- const name = obj?.name || obj?.key || obj?.id || "Item";
1860
- console.log(
1861
- `${chalk__default.default.gray(`${startingNumber + index + 1}.`)} ${chalk__default.default.cyan(String(name))}`
1849
+ function createInteractiveRenderer(context = {}) {
1850
+ async function renderItemsForDisplay(items, functionInfo, startingNumber = 0) {
1851
+ if (functionInfo?.inputSchema) {
1852
+ await formatItemsFromSchema(
1853
+ functionInfo,
1854
+ items,
1855
+ startingNumber,
1856
+ {
1857
+ formatter: functionInfo.formatter,
1858
+ sdk: context.sdk,
1859
+ params: context.params
1860
+ }
1862
1861
  );
1863
- if (obj?.description)
1864
- console.log(` ${chalk__default.default.dim(String(obj.description))}`);
1865
- console.log();
1866
- });
1862
+ } else {
1863
+ items.forEach((item, index) => {
1864
+ const obj = item;
1865
+ const name = obj?.name || obj?.key || obj?.id || "Item";
1866
+ console.log(
1867
+ `${chalk__default.default.gray(`${startingNumber + index + 1}.`)} ${chalk__default.default.cyan(String(name))}`
1868
+ );
1869
+ if (obj?.description)
1870
+ console.log(` ${chalk__default.default.dim(String(obj.description))}`);
1871
+ console.log();
1872
+ });
1873
+ }
1867
1874
  }
1868
- }
1869
- function createInteractiveRenderer() {
1870
1875
  return {
1871
1876
  async renderPaginatedList(source, functionInfo) {
1872
1877
  const itemName = getItemName(functionInfo);
@@ -1876,7 +1881,7 @@ function createInteractiveRenderer() {
1876
1881
  console.log(chalk__default.default.yellow(`No ${itemName} found.`));
1877
1882
  return;
1878
1883
  }
1879
- renderItemsForDisplay(items, functionInfo, 0);
1884
+ await renderItemsForDisplay(items, functionInfo, 0);
1880
1885
  console.log(chalk__default.default.green(`
1881
1886
  \u2705 Showing ${items.length} ${itemName}`));
1882
1887
  return;
@@ -1898,7 +1903,7 @@ function createInteractiveRenderer() {
1898
1903
  console.log(chalk__default.default.blue(`\u{1F4CB} ${getListTitle(functionInfo)}
1899
1904
  `));
1900
1905
  }
1901
- renderItemsForDisplay(items, functionInfo, totalShown);
1906
+ await renderItemsForDisplay(items, functionInfo, totalShown);
1902
1907
  totalShown += items.length;
1903
1908
  console.log(
1904
1909
  chalk__default.default.green(
@@ -1923,7 +1928,7 @@ function createInteractiveRenderer() {
1923
1928
  console.log(chalk__default.default.gray(`
1924
1929
  \u{1F4C4} Finished browsing ${itemName}`));
1925
1930
  },
1926
- renderCollectedList(items, { maxItems, userSpecifiedMaxItems, functionInfo } = {}) {
1931
+ async renderCollectedList(items, { maxItems, userSpecifiedMaxItems, functionInfo } = {}) {
1927
1932
  if (!Array.isArray(items)) {
1928
1933
  formatJsonOutput(items);
1929
1934
  return;
@@ -1936,7 +1941,7 @@ function createInteractiveRenderer() {
1936
1941
  console.log(chalk__default.default.green(`
1937
1942
  \u2705 Found ${items.length} ${itemName}:
1938
1943
  `));
1939
- renderItemsForDisplay(items, functionInfo);
1944
+ await renderItemsForDisplay(items, functionInfo);
1940
1945
  if (userSpecifiedMaxItems && maxItems) {
1941
1946
  console.log(
1942
1947
  chalk__default.default.gray(
@@ -2399,11 +2404,11 @@ function createCommandConfig(cliCommandName, functionInfo, sdk) {
2399
2404
  const startTime = Date.now();
2400
2405
  let success = true;
2401
2406
  let errorMessage = null;
2402
- let resolvedParams = {};
2407
+ const resolvedParams = {};
2403
2408
  const commandObj = args[args.length - 1];
2404
2409
  const options = commandObj.opts();
2405
2410
  const interactiveMode = !options.json;
2406
- const renderer = interactiveMode ? createInteractiveRenderer() : createJsonRenderer();
2411
+ const renderer = interactiveMode ? createInteractiveRenderer({ sdk, params: resolvedParams }) : createJsonRenderer();
2407
2412
  try {
2408
2413
  emitDeprecationWarning({
2409
2414
  cliCommandName,
@@ -2436,7 +2441,7 @@ function createCommandConfig(cliCommandName, functionInfo, sdk) {
2436
2441
  }
2437
2442
  if (schema && !usesInputParameters) {
2438
2443
  const resolver = new SchemaParameterResolver();
2439
- resolvedParams = await resolver.resolveParameters(
2444
+ const resolved = await resolver.resolveParameters(
2440
2445
  schema,
2441
2446
  rawParams,
2442
2447
  sdk,
@@ -2446,8 +2451,9 @@ function createCommandConfig(cliCommandName, functionInfo, sdk) {
2446
2451
  debug: !!options.debug || process.env.DEBUG === "true" || process.argv.includes("--debug")
2447
2452
  }
2448
2453
  );
2454
+ Object.assign(resolvedParams, resolved);
2449
2455
  } else {
2450
- resolvedParams = rawParams;
2456
+ Object.assign(resolvedParams, rawParams);
2451
2457
  }
2452
2458
  const confirm = functionInfo.confirm;
2453
2459
  let confirmMessageAfter;
@@ -2476,7 +2482,7 @@ function createCommandConfig(cliCommandName, functionInfo, sdk) {
2476
2482
  sdkResult,
2477
2483
  maxItems
2478
2484
  });
2479
- renderer.renderCollectedList(allItems, {
2485
+ await renderer.renderCollectedList(allItems, {
2480
2486
  maxItems,
2481
2487
  userSpecifiedMaxItems: hasUserSpecifiedMaxItems,
2482
2488
  functionInfo
@@ -2510,7 +2516,7 @@ function createCommandConfig(cliCommandName, functionInfo, sdk) {
2510
2516
  if (normalizedResult.kind === "response") {
2511
2517
  await renderer.renderResponse(normalizedResult.value);
2512
2518
  } else if (normalizedResult.kind === "list") {
2513
- renderer.renderCollectedList(normalizedResult.data, {
2519
+ await renderer.renderCollectedList(normalizedResult.data, {
2514
2520
  maxItems: resolvedParams.maxItems,
2515
2521
  userSpecifiedMaxItems: hasUserSpecifiedMaxItems,
2516
2522
  functionInfo
@@ -2566,7 +2572,7 @@ ${confirmMessageAfter}`));
2566
2572
  description,
2567
2573
  parameters,
2568
2574
  handler,
2569
- hidden: functionInfo.categories?.includes("deprecated") ?? false,
2575
+ hidden: !!functionInfo.deprecation,
2570
2576
  aliases: functionInfo.aliases,
2571
2577
  supportsJsonOutput: functionInfo.supportsJsonOutput
2572
2578
  };
@@ -2725,7 +2731,7 @@ var login_exports = {};
2725
2731
  __export(login_exports, {
2726
2732
  AUTH_MODE_HEADER: () => AUTH_MODE_HEADER,
2727
2733
  DEFAULT_AUTH_BASE_URL: () => DEFAULT_AUTH_BASE_URL,
2728
- ZapierAuthenticationError: () => ZapierAuthenticationError,
2734
+ ZapierAuthenticationError: () => zapierSdk.ZapierAuthenticationError,
2729
2735
  clearTokensFromKeychain: () => clearTokensFromKeychain,
2730
2736
  createCache: () => createCache,
2731
2737
  getActiveCredentials: () => getActiveCredentials,
@@ -3129,12 +3135,6 @@ async function deleteStoredClientCredentials({
3129
3135
  }
3130
3136
 
3131
3137
  // src/login/index.ts
3132
- var ZapierAuthenticationError = class extends Error {
3133
- constructor(message) {
3134
- super(message);
3135
- this.name = "ZapierAuthenticationError";
3136
- }
3137
- };
3138
3138
  var DEFAULT_AUTH_CLIENT_ID = "grwWZD5hUWGvb4V8ODBuOtXer3h0DBEZ2HR8aay6";
3139
3139
  var TOKEN_REFRESH_BUFFER_MS = 5 * 60 * 1e3;
3140
3140
  function createDebugLog(enabled) {
@@ -3144,9 +3144,9 @@ function createDebugLog(enabled) {
3144
3144
  }
3145
3145
  return (message, data) => {
3146
3146
  if (data === void 0) {
3147
- console.log(`[Zapier SDK CLI Login] ${message}`);
3147
+ console.error(`[Zapier SDK CLI Login] ${message}`);
3148
3148
  } else {
3149
- console.log(`[Zapier SDK CLI Login] ${message}`, data);
3149
+ console.error(`[Zapier SDK CLI Login] ${message}`, data);
3150
3150
  }
3151
3151
  };
3152
3152
  }
@@ -3392,7 +3392,7 @@ async function getToken(options = {}) {
3392
3392
  return await resolveOrRefreshToken(options);
3393
3393
  } catch (error) {
3394
3394
  const message = error instanceof Error ? error.message : "Token refresh failed";
3395
- throw new ZapierAuthenticationError(
3395
+ throw new zapierSdk.ZapierAuthenticationError(
3396
3396
  `${message}
3397
3397
  Please run 'login' to authenticate again.`
3398
3398
  );
@@ -3545,45 +3545,186 @@ async function revokeCredentials({
3545
3545
  });
3546
3546
  emitAuthLogout(onEvent);
3547
3547
  }
3548
+ function getBaseUrlFromResolvedCredentials(credentials2) {
3549
+ if (credentials2 && zapierSdk.isCredentialsObject(credentials2)) {
3550
+ return credentials2.baseUrl;
3551
+ }
3552
+ return void 0;
3553
+ }
3554
+ function getBaseUrlFromOptionsCredentials(credentials2) {
3555
+ if (credentials2 && typeof credentials2 === "object" && "baseUrl" in credentials2 && typeof credentials2.baseUrl === "string") {
3556
+ return credentials2.baseUrl;
3557
+ }
3558
+ return void 0;
3559
+ }
3560
+ async function resolveCredentialsBaseUrl(context) {
3561
+ const resolvedCredentials = "resolvedCredentials" in context ? context.resolvedCredentials : await context.resolveCredentials?.();
3562
+ return getBaseUrlFromResolvedCredentials(resolvedCredentials) ?? getBaseUrlFromOptionsCredentials(context.options?.credentials) ?? context.options?.baseUrl;
3563
+ }
3548
3564
 
3549
- // src/utils/constants.ts
3550
- var LOGIN_PORTS = [49505, 50575, 52804, 55981, 61010, 63851];
3551
- var LOGIN_TIMEOUT_MS = 3e5;
3552
- var spinPromise = async (promise, text) => {
3553
- const spinner = ora__default.default(text).start();
3565
+ // src/utils/non-interactive.ts
3566
+ function resolveNonInteractive(options) {
3567
+ return options.nonInteractive === true || options.skipPrompts === true || !process.stdin.isTTY || !process.stdout.isTTY;
3568
+ }
3569
+
3570
+ // src/utils/auth/client-credentials.ts
3571
+ var CREDENTIALS_SCOPES = ["external", "credentials"];
3572
+ var EMPTY_POLICY = {
3573
+ version: 2,
3574
+ statements: []
3575
+ };
3576
+ async function createCredentialsOnServer(api2, name, policy) {
3577
+ const response = await api2.post(
3578
+ "/api/v0/client-credentials",
3579
+ {
3580
+ name,
3581
+ allowed_scopes: CREDENTIALS_SCOPES,
3582
+ ...policy !== void 0 && { policy }
3583
+ },
3584
+ { authRequired: true, requiredScopes: ["credentials"] }
3585
+ );
3586
+ return {
3587
+ clientId: response.data.client_id,
3588
+ clientSecret: response.data.client_secret
3589
+ };
3590
+ }
3591
+ async function deleteCredentialsOnServer(api2, clientId) {
3592
+ await api2.delete(`/api/v0/client-credentials/${clientId}`, void 0, {
3593
+ authRequired: true,
3594
+ requiredScopes: ["credentials"]
3595
+ });
3596
+ }
3597
+ async function setupClientCredentials({
3598
+ api: api2,
3599
+ name,
3600
+ credentialsBaseUrl: credentialsBaseUrl2,
3601
+ policy
3602
+ }) {
3603
+ const { clientId, clientSecret } = await createCredentialsOnServer(
3604
+ api2,
3605
+ name,
3606
+ policy
3607
+ );
3554
3608
  try {
3555
- const result = await promise;
3556
- spinner.succeed();
3557
- return result;
3558
- } catch (error) {
3559
- if (error instanceof ZapierCliUserCancellationError) {
3560
- spinner.stop();
3561
- } else {
3562
- spinner.fail();
3609
+ await withRetry({
3610
+ action: () => storeClientCredentials({
3611
+ name,
3612
+ clientId,
3613
+ clientSecret,
3614
+ scopes: [...CREDENTIALS_SCOPES],
3615
+ baseUrl: credentialsBaseUrl2
3616
+ })
3617
+ });
3618
+ } catch (storeErr) {
3619
+ try {
3620
+ await withRetry({
3621
+ action: () => deleteCredentialsOnServer(api2, clientId)
3622
+ });
3623
+ } catch {
3624
+ console.error(
3625
+ `Failed to roll back orphaned credential ${clientId}. Delete it manually with: zapier-sdk delete-client-credentials ${clientId}`
3626
+ );
3563
3627
  }
3564
- throw error;
3628
+ throw storeErr;
3565
3629
  }
3630
+ return { clientId };
3631
+ }
3632
+
3633
+ // src/utils/constants.ts
3634
+ var LOGIN_PORTS = [49505, 50575, 52804, 55981, 61010, 63851];
3635
+ var LOGIN_TIMEOUT_MS = 3e5;
3636
+
3637
+ // src/utils/getCallablePromise.ts
3638
+ var getCallablePromise = () => {
3639
+ let resolve4 = () => {
3640
+ };
3641
+ let reject = () => {
3642
+ };
3643
+ const promise = new Promise((_resolve, _reject) => {
3644
+ resolve4 = _resolve;
3645
+ reject = _reject;
3646
+ });
3647
+ return {
3648
+ promise,
3649
+ resolve: resolve4,
3650
+ reject
3651
+ };
3566
3652
  };
3653
+ var getCallablePromise_default = getCallablePromise;
3567
3654
  var log = {
3568
3655
  info: (message, ...args) => {
3569
- console.log(chalk__default.default.blue("\u2139"), message, ...args);
3656
+ console.error(chalk__default.default.blue("\u2139"), message, ...args);
3570
3657
  },
3571
3658
  error: (message, ...args) => {
3572
3659
  console.error(chalk__default.default.red("\u2716"), message, ...args);
3573
3660
  },
3574
3661
  success: (message, ...args) => {
3575
- console.log(chalk__default.default.green("\u2713"), message, ...args);
3662
+ console.error(chalk__default.default.green("\u2713"), message, ...args);
3576
3663
  },
3577
3664
  warn: (message, ...args) => {
3578
- console.log(chalk__default.default.yellow("\u26A0"), message, ...args);
3665
+ console.error(chalk__default.default.yellow("\u26A0"), message, ...args);
3579
3666
  },
3580
3667
  debug: (message, ...args) => {
3581
3668
  if (process.env.DEBUG === "true" || process.argv.includes("--debug")) {
3582
- console.log(chalk__default.default.gray("\u{1F41B}"), message, ...args);
3669
+ console.error(chalk__default.default.gray("\u{1F41B}"), message, ...args);
3583
3670
  }
3584
3671
  }
3585
3672
  };
3586
3673
  var log_default = log;
3674
+ var spinPromise = async (promise, text) => {
3675
+ const spinner = ora__default.default(text).start();
3676
+ try {
3677
+ const result = await promise;
3678
+ spinner.succeed();
3679
+ return result;
3680
+ } catch (error) {
3681
+ if (error instanceof ZapierCliUserCancellationError) {
3682
+ spinner.stop();
3683
+ } else {
3684
+ spinner.fail();
3685
+ }
3686
+ throw error;
3687
+ }
3688
+ };
3689
+
3690
+ // src/utils/auth/oauth-callback.ts
3691
+ function getCallbackCode({
3692
+ callbackUrl,
3693
+ transaction,
3694
+ recoveryMessage
3695
+ }) {
3696
+ let parsed;
3697
+ try {
3698
+ parsed = new URL(callbackUrl.trim());
3699
+ } catch {
3700
+ throw new ZapierCliValidationError(
3701
+ "Paste the final OAuth callback URL from your browser."
3702
+ );
3703
+ }
3704
+ const expected = new URL(transaction.redirectUri);
3705
+ if (parsed.protocol !== "http:" || parsed.hostname !== expected.hostname || parsed.pathname !== expected.pathname || parsed.port !== expected.port) {
3706
+ throw new ZapierCliValidationError(
3707
+ `Expected the final OAuth callback URL to start with ${transaction.redirectUri}.`
3708
+ );
3709
+ }
3710
+ if (parsed.searchParams.get("state") !== transaction.state) {
3711
+ throw new ZapierCliValidationError(
3712
+ `OAuth state mismatch.${recoveryMessage ? ` ${recoveryMessage}` : ""}`
3713
+ );
3714
+ }
3715
+ if (parsed.searchParams.has("error")) {
3716
+ throw new ZapierCliValidationError(
3717
+ `Authorization denied: ${parsed.searchParams.get("error_description") ?? parsed.searchParams.get("error")}.${recoveryMessage ? ` ${recoveryMessage}` : ""}`
3718
+ );
3719
+ }
3720
+ const code = parsed.searchParams.get("code");
3721
+ if (!code) {
3722
+ throw new ZapierCliValidationError(
3723
+ "No authorization code found in the pasted callback URL."
3724
+ );
3725
+ }
3726
+ return code;
3727
+ }
3587
3728
 
3588
3729
  // src/utils/api/client.ts
3589
3730
  var createApiClient = () => {
@@ -3614,179 +3755,77 @@ var createApiClient = () => {
3614
3755
  var api = createApiClient();
3615
3756
  var client_default = api;
3616
3757
 
3617
- // src/utils/getCallablePromise.ts
3618
- var getCallablePromise = () => {
3619
- let resolve4 = () => {
3620
- };
3621
- let reject = () => {
3622
- };
3623
- const promise = new Promise((_resolve, _reject) => {
3624
- resolve4 = _resolve;
3625
- reject = _reject;
3626
- });
3627
- return {
3628
- promise,
3629
- resolve: resolve4,
3630
- reject
3631
- };
3632
- };
3633
- var getCallablePromise_default = getCallablePromise;
3634
-
3635
- // src/utils/auth/oauth-flow.ts
3636
- var findAvailablePort = () => {
3637
- return new Promise((resolve4, reject) => {
3638
- let portIndex = 0;
3639
- const tryPort = (port) => {
3640
- const server = express__default.default().listen(port, () => {
3641
- server.close();
3642
- resolve4(port);
3643
- });
3644
- server.on("error", (err) => {
3645
- if (err.code === "EADDRINUSE") {
3646
- if (portIndex < LOGIN_PORTS.length) {
3647
- tryPort(LOGIN_PORTS[portIndex++]);
3648
- } else {
3649
- reject(
3650
- new Error(
3651
- `All configured OAuth callback ports are busy: ${LOGIN_PORTS.join(", ")}. Please try again later or close applications using these ports.`
3652
- )
3653
- );
3654
- }
3655
- } else {
3656
- reject(err);
3657
- }
3658
- });
3659
- };
3660
- if (LOGIN_PORTS.length > 0) {
3661
- tryPort(LOGIN_PORTS[portIndex++]);
3662
- } else {
3663
- reject(new Error("No OAuth callback ports configured"));
3664
- }
3665
- });
3666
- };
3667
- var generateRandomString = () => {
3758
+ // src/utils/auth/oauth-transaction.ts
3759
+ var OAUTH_LOOPBACK_HOST = "localhost";
3760
+ function buildBrowserAuthUrl({
3761
+ authorizeUrl,
3762
+ entryPoint = "login"
3763
+ }) {
3764
+ if (entryPoint === "login") return authorizeUrl;
3765
+ const parsedAuthorizeUrl = new URL(authorizeUrl);
3766
+ const signupUrl = new URL("/sign-up", parsedAuthorizeUrl);
3767
+ signupUrl.searchParams.set("skipOnboarding", "true");
3768
+ signupUrl.searchParams.set(
3769
+ "next",
3770
+ `${parsedAuthorizeUrl.pathname}${parsedAuthorizeUrl.search}`
3771
+ );
3772
+ return signupUrl.toString();
3773
+ }
3774
+ function generateRandomString() {
3668
3775
  const array = new Uint32Array(28);
3669
3776
  crypto__default.default.getRandomValues(array);
3670
3777
  return Array.from(array, (dec) => ("0" + dec.toString(16)).slice(-2)).join(
3671
3778
  ""
3672
3779
  );
3673
- };
3780
+ }
3674
3781
  function ensureOfflineAccess(scope) {
3675
- if (scope.includes("offline_access")) {
3676
- return scope;
3677
- }
3782
+ if (scope.includes("offline_access")) return scope;
3678
3783
  return `${scope} offline_access`;
3679
3784
  }
3680
- async function runOauthFlow({
3681
- timeoutMs = LOGIN_TIMEOUT_MS,
3785
+ async function prepareOauthTransaction({
3682
3786
  pkceCredentials,
3683
- baseUrl: baseUrl2
3787
+ baseUrl: baseUrl2,
3788
+ redirectUri,
3789
+ entryPoint = "login"
3684
3790
  }) {
3685
3791
  const { clientId, tokenUrl, authorizeUrl } = getPkceLoginConfig({
3686
3792
  credentials: pkceCredentials,
3687
3793
  baseUrl: baseUrl2
3688
3794
  });
3689
- const scope = ensureOfflineAccess(
3690
- pkceCredentials?.scope || "internal credentials"
3691
- );
3692
- const availablePort = await findAvailablePort();
3693
- const redirectUri = `http://localhost:${availablePort}/oauth`;
3694
- log_default.info(`Using port ${availablePort} for OAuth callback`);
3695
- const {
3696
- promise: promisedCode,
3697
- resolve: setCode,
3698
- reject: rejectCode
3699
- } = getCallablePromise_default();
3700
- const oauthState = generateRandomString();
3701
- const expressApp = express__default.default();
3702
- expressApp.get("/oauth", (req, res) => {
3703
- res.setHeader("Connection", "close");
3704
- if (req.query.state !== oauthState) {
3705
- rejectCode(new Error("OAuth state mismatch \u2014 possible CSRF"));
3706
- res.status(400).end("Invalid state. You can close this tab.");
3707
- return;
3708
- }
3709
- if (req.query.error) {
3710
- const desc = req.query.error_description ?? req.query.error;
3711
- rejectCode(new Error(`Authorization denied: ${desc}`));
3712
- res.end("Authorization was denied. You can close this tab.");
3713
- return;
3714
- }
3715
- if (!req.query.code) {
3716
- rejectCode(new Error("No authorization code received"));
3717
- res.end("No authorization code received. You can close this tab.");
3718
- return;
3719
- }
3720
- setCode(String(req.query.code));
3721
- res.end("You can now close this tab and return to the CLI.");
3722
- });
3723
- const server = expressApp.listen(availablePort);
3724
- const connections = /* @__PURE__ */ new Set();
3725
- server.on("connection", (conn) => {
3726
- connections.add(conn);
3727
- conn.on("close", () => connections.delete(conn));
3728
- });
3729
- const cleanup = () => {
3730
- server.close();
3731
- log_default.info("\n\u274C Login cancelled by user");
3732
- rejectCode(new ZapierCliUserCancellationError());
3733
- };
3734
- process.on("SIGINT", cleanup);
3735
- process.on("SIGTERM", cleanup);
3736
3795
  const { code_verifier: codeVerifier, code_challenge: codeChallenge } = await pkceChallenge__default.default();
3796
+ const state = generateRandomString();
3737
3797
  const authUrl = `${authorizeUrl}?${new URLSearchParams({
3738
3798
  response_type: "code",
3739
3799
  client_id: clientId,
3740
3800
  redirect_uri: redirectUri,
3741
- scope,
3742
- state: oauthState,
3801
+ scope: ensureOfflineAccess(
3802
+ pkceCredentials?.scope || "internal credentials"
3803
+ ),
3804
+ state,
3743
3805
  code_challenge: codeChallenge,
3744
3806
  code_challenge_method: "S256"
3745
3807
  }).toString()}`;
3746
- log_default.info("Opening your browser to log in.");
3747
- log_default.info("If it doesn't open, visit:", authUrl);
3748
- open__default.default(authUrl);
3749
- let timeoutTimer;
3750
- try {
3751
- await spinPromise(
3752
- Promise.race([
3753
- promisedCode,
3754
- new Promise((_resolve, reject) => {
3755
- timeoutTimer = setTimeout(() => {
3756
- reject(
3757
- new Error(
3758
- `Login timed out after ${Math.round(timeoutMs / 1e3)} seconds.`
3759
- )
3760
- );
3761
- }, timeoutMs);
3762
- })
3763
- ]),
3764
- "Waiting for you to login and authorize"
3765
- );
3766
- } finally {
3767
- if (timeoutTimer) {
3768
- clearTimeout(timeoutTimer);
3769
- }
3770
- process.off("SIGINT", cleanup);
3771
- process.off("SIGTERM", cleanup);
3772
- await new Promise((resolve4) => {
3773
- const timeout = setTimeout(() => {
3774
- log_default.info("Server close timed out, forcing connection shutdown...");
3775
- connections.forEach((conn) => conn.destroy());
3776
- resolve4();
3777
- }, 1e3);
3778
- server.close(() => {
3779
- clearTimeout(timeout);
3780
- resolve4();
3781
- });
3782
- });
3783
- }
3784
- log_default.info("Exchanging authorization code for tokens...");
3808
+ return {
3809
+ browserAuthUrl: buildBrowserAuthUrl({ authorizeUrl: authUrl, entryPoint }),
3810
+ clientId,
3811
+ codeVerifier,
3812
+ redirectUri,
3813
+ state,
3814
+ tokenUrl
3815
+ };
3816
+ }
3817
+ async function exchangeOauthCode({
3818
+ tokenUrl,
3819
+ code,
3820
+ redirectUri,
3821
+ clientId,
3822
+ codeVerifier
3823
+ }) {
3785
3824
  const { data } = await client_default.post(
3786
3825
  tokenUrl,
3787
3826
  {
3788
3827
  grant_type: "authorization_code",
3789
- code: await promisedCode,
3828
+ code,
3790
3829
  redirect_uri: redirectUri,
3791
3830
  client_id: clientId,
3792
3831
  code_verifier: codeVerifier
@@ -3798,7 +3837,6 @@ async function runOauthFlow({
3798
3837
  }
3799
3838
  }
3800
3839
  );
3801
- log_default.info("Token exchange completed successfully");
3802
3840
  return {
3803
3841
  accessToken: data.access_token,
3804
3842
  refreshToken: data.refresh_token,
@@ -3806,105 +3844,467 @@ async function runOauthFlow({
3806
3844
  };
3807
3845
  }
3808
3846
 
3809
- // src/utils/auth/client-credentials.ts
3810
- var CREDENTIALS_SCOPES = ["external", "credentials"];
3811
- var EMPTY_POLICY = {
3812
- version: 2,
3813
- statements: []
3847
+ // src/utils/auth/oauth-flow.ts
3848
+ var OauthFlowTimeoutError = class extends Error {
3849
+ constructor(timeoutMs) {
3850
+ super("OAuth flow timed out");
3851
+ this.timeoutMs = timeoutMs;
3852
+ this.name = "OauthFlowTimeoutError";
3853
+ }
3814
3854
  };
3815
- async function createCredentialsOnServer(api2, name, policy) {
3816
- const response = await api2.post(
3817
- "/api/v0/client-credentials",
3818
- {
3819
- name,
3820
- allowed_scopes: CREDENTIALS_SCOPES,
3821
- ...policy !== void 0 && { policy }
3822
- },
3823
- { authRequired: true, requiredScopes: ["credentials"] }
3824
- );
3825
- return {
3826
- clientId: response.data.client_id,
3827
- clientSecret: response.data.client_secret
3828
- };
3855
+ var OauthAuthorizationDeniedError = class extends Error {
3856
+ constructor(reason) {
3857
+ super("OAuth authorization denied");
3858
+ this.reason = reason;
3859
+ this.name = "OauthAuthorizationDeniedError";
3860
+ }
3861
+ };
3862
+ function findAvailablePort() {
3863
+ return new Promise((resolve4, reject) => {
3864
+ let portIndex = 0;
3865
+ const tryPort = (port) => {
3866
+ const server = express__default.default().listen(port, OAUTH_LOOPBACK_HOST, () => {
3867
+ server.close();
3868
+ resolve4(port);
3869
+ });
3870
+ server.on("error", (err) => {
3871
+ if (err.code === "EADDRINUSE" && portIndex < LOGIN_PORTS.length) {
3872
+ tryPort(LOGIN_PORTS[portIndex++]);
3873
+ } else if (err.code === "EADDRINUSE") {
3874
+ reject(
3875
+ new Error(
3876
+ `All configured OAuth callback ports are busy: ${LOGIN_PORTS.join(", ")}. Please try again later or close applications using these ports.`
3877
+ )
3878
+ );
3879
+ } else {
3880
+ reject(err);
3881
+ }
3882
+ });
3883
+ };
3884
+ if (LOGIN_PORTS.length > 0) tryPort(LOGIN_PORTS[portIndex++]);
3885
+ else reject(new Error("No OAuth callback ports configured"));
3886
+ });
3829
3887
  }
3830
- async function deleteCredentialsOnServer(api2, clientId) {
3831
- await api2.delete(`/api/v0/client-credentials/${clientId}`, void 0, {
3832
- authRequired: true,
3833
- requiredScopes: ["credentials"]
3888
+ async function runLoginOauthFlow(options) {
3889
+ return runOauthFlowEntryPoint({
3890
+ ...options,
3891
+ entryPoint: "login",
3892
+ authAction: "log in",
3893
+ flowName: "Login"
3834
3894
  });
3835
3895
  }
3836
- async function setupClientCredentials({
3837
- api: api2,
3838
- name,
3839
- credentialsBaseUrl: credentialsBaseUrl2,
3840
- policy
3896
+ async function runSignupOauthFlow(options) {
3897
+ if (options.headless) {
3898
+ return runOauthFlowEntryPoint({
3899
+ ...options,
3900
+ entryPoint: "signup",
3901
+ authAction: "sign up",
3902
+ flowName: "Signup",
3903
+ headless: true
3904
+ });
3905
+ }
3906
+ return runOauthFlowEntryPoint({
3907
+ ...options,
3908
+ entryPoint: "signup",
3909
+ authAction: "sign up",
3910
+ flowName: "Signup"
3911
+ });
3912
+ }
3913
+ async function runOauthFlowEntryPoint({
3914
+ flowName,
3915
+ ...options
3841
3916
  }) {
3842
- const { clientId, clientSecret } = await createCredentialsOnServer(
3843
- api2,
3844
- name,
3845
- policy
3917
+ try {
3918
+ return options.headless ? await runHeadlessSignupOauthFlow(options) : await runOauthFlow(options);
3919
+ } catch (error) {
3920
+ if (error instanceof OauthFlowTimeoutError) {
3921
+ throw new Error(
3922
+ withRecoveryMessage(
3923
+ `${flowName} timed out after ${Math.round(error.timeoutMs / 1e3)} seconds.`,
3924
+ options.recoveryMessage
3925
+ )
3926
+ );
3927
+ }
3928
+ if (error instanceof OauthAuthorizationDeniedError) {
3929
+ throw new Error(
3930
+ withRecoveryMessage(
3931
+ `Authorization denied: ${error.reason}.`,
3932
+ options.recoveryMessage
3933
+ )
3934
+ );
3935
+ }
3936
+ if (error instanceof ZapierCliUserCancellationError && !options.silent) {
3937
+ log_default.info(`
3938
+ \u274C ${flowName} cancelled by user`);
3939
+ }
3940
+ throw error;
3941
+ }
3942
+ }
3943
+ function withRecoveryMessage(message, recoveryMessage) {
3944
+ return recoveryMessage ? `${message} ${recoveryMessage}` : message;
3945
+ }
3946
+ async function runOauthFlow({
3947
+ timeoutMs = LOGIN_TIMEOUT_MS,
3948
+ pkceCredentials,
3949
+ baseUrl: baseUrl2,
3950
+ entryPoint,
3951
+ authAction,
3952
+ silent = false,
3953
+ onProgress
3954
+ }) {
3955
+ const port = await findAvailablePort();
3956
+ if (!silent) log_default.info(`Using port ${port} for OAuth callback`);
3957
+ const transaction = await prepareOauthTransaction({
3958
+ pkceCredentials,
3959
+ baseUrl: baseUrl2,
3960
+ redirectUri: `http://${OAUTH_LOOPBACK_HOST}:${port}/oauth`,
3961
+ entryPoint
3962
+ });
3963
+ const code = await collectLocalCallbackCode({
3964
+ transaction,
3965
+ timeoutMs,
3966
+ authAction,
3967
+ silent,
3968
+ onProgress
3969
+ });
3970
+ onProgress?.({ type: "callback_accepted" });
3971
+ if (!silent) log_default.info("Exchanging authorization code for tokens...");
3972
+ onProgress?.({ type: "token_exchange_started" });
3973
+ const tokens = await exchangeOauthCode({ ...transaction, code });
3974
+ if (!silent) log_default.info("Token exchange completed successfully");
3975
+ onProgress?.({ type: "token_exchange_completed" });
3976
+ return tokens;
3977
+ }
3978
+ async function readHeadlessCallbackUrl({
3979
+ timeoutMs,
3980
+ interactive,
3981
+ recoveryMessage
3982
+ }) {
3983
+ const timeoutMessage = withRecoveryMessage(
3984
+ `Signup timed out after ${Math.round(timeoutMs / 1e3)} seconds.`,
3985
+ recoveryMessage
3986
+ );
3987
+ const missingCallbackUrlMessage = withRecoveryMessage(
3988
+ "Paste the final OAuth callback URL from your browser.",
3989
+ recoveryMessage
3846
3990
  );
3991
+ const rl = promises$1.createInterface({ input: process.stdin, output: process.stderr });
3992
+ const abortController = new AbortController();
3993
+ const timeoutTimer = setTimeout(() => abortController.abort(), timeoutMs);
3994
+ const readUrl = interactive ? rl.question("Paste the final OAuth callback URL: ", {
3995
+ signal: abortController.signal
3996
+ }) : new Promise((resolve4, reject) => {
3997
+ let settled = false;
3998
+ const settleResolve = (value) => {
3999
+ settled = true;
4000
+ resolve4(value);
4001
+ };
4002
+ const settleReject = (error) => {
4003
+ if (settled) return;
4004
+ settled = true;
4005
+ reject(error);
4006
+ };
4007
+ abortController.signal.addEventListener(
4008
+ "abort",
4009
+ () => settleReject(new Error(timeoutMessage)),
4010
+ { once: true }
4011
+ );
4012
+ rl.once("line", settleResolve);
4013
+ rl.once(
4014
+ "close",
4015
+ () => settleReject(new ZapierCliValidationError(missingCallbackUrlMessage))
4016
+ );
4017
+ rl.once("error", settleReject);
4018
+ });
3847
4019
  try {
3848
- await withRetry({
3849
- action: () => storeClientCredentials({
3850
- name,
3851
- clientId,
3852
- clientSecret,
3853
- scopes: [...CREDENTIALS_SCOPES],
3854
- baseUrl: credentialsBaseUrl2
3855
- })
4020
+ return await readUrl.catch((error) => {
4021
+ if (error instanceof Error && error.name === "AbortError") {
4022
+ throw new Error(timeoutMessage);
4023
+ }
4024
+ throw error;
3856
4025
  });
3857
- } catch (storeErr) {
3858
- try {
3859
- await withRetry({
3860
- action: () => deleteCredentialsOnServer(api2, clientId)
3861
- });
3862
- } catch {
3863
- console.error(
3864
- `Failed to roll back orphaned credential ${clientId}. Delete it manually with: zapier-sdk delete-client-credentials ${clientId}`
4026
+ } finally {
4027
+ clearTimeout(timeoutTimer);
4028
+ rl.close();
4029
+ }
4030
+ }
4031
+ async function runHeadlessSignupOauthFlow({
4032
+ timeoutMs = LOGIN_TIMEOUT_MS,
4033
+ pkceCredentials,
4034
+ baseUrl: baseUrl2,
4035
+ interactive = true,
4036
+ onProgress,
4037
+ recoveryMessage
4038
+ }) {
4039
+ const port = LOGIN_PORTS[0];
4040
+ const transaction = await prepareOauthTransaction({
4041
+ pkceCredentials,
4042
+ baseUrl: baseUrl2,
4043
+ redirectUri: `http://${OAUTH_LOOPBACK_HOST}:${port}/oauth`,
4044
+ entryPoint: "signup"
4045
+ });
4046
+ console.log(
4047
+ "Use this mode when signing up from a machine that has no browser."
4048
+ );
4049
+ console.log("Open this signup URL in a browser on another machine:");
4050
+ console.log(transaction.browserAuthUrl);
4051
+ console.log(
4052
+ `When the browser lands on ${transaction.redirectUri} and cannot connect, paste the full final URL back here.`
4053
+ );
4054
+ const callbackUrl = await readHeadlessCallbackUrl({
4055
+ timeoutMs,
4056
+ interactive,
4057
+ recoveryMessage
4058
+ });
4059
+ const code = getCallbackCode({
4060
+ callbackUrl,
4061
+ transaction,
4062
+ recoveryMessage
4063
+ });
4064
+ onProgress?.({ type: "callback_accepted" });
4065
+ console.log("Exchanging authorization code for tokens...");
4066
+ onProgress?.({ type: "token_exchange_started" });
4067
+ const tokens = await exchangeOauthCode({ ...transaction, code });
4068
+ onProgress?.({ type: "token_exchange_completed" });
4069
+ return tokens;
4070
+ }
4071
+ async function collectLocalCallbackCode({
4072
+ transaction,
4073
+ timeoutMs,
4074
+ authAction,
4075
+ silent,
4076
+ onProgress
4077
+ }) {
4078
+ const { promise, resolve: resolve4, reject } = getCallablePromise_default();
4079
+ const app = express__default.default();
4080
+ app.get("/oauth", (req, res) => {
4081
+ res.setHeader("Connection", "close");
4082
+ if (req.query.state !== transaction.state) {
4083
+ res.status(400).end("Invalid state. You can close this tab.");
4084
+ } else if (req.query.error) {
4085
+ reject(
4086
+ new OauthAuthorizationDeniedError(
4087
+ String(req.query.error_description ?? req.query.error)
4088
+ )
3865
4089
  );
4090
+ res.end("Authorization was denied. You can close this tab.");
4091
+ } else if (!req.query.code) {
4092
+ reject(new Error("No authorization code received"));
4093
+ res.end("No authorization code received. You can close this tab.");
4094
+ } else {
4095
+ resolve4(String(req.query.code));
4096
+ res.end("You can now close this tab and return to the CLI.");
3866
4097
  }
3867
- throw storeErr;
4098
+ });
4099
+ const server = app.listen(
4100
+ Number(new URL(transaction.redirectUri).port),
4101
+ OAUTH_LOOPBACK_HOST
4102
+ );
4103
+ const connections = /* @__PURE__ */ new Set();
4104
+ server.on("connection", (conn) => {
4105
+ connections.add(conn);
4106
+ conn.on("close", () => connections.delete(conn));
4107
+ });
4108
+ const cleanup = () => {
4109
+ server.close();
4110
+ reject(new ZapierCliUserCancellationError());
4111
+ };
4112
+ process.on("SIGINT", cleanup);
4113
+ process.on("SIGTERM", cleanup);
4114
+ let timeoutTimer;
4115
+ try {
4116
+ await waitForServerListening(server);
4117
+ await openBrowser({ transaction, authAction, silent, onProgress });
4118
+ const waitForCode = Promise.race([
4119
+ promise,
4120
+ new Promise((_resolve, rejectTimeout) => {
4121
+ timeoutTimer = setTimeout(() => {
4122
+ rejectTimeout(new OauthFlowTimeoutError(timeoutMs));
4123
+ }, timeoutMs);
4124
+ })
4125
+ ]);
4126
+ onProgress?.({ type: "callback_waiting" });
4127
+ return silent ? await waitForCode : await spinPromise(
4128
+ waitForCode,
4129
+ `Waiting for you to ${authAction} and authorize`
4130
+ );
4131
+ } finally {
4132
+ if (timeoutTimer) clearTimeout(timeoutTimer);
4133
+ process.off("SIGINT", cleanup);
4134
+ process.off("SIGTERM", cleanup);
4135
+ await closeServer({ server, connections, silent });
3868
4136
  }
3869
- return { clientId };
3870
4137
  }
3871
- function getBaseUrlFromResolvedCredentials(credentials2) {
3872
- if (credentials2 && zapierSdk.isCredentialsObject(credentials2)) {
3873
- return credentials2.baseUrl;
3874
- }
3875
- return void 0;
4138
+ async function waitForServerListening(server) {
4139
+ if (server.listening) return;
4140
+ await new Promise((resolve4, reject) => {
4141
+ const cleanup = () => {
4142
+ server.off("listening", handleListening);
4143
+ server.off("error", handleError);
4144
+ };
4145
+ const handleListening = () => {
4146
+ cleanup();
4147
+ resolve4();
4148
+ };
4149
+ const handleError = (error) => {
4150
+ cleanup();
4151
+ reject(error);
4152
+ };
4153
+ server.once("listening", handleListening);
4154
+ server.once("error", handleError);
4155
+ });
3876
4156
  }
3877
- function getBaseUrlFromOptionsCredentials(credentials2) {
3878
- if (credentials2 && typeof credentials2 === "object" && "baseUrl" in credentials2 && typeof credentials2.baseUrl === "string") {
3879
- return credentials2.baseUrl;
4157
+ async function openBrowser({
4158
+ transaction,
4159
+ authAction,
4160
+ silent,
4161
+ onProgress
4162
+ }) {
4163
+ if (!silent) {
4164
+ log_default.info(`Opening your browser to ${authAction}.`);
4165
+ log_default.info("If it doesn't open, visit:", transaction.browserAuthUrl);
4166
+ }
4167
+ onProgress?.({ type: "browser_opening", url: transaction.browserAuthUrl });
4168
+ try {
4169
+ await open__default.default(transaction.browserAuthUrl);
4170
+ onProgress?.({ type: "browser_opened", url: transaction.browserAuthUrl });
4171
+ } catch (err) {
4172
+ const reason = err instanceof Error ? err.message : String(err);
4173
+ if (!silent) {
4174
+ log_default.info(
4175
+ `Browser did not open automatically to ${authAction}: ${reason}`
4176
+ );
4177
+ log_default.info("Visit this URL manually:", transaction.browserAuthUrl);
4178
+ }
4179
+ onProgress?.({
4180
+ type: "browser_open_failed",
4181
+ url: transaction.browserAuthUrl,
4182
+ reason
4183
+ });
3880
4184
  }
3881
- return void 0;
3882
4185
  }
3883
- async function resolveCredentialsBaseUrl(context) {
3884
- const resolvedCredentials = "resolvedCredentials" in context ? context.resolvedCredentials : await context.resolveCredentials?.();
3885
- return getBaseUrlFromResolvedCredentials(resolvedCredentials) ?? getBaseUrlFromOptionsCredentials(context.options?.credentials) ?? context.options?.baseUrl;
4186
+ async function closeServer({
4187
+ server,
4188
+ connections,
4189
+ silent
4190
+ }) {
4191
+ await new Promise((resolve4) => {
4192
+ const timeout = setTimeout(() => {
4193
+ if (!silent)
4194
+ log_default.info("Server close timed out, forcing connection shutdown...");
4195
+ connections.forEach((conn) => conn.destroy());
4196
+ resolve4();
4197
+ }, 1e3);
4198
+ server.close(() => {
4199
+ clearTimeout(timeout);
4200
+ resolve4();
4201
+ });
4202
+ });
3886
4203
  }
3887
4204
 
3888
- // src/utils/non-interactive.ts
3889
- function resolveNonInteractive(options) {
3890
- return (options.nonInteractive ?? options.skipPrompts) === true || !process.stdin.isTTY || !process.stdout.isTTY;
4205
+ // src/utils/auth/oauth-errors.ts
4206
+ var SENSITIVE_OAUTH_FIELDS = [
4207
+ "access_token",
4208
+ "refresh_token",
4209
+ "id_token",
4210
+ "client_secret",
4211
+ "code_verifier",
4212
+ "code_challenge"
4213
+ ];
4214
+ function getErrorMessage(error) {
4215
+ return error instanceof Error ? error.message : String(error);
4216
+ }
4217
+ function toCamelCase(field) {
4218
+ return field.replace(
4219
+ /_([a-z])/g,
4220
+ (_match, letter) => letter.toUpperCase()
4221
+ );
4222
+ }
4223
+ function escapeRegExp(value) {
4224
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4225
+ }
4226
+ var sensitiveOauthFieldPattern = Array.from(
4227
+ new Set(
4228
+ SENSITIVE_OAUTH_FIELDS.flatMap((field) => [field, toCamelCase(field)])
4229
+ )
4230
+ ).map(escapeRegExp).join("|");
4231
+ var sensitiveQueryParamPattern = new RegExp(
4232
+ `([?&])(${sensitiveOauthFieldPattern})(=)[^&#\\s"'<>]*`,
4233
+ "gi"
4234
+ );
4235
+ function redactSensitiveOauthErrorMessage(message) {
4236
+ return message.replace(
4237
+ sensitiveQueryParamPattern,
4238
+ (_match, prefix, key, separator) => `${prefix}${key}${separator}[REDACTED]`
4239
+ ).replace(
4240
+ new RegExp(`"(${sensitiveOauthFieldPattern})"(\\s*:\\s*)"[^"]*"`, "g"),
4241
+ (_match, key, separator) => `"${key}"${separator}"[REDACTED]"`
4242
+ );
4243
+ }
4244
+ function toRedactedOauthError(error) {
4245
+ const message = redactSensitiveOauthErrorMessage(getErrorMessage(error));
4246
+ if (error instanceof ZapierCliValidationError) {
4247
+ return new ZapierCliValidationError(message);
4248
+ }
4249
+ if (error instanceof Error) {
4250
+ const redactedError = new Error(message);
4251
+ redactedError.name = error.name;
4252
+ return redactedError;
4253
+ }
4254
+ return new ZapierCliValidationError(message);
3891
4255
  }
3892
- var LoginSchema = zod.z.object({
3893
- timeout: zod.z.string().optional().describe("Login timeout in seconds (default: 300)"),
3894
- useApprovals: zod.z.boolean().optional().describe(
3895
- "Require approvals for actions performed with these credentials"
3896
- ),
3897
- nonInteractive: zod.z.boolean().optional().describe(
3898
- "Skip interactive prompts. Uses defaults where possible; errors instead of prompting when input is required. Useful in CI, piped output, or environments where TTY detection is unreliable."
3899
- ),
3900
- /** @deprecated Use `nonInteractive` instead. */
3901
- skipPrompts: zod.z.boolean().optional().meta({
3902
- deprecated: true,
3903
- deprecationMessage: "Use --non-interactive instead."
3904
- })
3905
- }).describe("Log in to Zapier to access your account");
3906
4256
 
3907
- // src/plugins/login/index.ts
4257
+ // src/utils/auth/account-auth.ts
4258
+ var LEGACY_JWT_UPGRADE_PROMPT = "We're upgrading your login to client credentials for a simpler, more reliable experience and to support future security controls. Older Zapier SDK/CLI versions on this machine may stop working after the upgrade. Continue?";
4259
+ var SIGNUP_RECOVERY_MESSAGE = "Restart `zapier-sdk signup` to generate a fresh signup URL and try again.";
4260
+ var HEADLESS_SIGNUP_RECOVERY_MESSAGE = "Restart `zapier-sdk signup --headless` to generate a fresh signup URL and try again.";
4261
+ function getEntryPointLabel(entryPoint) {
4262
+ return entryPoint === "signup" ? "Signup" : "Login";
4263
+ }
4264
+ function getActiveCredentialsAction(entryPoint) {
4265
+ return entryPoint === "signup" ? "continue signup" : "log in again";
4266
+ }
4267
+ function getCredentialsPromptMessage(entryPoint) {
4268
+ return entryPoint === "signup" ? "Enter a name to identify these credentials:" : "Enter a name to identify them:";
4269
+ }
4270
+ function getProfileMessage(entryPoint, email) {
4271
+ return entryPoint === "signup" ? `\u{1F464} Authenticated as ${email}` : `\u{1F464} Logged in as ${email}`;
4272
+ }
4273
+ function defaultCredentialsName(email) {
4274
+ return `${email}@${os.hostname()}`;
4275
+ }
4276
+ function validateCredentialsName(name) {
4277
+ const trimmedName = name.trim();
4278
+ if (!trimmedName) throw new ZapierCliValidationError("Name cannot be empty");
4279
+ return trimmedName;
4280
+ }
4281
+ async function promptCredentialsName({
4282
+ email,
4283
+ promptMessage
4284
+ }) {
4285
+ const { credentialName } = await inquirer__default.default.prompt([
4286
+ {
4287
+ type: "input",
4288
+ name: "credentialName",
4289
+ message: promptMessage,
4290
+ default: defaultCredentialsName(email),
4291
+ validate: (input) => {
4292
+ try {
4293
+ validateCredentialsName(input);
4294
+ return true;
4295
+ } catch (err) {
4296
+ return err instanceof Error ? err.message : String(err);
4297
+ }
4298
+ }
4299
+ }
4300
+ ]);
4301
+ return validateCredentialsName(credentialName);
4302
+ }
4303
+ function resolveDefaultCredentialsName({
4304
+ email
4305
+ }) {
4306
+ return validateCredentialsName(defaultCredentialsName(email));
4307
+ }
3908
4308
  function toPkceCredentials(credentials2) {
3909
4309
  if (credentials2 && zapierSdk.isCredentialsObject(credentials2) && !("clientSecret" in credentials2)) {
3910
4310
  return {
@@ -3916,104 +4316,125 @@ function toPkceCredentials(credentials2) {
3916
4316
  }
3917
4317
  return void 0;
3918
4318
  }
3919
- async function confirmRevokeAndRelogin(activeCredentials, nonInteractive) {
3920
- if (nonInteractive) {
4319
+ function parseTimeoutSeconds(timeout) {
4320
+ if (timeout === void 0) return 300;
4321
+ const timeoutSeconds = Number(timeout);
4322
+ if (!Number.isInteger(timeoutSeconds) || timeoutSeconds <= 0) {
3921
4323
  throw new ZapierCliValidationError(
3922
- `Already logged in as "${activeCredentials.name}". Run \`logout\` first or use an interactive terminal to re-authenticate.`
4324
+ "Timeout must be a positive integer (seconds)."
3923
4325
  );
3924
4326
  }
4327
+ return timeoutSeconds;
4328
+ }
4329
+ async function promptConfirm2({
4330
+ message,
4331
+ defaultValue
4332
+ }) {
3925
4333
  const { confirmed } = await inquirer__default.default.prompt([
3926
- {
3927
- type: "confirm",
3928
- name: "confirmed",
4334
+ { type: "confirm", name: "confirmed", message, default: defaultValue }
4335
+ ]);
4336
+ return confirmed;
4337
+ }
4338
+ function promptlessCredentialResetError(credentials2) {
4339
+ throw new ZapierCliValidationError(
4340
+ `Already logged in as "${credentials2.name}". Run \`logout\` first or use an interactive terminal to re-authenticate.`
4341
+ );
4342
+ }
4343
+ function promptlessLegacyJwtUpgradeError() {
4344
+ throw new ZapierCliValidationError(
4345
+ "Legacy JWT login detected. Run `logout` first or use an interactive terminal to migrate to client credentials."
4346
+ );
4347
+ }
4348
+ async function clearExistingAuthState({
4349
+ sdk,
4350
+ baseUrl: baseUrl2,
4351
+ interactive,
4352
+ entryPoint
4353
+ }) {
4354
+ const activeCredentials = getActiveCredentials({ baseUrl: baseUrl2 });
4355
+ const flowLabel = getEntryPointLabel(entryPoint);
4356
+ if (activeCredentials) {
4357
+ const confirmed = interactive ? await promptConfirm2({
4358
+ defaultValue: false,
3929
4359
  message: `You are already logged in as "${activeCredentials.name}".
3930
4360
  Logging out will delete these credentials and may interrupt other Zapier SDK or CLI sessions using them.
3931
- Log out and log in again?`,
3932
- default: false
4361
+ Log out and ${getActiveCredentialsAction(entryPoint)}?`
4362
+ }) : promptlessCredentialResetError(activeCredentials);
4363
+ if (!confirmed) {
4364
+ console.log(`${flowLabel} cancelled.`);
4365
+ return false;
3933
4366
  }
3934
- ]);
3935
- if (!confirmed) {
3936
- console.log("Login cancelled.");
3937
- return false;
3938
- }
3939
- return true;
3940
- }
3941
- async function confirmJwtMigration(nonInteractive) {
3942
- if (nonInteractive) {
3943
- throw new ZapierCliValidationError(
3944
- "Legacy JWT login detected. Run `logout` first or use an interactive terminal to migrate to client credentials."
3945
- );
3946
- }
3947
- const { confirmed } = await inquirer__default.default.prompt([
3948
- {
3949
- type: "confirm",
3950
- name: "confirmed",
3951
- message: "We're upgrading your login to client credentials for a simpler, more reliable experience and to support future security controls. Older Zapier SDK/CLI versions on this machine may stop working after the upgrade. Continue?",
3952
- default: true
4367
+ try {
4368
+ await revokeCredentials({
4369
+ api: sdk.context.api,
4370
+ credentials: activeCredentials
4371
+ });
4372
+ } catch {
4373
+ if (!interactive) {
4374
+ throw new ZapierCliValidationError(
4375
+ `${flowLabel} cleanup failed and cannot be reset without confirmation. Re-run with an interactive terminal.`
4376
+ );
4377
+ }
4378
+ const reset = await promptConfirm2({
4379
+ defaultValue: false,
4380
+ message: `${flowLabel} cleanup failed. Reset local session state and continue?`
4381
+ });
4382
+ if (!reset) {
4383
+ console.log(`${flowLabel} cancelled.`);
4384
+ return false;
4385
+ }
4386
+ await deleteStoredClientCredentials({
4387
+ name: activeCredentials.name,
4388
+ baseUrl: activeCredentials.baseUrl
4389
+ });
3953
4390
  }
3954
- ]);
3955
- if (!confirmed) {
3956
- console.log("Login cancelled.");
3957
- return false;
3958
- }
3959
- return true;
3960
- }
3961
- async function confirmLocalLoginReset(nonInteractive) {
3962
- if (nonInteractive) {
3963
- throw new ZapierCliValidationError(
3964
- "Login cleanup failed and cannot be reset without confirmation. Re-run with an interactive terminal."
3965
- );
3966
- }
3967
- const { confirmed } = await inquirer__default.default.prompt([
3968
- {
3969
- type: "confirm",
3970
- name: "confirmed",
3971
- message: "Login cleanup failed. Reset local session state and continue?",
3972
- default: false
4391
+ } else if (hasLegacyJwtConfig()) {
4392
+ const confirmed = interactive ? await promptConfirm2({
4393
+ defaultValue: true,
4394
+ message: LEGACY_JWT_UPGRADE_PROMPT
4395
+ }) : promptlessLegacyJwtUpgradeError();
4396
+ if (!confirmed) {
4397
+ console.log(`${flowLabel} cancelled.`);
4398
+ return false;
3973
4399
  }
3974
- ]);
3975
- if (!confirmed) {
3976
- console.log("Login cancelled.");
3977
- return false;
3978
4400
  }
3979
4401
  return true;
3980
4402
  }
3981
- function parseTimeoutSeconds(timeout) {
3982
- const timeoutSeconds = timeout ? parseInt(timeout, 10) : 300;
3983
- if (isNaN(timeoutSeconds) || timeoutSeconds <= 0) {
3984
- throw new Error("Timeout must be a positive number");
3985
- }
3986
- return timeoutSeconds;
4403
+ async function getProfile(api2) {
4404
+ return api2.get("/zapier/api/v4/profile/", {
4405
+ authRequired: true
4406
+ });
3987
4407
  }
3988
- async function promptCredentialsName(email, nonInteractive) {
3989
- const fallback = `${email}@${os.hostname()}`;
3990
- if (nonInteractive) {
3991
- return fallback;
4408
+ async function saveClientCredentials({
4409
+ api: api2,
4410
+ name,
4411
+ credentialsBaseUrl: credentialsBaseUrl2,
4412
+ useApprovals,
4413
+ cleanupLogPrefix
4414
+ }) {
4415
+ await setupClientCredentials({
4416
+ api: api2,
4417
+ name,
4418
+ credentialsBaseUrl: credentialsBaseUrl2,
4419
+ ...useApprovals && { policy: EMPTY_POLICY }
4420
+ });
4421
+ try {
4422
+ await clearLegacyJwtState();
4423
+ } catch (err) {
4424
+ console.error(
4425
+ `[${cleanupLogPrefix}] Best-effort legacy JWT cleanup failed:`,
4426
+ err
4427
+ );
3992
4428
  }
3993
- const { credentialName } = await inquirer__default.default.prompt([
3994
- {
3995
- type: "input",
3996
- name: "credentialName",
3997
- message: "Enter a name to identify them:",
3998
- default: fallback,
3999
- validate: (input) => {
4000
- if (!input.trim()) return "Name cannot be empty";
4001
- return true;
4002
- }
4003
- }
4004
- ]);
4005
- return credentialName;
4006
4429
  }
4007
- function emitLoginSuccess({
4430
+ function emitAccountAuthSuccess({
4008
4431
  sdk,
4009
4432
  profile
4010
4433
  }) {
4011
4434
  sdk.context.eventEmission.emit(
4012
4435
  "platform.sdk.ApplicationLifecycleEvent",
4013
4436
  zapierSdk.buildApplicationLifecycleEvent(
4014
- {
4015
- lifecycle_event_type: "login_success"
4016
- },
4437
+ { lifecycle_event_type: "login_success" },
4017
4438
  {
4018
4439
  customuser_id: profile.user_id,
4019
4440
  account_id: profile.roles[0]?.account_id ?? null
@@ -4021,18 +4442,128 @@ function emitLoginSuccess({
4021
4442
  )
4022
4443
  );
4023
4444
  }
4024
- async function getProfile(api2) {
4025
- return api2.get("/zapier/api/v4/profile/", {
4026
- authRequired: true
4027
- });
4445
+ function emitSignupSuccess({
4446
+ sdk
4447
+ }) {
4448
+ sdk.context.eventEmission.emit(
4449
+ "platform.sdk.ApplicationLifecycleEvent",
4450
+ zapierSdk.buildApplicationLifecycleEvent({ lifecycle_event_type: "signup_success" })
4451
+ );
4028
4452
  }
4029
- async function bestEffortClearLegacyJwtState() {
4453
+ async function runOauthWithRedaction(runOauth) {
4030
4454
  try {
4031
- await clearLegacyJwtState();
4032
- } catch (err) {
4033
- console.error("[login] Best-effort legacy JWT cleanup failed:", err);
4455
+ return await runOauth();
4456
+ } catch (error) {
4457
+ if (error instanceof ZapierCliUserCancellationError) throw error;
4458
+ throw toRedactedOauthError(error);
4459
+ }
4460
+ }
4461
+ async function runOauthForEntryPoint({
4462
+ sdk,
4463
+ entryPoint,
4464
+ timeoutMs,
4465
+ pkceCredentials,
4466
+ baseUrl: baseUrl2,
4467
+ headless,
4468
+ interactive
4469
+ }) {
4470
+ if (entryPoint === "signup") {
4471
+ return runOauthWithRedaction(
4472
+ () => runSignupOauthFlow({
4473
+ timeoutMs,
4474
+ pkceCredentials,
4475
+ baseUrl: baseUrl2,
4476
+ headless,
4477
+ interactive,
4478
+ recoveryMessage: headless ? HEADLESS_SIGNUP_RECOVERY_MESSAGE : SIGNUP_RECOVERY_MESSAGE,
4479
+ onProgress: (event) => {
4480
+ if (event.type === "callback_accepted") {
4481
+ emitSignupSuccess({ sdk });
4482
+ }
4483
+ }
4484
+ })
4485
+ );
4034
4486
  }
4487
+ return runOauthWithRedaction(
4488
+ () => runLoginOauthFlow({ timeoutMs, pkceCredentials, baseUrl: baseUrl2 })
4489
+ );
4490
+ }
4491
+ async function runAccountAuth({
4492
+ sdk,
4493
+ options,
4494
+ entryPoint
4495
+ }) {
4496
+ const timeoutSeconds = parseTimeoutSeconds(options.timeout);
4497
+ const interactive = !resolveNonInteractive(options);
4498
+ const resolvedCredentials = await sdk.context.resolveCredentials();
4499
+ const pkceCredentials = toPkceCredentials(resolvedCredentials);
4500
+ const credentialsBaseUrl2 = await resolveCredentialsBaseUrl({
4501
+ ...sdk.context,
4502
+ resolvedCredentials
4503
+ });
4504
+ if (!await clearExistingAuthState({
4505
+ sdk,
4506
+ baseUrl: credentialsBaseUrl2,
4507
+ interactive,
4508
+ entryPoint
4509
+ })) {
4510
+ return;
4511
+ }
4512
+ const { accessToken } = await runOauthForEntryPoint({
4513
+ sdk,
4514
+ entryPoint,
4515
+ timeoutMs: timeoutSeconds * 1e3,
4516
+ pkceCredentials,
4517
+ baseUrl: credentialsBaseUrl2,
4518
+ headless: options.headless === true,
4519
+ interactive
4520
+ });
4521
+ const scopedApi = zapierSdk.getOrCreateApiClient({
4522
+ credentials: accessToken,
4523
+ baseUrl: credentialsBaseUrl2
4524
+ });
4525
+ const profile = await getProfile(scopedApi);
4526
+ console.log(getProfileMessage(entryPoint, profile.email));
4527
+ console.log(
4528
+ "\nGenerating credentials so this machine can make authenticated requests on your behalf."
4529
+ );
4530
+ const resolveCredentialsName = interactive ? ({ email }) => promptCredentialsName({
4531
+ email,
4532
+ promptMessage: getCredentialsPromptMessage(entryPoint)
4533
+ }) : resolveDefaultCredentialsName;
4534
+ const credentialName = await resolveCredentialsName({ email: profile.email });
4535
+ const useApprovals = options.useApprovals === true;
4536
+ await saveClientCredentials({
4537
+ api: scopedApi,
4538
+ name: credentialName,
4539
+ credentialsBaseUrl: credentialsBaseUrl2,
4540
+ useApprovals,
4541
+ cleanupLogPrefix: entryPoint
4542
+ });
4543
+ console.log(
4544
+ `\u2705 Credentials "${credentialName}" created and set as default. You are ready to use the Zapier SDK.`
4545
+ );
4546
+ if (useApprovals) {
4547
+ console.log("\u{1F510} Approvals are enabled for these credentials.");
4548
+ }
4549
+ emitAccountAuthSuccess({ sdk, profile });
4035
4550
  }
4551
+ var LoginSchema = zod.z.object({
4552
+ timeout: zod.z.string().optional().describe("Login timeout in seconds (default: 300)"),
4553
+ useApprovals: zod.z.boolean().optional().describe(
4554
+ "Require approvals for actions performed with these credentials"
4555
+ ),
4556
+ nonInteractive: zod.z.boolean().optional().describe(
4557
+ "Skip interactive prompts. Uses defaults where possible; errors instead of prompting when input is required. Useful in CI, piped output, or environments where TTY detection is unreliable."
4558
+ ),
4559
+ /** @deprecated Use `nonInteractive` instead. */
4560
+ skipPrompts: zod.z.boolean().optional().meta({
4561
+ deprecated: true,
4562
+ deprecationMessage: "Use --non-interactive instead."
4563
+ })
4564
+ }).describe("Log in to Zapier to access your account");
4565
+
4566
+ // src/plugins/login/index.ts
4036
4567
  var loginPlugin = zapierSdk.definePlugin(
4037
4568
  (sdk) => zapierSdk.createPluginMethod(sdk, {
4038
4569
  name: "login",
@@ -4040,68 +4571,37 @@ var loginPlugin = zapierSdk.definePlugin(
4040
4571
  inputSchema: LoginSchema,
4041
4572
  supportsJsonOutput: false,
4042
4573
  handler: async ({ sdk: sdk2, options }) => {
4043
- const timeoutSeconds = parseTimeoutSeconds(options.timeout);
4044
- const nonInteractive = resolveNonInteractive(options);
4045
- const resolvedCredentials = await sdk2.context.resolveCredentials();
4046
- const pkceCredentials = toPkceCredentials(resolvedCredentials);
4047
- const credentialsBaseUrl2 = await resolveCredentialsBaseUrl({
4048
- ...sdk2.context,
4049
- resolvedCredentials
4050
- });
4051
- const activeCredentials = getActiveCredentials({
4052
- baseUrl: credentialsBaseUrl2
4053
- });
4054
- if (activeCredentials) {
4055
- if (!await confirmRevokeAndRelogin(activeCredentials, nonInteractive))
4056
- return;
4057
- try {
4058
- await revokeCredentials({
4059
- api: sdk2.context.api,
4060
- credentials: activeCredentials
4061
- });
4062
- } catch {
4063
- if (!await confirmLocalLoginReset(nonInteractive)) return;
4064
- await deleteStoredClientCredentials({
4065
- name: activeCredentials.name,
4066
- baseUrl: activeCredentials.baseUrl
4067
- });
4068
- }
4069
- } else if (hasLegacyJwtConfig()) {
4070
- if (!await confirmJwtMigration(nonInteractive)) return;
4071
- }
4072
- const { accessToken } = await runOauthFlow({
4073
- timeoutMs: timeoutSeconds * 1e3,
4074
- pkceCredentials,
4075
- baseUrl: credentialsBaseUrl2
4076
- });
4077
- const scopedApi = zapierSdk.getOrCreateApiClient({
4078
- credentials: accessToken,
4079
- baseUrl: credentialsBaseUrl2
4080
- });
4081
- const profile = await getProfile(scopedApi);
4082
- console.log(`\u{1F464} Logged in as ${profile.email}`);
4083
- console.log(
4084
- "\nGenerating credentials so this machine can make authenticated requests on your behalf."
4085
- );
4086
- const credentialName = await promptCredentialsName(
4087
- profile.email,
4088
- nonInteractive
4089
- );
4090
- const useApprovals = options.useApprovals === true;
4091
- await setupClientCredentials({
4092
- api: scopedApi,
4093
- name: credentialName,
4094
- credentialsBaseUrl: credentialsBaseUrl2,
4095
- ...useApprovals && { policy: EMPTY_POLICY }
4096
- });
4097
- await bestEffortClearLegacyJwtState();
4098
- console.log(
4099
- `\u2705 Credentials "${credentialName}" created and set as default. You are ready to use the Zapier SDK.`
4100
- );
4101
- if (useApprovals) {
4102
- console.log("\u{1F510} Approvals are enabled for these credentials.");
4103
- }
4104
- emitLoginSuccess({ sdk: sdk2, profile });
4574
+ await runAccountAuth({ sdk: sdk2, options, entryPoint: "login" });
4575
+ }
4576
+ })
4577
+ );
4578
+ var SignupSchema = zod.z.object({
4579
+ timeout: zod.z.string().optional().describe("Signup timeout in seconds (default: 300)"),
4580
+ useApprovals: zod.z.boolean().optional().describe(
4581
+ "Require approvals for actions performed with these credentials"
4582
+ ),
4583
+ nonInteractive: zod.z.boolean().optional().describe(
4584
+ "Skip interactive prompts. Uses defaults where possible; errors instead of prompting when input is required. Useful in CI, piped output, or environments where TTY detection is unreliable."
4585
+ ),
4586
+ /** @deprecated Use `nonInteractive` instead. */
4587
+ skipPrompts: zod.z.boolean().optional().meta({
4588
+ deprecated: true,
4589
+ deprecationMessage: "Use --non-interactive instead."
4590
+ }),
4591
+ headless: zod.z.boolean().optional().describe(
4592
+ "Use when signing up from a machine that has no browser. Prints a signup link to open elsewhere, then accepts the pasted loopback callback URL."
4593
+ )
4594
+ }).describe("Set up Zapier account access and SDK credentials");
4595
+
4596
+ // src/plugins/signup/index.ts
4597
+ var signupPlugin = zapierSdk.definePlugin(
4598
+ (sdk) => zapierSdk.createPluginMethod(sdk, {
4599
+ name: "signup",
4600
+ categories: ["account"],
4601
+ inputSchema: SignupSchema,
4602
+ supportsJsonOutput: false,
4603
+ handler: async ({ sdk: sdk2, options }) => {
4604
+ await runAccountAuth({ sdk: sdk2, options, entryPoint: "signup" });
4105
4605
  }
4106
4606
  })
4107
4607
  );
@@ -4168,7 +4668,8 @@ var BundleCodeSchema = zod.z.object({
4168
4668
  var bundleCodePlugin = zapierSdk.definePlugin(
4169
4669
  (sdk) => zapierSdk.createPluginMethod(sdk, {
4170
4670
  name: "bundleCode",
4171
- categories: ["utility", "deprecated"],
4671
+ categories: ["utility"],
4672
+ deprecation: { message: "bundleCode is no longer maintained." },
4172
4673
  inputSchema: BundleCodeSchema,
4173
4674
  handler: async ({ options }) => bundleCode(options)
4174
4675
  })
@@ -4264,7 +4765,7 @@ async function detectTypesOutputDirectory() {
4264
4765
  }
4265
4766
  return "./zapier/apps/";
4266
4767
  }
4267
- var addPlugin = zapierSdk.definePlugin(
4768
+ var addAppsPlugin = zapierSdk.definePlugin(
4268
4769
  (sdk) => zapierSdk.createPluginMethod(sdk, {
4269
4770
  name: "add",
4270
4771
  categories: ["utility"],
@@ -5669,10 +6170,6 @@ var cliOverridesPlugin = zapierSdk.definePlugin(
5669
6170
  if (sdk.context.meta.fetch) {
5670
6171
  meta.fetch = {
5671
6172
  ...sdk.context.meta.fetch,
5672
- categories: [
5673
- ...sdk.context.meta.fetch.categories || [],
5674
- "deprecated"
5675
- ],
5676
6173
  deprecation: {
5677
6174
  message: "This command is deprecated and will be removed soon. Use `curl` instead. Learn more: https://docs.zapier.com/sdk/cli-reference#curl"
5678
6175
  }
@@ -6653,7 +7150,7 @@ var watchTriggerInboxCliPlugin = zapierSdk.definePlugin(
6653
7150
  // package.json with { type: 'json' }
6654
7151
  var package_default2 = {
6655
7152
  name: "@zapier/zapier-sdk-cli",
6656
- version: "0.52.10"};
7153
+ version: "0.53.0"};
6657
7154
 
6658
7155
  // src/sdk.ts
6659
7156
  zapierSdk.injectCliLogin(login_exports);
@@ -6662,21 +7159,21 @@ function createZapierCliSdk(options = {}) {
6662
7159
  const extensionsContextPlugin = () => ({
6663
7160
  context: { extensions }
6664
7161
  });
6665
- let chain = zapierSdk.createZapierSdk({
7162
+ const sdk = zapierSdk.createZapierSdkStack({
6666
7163
  ...sdkOptions,
6667
7164
  eventEmission: { ...sdkOptions.eventEmission, callContext: "cli" },
6668
7165
  callerPackage: { name: package_default2.name, version: package_default2.version }
6669
- }).addPlugin(extensionsContextPlugin).addPlugin(generateAppTypesPlugin).addPlugin(buildManifestPlugin).addPlugin(bundleCodePlugin).addPlugin(getLoginConfigPathPlugin).addPlugin(addPlugin).addPlugin(feedbackPlugin).addPlugin(curlPlugin).addPlugin(initPlugin).addPlugin(mcpPlugin).addPlugin(loginPlugin).addPlugin(logoutPlugin).addPlugin(cliOverridesPlugin);
7166
+ }).use(extensionsContextPlugin).use(generateAppTypesPlugin).use(buildManifestPlugin).use(bundleCodePlugin).use(getLoginConfigPathPlugin).use(addAppsPlugin).use(feedbackPlugin).use(curlPlugin).use(initPlugin).use(mcpPlugin).use(loginPlugin).use(signupPlugin).use(logoutPlugin).use(cliOverridesPlugin, { override: true }).toSdk();
6670
7167
  for (const ext of extensions) {
6671
7168
  try {
6672
- chain = chain.addPlugin(ext);
7169
+ zapierSdk.addPlugin(sdk, ext);
6673
7170
  } catch (err) {
6674
7171
  console.warn(
6675
7172
  `Extension plugin failed to construct: ${err.message}; skipping.`
6676
7173
  );
6677
7174
  }
6678
7175
  }
6679
- return chain;
7176
+ return sdk;
6680
7177
  }
6681
7178
  experimental.injectCliLogin(login_exports);
6682
7179
  function createZapierCliSdk2(options = {}) {
@@ -6687,21 +7184,21 @@ function createZapierCliSdk2(options = {}) {
6687
7184
  const experimentalContextPlugin = () => ({
6688
7185
  context: { experimental: true }
6689
7186
  });
6690
- let chain = experimental.createZapierSdk({
7187
+ const sdk = experimental.createZapierSdkStack({
6691
7188
  ...sdkOptions,
6692
7189
  eventEmission: { ...sdkOptions.eventEmission, callContext: "cli" },
6693
7190
  callerPackage: { name: package_default2.name, version: package_default2.version }
6694
- }).addPlugin(extensionsContextPlugin).addPlugin(experimentalContextPlugin).addPlugin(generateAppTypesPlugin).addPlugin(buildManifestPlugin).addPlugin(bundleCodePlugin).addPlugin(getLoginConfigPathPlugin).addPlugin(addPlugin).addPlugin(feedbackPlugin).addPlugin(curlPlugin).addPlugin(initPlugin).addPlugin(drainTriggerInboxCliPlugin, { override: true }).addPlugin(watchTriggerInboxCliPlugin, { override: true }).addPlugin(mcpPlugin).addPlugin(loginPlugin).addPlugin(logoutPlugin).addPlugin(cliOverridesPlugin);
7191
+ }).use(extensionsContextPlugin).use(experimentalContextPlugin).use(generateAppTypesPlugin).use(buildManifestPlugin).use(bundleCodePlugin).use(getLoginConfigPathPlugin).use(addAppsPlugin).use(feedbackPlugin).use(curlPlugin).use(initPlugin).use(drainTriggerInboxCliPlugin, { override: true }).use(watchTriggerInboxCliPlugin, { override: true }).use(mcpPlugin).use(loginPlugin).use(signupPlugin).use(logoutPlugin).use(cliOverridesPlugin, { override: true }).toSdk();
6695
7192
  for (const ext of extensions) {
6696
7193
  try {
6697
- chain = chain.addPlugin(ext);
7194
+ experimental.addPlugin(sdk, ext);
6698
7195
  } catch (err) {
6699
7196
  console.warn(
6700
7197
  `Extension plugin failed to construct: ${err.message}; skipping.`
6701
7198
  );
6702
7199
  }
6703
7200
  }
6704
- return chain;
7201
+ return sdk;
6705
7202
  }
6706
7203
 
6707
7204
  // src/utils/extensions.ts
@@ -6835,7 +7332,9 @@ async function checkForUpdates({
6835
7332
  currentVersion
6836
7333
  );
6837
7334
  } catch (error) {
6838
- log_default.debug(`Failed to check deprecation for current version: ${error}`);
7335
+ if (!(error instanceof packageJsonLib.VersionNotFoundError)) {
7336
+ log_default.debug(`Failed to check deprecation for current version: ${error}`);
7337
+ }
6839
7338
  currentPackageInfo = latestPackageInfo;
6840
7339
  }
6841
7340
  const isDeprecated = Boolean(currentPackageInfo.deprecated);