@zapier/zapier-sdk-cli 0.59.0 → 0.59.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/cli.cjs +2 -2
  3. package/dist/cli.mjs +2 -2
  4. package/dist/experimental.cjs +1 -1
  5. package/dist/experimental.mjs +1 -1
  6. package/dist/index.cjs +2 -2
  7. package/dist/index.mjs +2 -2
  8. package/package.json +4 -4
  9. package/dist/package.json +0 -121
  10. package/dist/src/cli.d.ts +0 -2
  11. package/dist/src/cli.js +0 -219
  12. package/dist/src/experimental.d.ts +0 -33
  13. package/dist/src/experimental.js +0 -86
  14. package/dist/src/generators/ast-generator.d.ts +0 -41
  15. package/dist/src/generators/ast-generator.js +0 -405
  16. package/dist/src/index.d.ts +0 -5
  17. package/dist/src/index.js +0 -5
  18. package/dist/src/login/config.d.ts +0 -4
  19. package/dist/src/login/config.js +0 -21
  20. package/dist/src/login/credentials-revoke.d.ts +0 -14
  21. package/dist/src/login/credentials-revoke.js +0 -95
  22. package/dist/src/login/credentials-store.d.ts +0 -60
  23. package/dist/src/login/credentials-store.js +0 -181
  24. package/dist/src/login/filesystem-cache.d.ts +0 -25
  25. package/dist/src/login/filesystem-cache.js +0 -195
  26. package/dist/src/login/index.d.ts +0 -110
  27. package/dist/src/login/index.js +0 -424
  28. package/dist/src/login/keychain.d.ts +0 -18
  29. package/dist/src/login/keychain.js +0 -74
  30. package/dist/src/login/legacy-jwt.d.ts +0 -4
  31. package/dist/src/login/legacy-jwt.js +0 -18
  32. package/dist/src/login.d.ts +0 -10
  33. package/dist/src/login.js +0 -10
  34. package/dist/src/paths.d.ts +0 -1
  35. package/dist/src/paths.js +0 -6
  36. package/dist/src/plugins/add/index.d.ts +0 -254
  37. package/dist/src/plugins/add/index.js +0 -95
  38. package/dist/src/plugins/add/schemas.d.ts +0 -8
  39. package/dist/src/plugins/add/schemas.js +0 -22
  40. package/dist/src/plugins/auth/credentials-base-url.d.ts +0 -11
  41. package/dist/src/plugins/auth/credentials-base-url.js +0 -24
  42. package/dist/src/plugins/buildManifest/index.d.ts +0 -120
  43. package/dist/src/plugins/buildManifest/index.js +0 -71
  44. package/dist/src/plugins/buildManifest/schemas.d.ts +0 -44
  45. package/dist/src/plugins/buildManifest/schemas.js +0 -17
  46. package/dist/src/plugins/bundleCode/index.d.ts +0 -23
  47. package/dist/src/plugins/bundleCode/index.js +0 -62
  48. package/dist/src/plugins/bundleCode/schemas.d.ts +0 -10
  49. package/dist/src/plugins/bundleCode/schemas.js +0 -19
  50. package/dist/src/plugins/cliOverrides/index.d.ts +0 -21
  51. package/dist/src/plugins/cliOverrides/index.js +0 -17
  52. package/dist/src/plugins/curl/index.d.ts +0 -76
  53. package/dist/src/plugins/curl/index.js +0 -236
  54. package/dist/src/plugins/curl/schemas.d.ts +0 -40
  55. package/dist/src/plugins/curl/schemas.js +0 -108
  56. package/dist/src/plugins/curl/utils.d.ts +0 -34
  57. package/dist/src/plugins/curl/utils.js +0 -150
  58. package/dist/src/plugins/drainTriggerInbox/index.d.ts +0 -46
  59. package/dist/src/plugins/drainTriggerInbox/index.js +0 -178
  60. package/dist/src/plugins/feedback/index.d.ts +0 -24
  61. package/dist/src/plugins/feedback/index.js +0 -52
  62. package/dist/src/plugins/feedback/schemas.d.ts +0 -5
  63. package/dist/src/plugins/feedback/schemas.js +0 -8
  64. package/dist/src/plugins/generateAppTypes/index.d.ts +0 -265
  65. package/dist/src/plugins/generateAppTypes/index.js +0 -129
  66. package/dist/src/plugins/generateAppTypes/schemas.d.ts +0 -58
  67. package/dist/src/plugins/generateAppTypes/schemas.js +0 -21
  68. package/dist/src/plugins/getLoginConfigPath/index.d.ts +0 -16
  69. package/dist/src/plugins/getLoginConfigPath/index.js +0 -9
  70. package/dist/src/plugins/getLoginConfigPath/schemas.d.ts +0 -3
  71. package/dist/src/plugins/getLoginConfigPath/schemas.js +0 -5
  72. package/dist/src/plugins/index.d.ts +0 -15
  73. package/dist/src/plugins/index.js +0 -15
  74. package/dist/src/plugins/init/display.d.ts +0 -9
  75. package/dist/src/plugins/init/display.js +0 -72
  76. package/dist/src/plugins/init/index.d.ts +0 -21
  77. package/dist/src/plugins/init/index.js +0 -56
  78. package/dist/src/plugins/init/schemas.d.ts +0 -9
  79. package/dist/src/plugins/init/schemas.js +0 -19
  80. package/dist/src/plugins/init/steps.d.ts +0 -39
  81. package/dist/src/plugins/init/steps.js +0 -141
  82. package/dist/src/plugins/init/types.d.ts +0 -31
  83. package/dist/src/plugins/init/types.js +0 -1
  84. package/dist/src/plugins/init/utils.d.ts +0 -48
  85. package/dist/src/plugins/init/utils.js +0 -135
  86. package/dist/src/plugins/login/index.d.ts +0 -25
  87. package/dist/src/plugins/login/index.js +0 -12
  88. package/dist/src/plugins/login/schemas.d.ts +0 -9
  89. package/dist/src/plugins/login/schemas.js +0 -27
  90. package/dist/src/plugins/logout/index.d.ts +0 -30
  91. package/dist/src/plugins/logout/index.js +0 -33
  92. package/dist/src/plugins/logout/schemas.d.ts +0 -2
  93. package/dist/src/plugins/logout/schemas.js +0 -4
  94. package/dist/src/plugins/mcp/index.d.ts +0 -28
  95. package/dist/src/plugins/mcp/index.js +0 -24
  96. package/dist/src/plugins/mcp/schemas.d.ts +0 -5
  97. package/dist/src/plugins/mcp/schemas.js +0 -10
  98. package/dist/src/plugins/signup/index.d.ts +0 -25
  99. package/dist/src/plugins/signup/index.js +0 -12
  100. package/dist/src/plugins/signup/schemas.d.ts +0 -9
  101. package/dist/src/plugins/signup/schemas.js +0 -26
  102. package/dist/src/plugins/signup/test-harness.d.ts +0 -34
  103. package/dist/src/plugins/signup/test-harness.js +0 -76
  104. package/dist/src/plugins/watchTriggerInbox/index.d.ts +0 -46
  105. package/dist/src/plugins/watchTriggerInbox/index.js +0 -166
  106. package/dist/src/sdk.d.ts +0 -17
  107. package/dist/src/sdk.js +0 -67
  108. package/dist/src/telemetry/builders.d.ts +0 -44
  109. package/dist/src/telemetry/builders.js +0 -59
  110. package/dist/src/telemetry/events.d.ts +0 -40
  111. package/dist/src/telemetry/events.js +0 -4
  112. package/dist/src/types/sdk.d.ts +0 -6
  113. package/dist/src/types/sdk.js +0 -1
  114. package/dist/src/utils/api/client.d.ts +0 -15
  115. package/dist/src/utils/api/client.js +0 -27
  116. package/dist/src/utils/approval-errors.d.ts +0 -1
  117. package/dist/src/utils/approval-errors.js +0 -9
  118. package/dist/src/utils/approval-progress.d.ts +0 -12
  119. package/dist/src/utils/approval-progress.js +0 -179
  120. package/dist/src/utils/auth/account-auth.d.ts +0 -33
  121. package/dist/src/utils/auth/account-auth.js +0 -302
  122. package/dist/src/utils/auth/client-credentials.d.ts +0 -26
  123. package/dist/src/utils/auth/client-credentials.js +0 -67
  124. package/dist/src/utils/auth/oauth-callback.d.ts +0 -6
  125. package/dist/src/utils/auth/oauth-callback.js +0 -28
  126. package/dist/src/utils/auth/oauth-errors.d.ts +0 -2
  127. package/dist/src/utils/auth/oauth-errors.js +0 -39
  128. package/dist/src/utils/auth/oauth-flow.d.ts +0 -37
  129. package/dist/src/utils/auth/oauth-flow.js +0 -313
  130. package/dist/src/utils/auth/oauth-transaction.d.ts +0 -35
  131. package/dist/src/utils/auth/oauth-transaction.js +0 -69
  132. package/dist/src/utils/cli-generator-utils.d.ts +0 -14
  133. package/dist/src/utils/cli-generator-utils.js +0 -122
  134. package/dist/src/utils/cli-generator.d.ts +0 -4
  135. package/dist/src/utils/cli-generator.js +0 -831
  136. package/dist/src/utils/cli-options.d.ts +0 -16
  137. package/dist/src/utils/cli-options.js +0 -34
  138. package/dist/src/utils/cli-renderer.d.ts +0 -53
  139. package/dist/src/utils/cli-renderer.js +0 -265
  140. package/dist/src/utils/constants.d.ts +0 -3
  141. package/dist/src/utils/constants.js +0 -5
  142. package/dist/src/utils/directory-detection.d.ts +0 -5
  143. package/dist/src/utils/directory-detection.js +0 -21
  144. package/dist/src/utils/errors.d.ts +0 -33
  145. package/dist/src/utils/errors.js +0 -36
  146. package/dist/src/utils/extensions.d.ts +0 -20
  147. package/dist/src/utils/extensions.js +0 -66
  148. package/dist/src/utils/getCallablePromise.d.ts +0 -6
  149. package/dist/src/utils/getCallablePromise.js +0 -14
  150. package/dist/src/utils/log.d.ts +0 -8
  151. package/dist/src/utils/log.js +0 -26
  152. package/dist/src/utils/manifest-helpers.d.ts +0 -10
  153. package/dist/src/utils/manifest-helpers.js +0 -19
  154. package/dist/src/utils/non-interactive.d.ts +0 -14
  155. package/dist/src/utils/non-interactive.js +0 -15
  156. package/dist/src/utils/package-manager-detector.d.ts +0 -18
  157. package/dist/src/utils/package-manager-detector.js +0 -72
  158. package/dist/src/utils/parameter-resolver.d.ts +0 -179
  159. package/dist/src/utils/parameter-resolver.js +0 -1554
  160. package/dist/src/utils/retry.d.ts +0 -6
  161. package/dist/src/utils/retry.js +0 -21
  162. package/dist/src/utils/schema-formatter.d.ts +0 -11
  163. package/dist/src/utils/schema-formatter.js +0 -131
  164. package/dist/src/utils/serializeAsync.d.ts +0 -2
  165. package/dist/src/utils/serializeAsync.js +0 -16
  166. package/dist/src/utils/spinner.d.ts +0 -1
  167. package/dist/src/utils/spinner.js +0 -21
  168. package/dist/src/utils/string-utils.d.ts +0 -1
  169. package/dist/src/utils/string-utils.js +0 -6
  170. package/dist/src/utils/triggerDrain.d.ts +0 -144
  171. package/dist/src/utils/triggerDrain.js +0 -351
  172. package/dist/src/utils/version-checker.d.ts +0 -17
  173. package/dist/src/utils/version-checker.js +0 -154
  174. package/dist/tsconfig.tsbuildinfo +0 -1
@@ -1,40 +0,0 @@
1
- /**
2
- * CLI-specific telemetry event definitions
3
- */
4
- import type { BaseEvent } from "@zapier/zapier-sdk";
5
- /**
6
- * Event emitted when a CLI command is executed
7
- */
8
- export interface CliCommandExecutedEvent extends BaseEvent {
9
- system_name: string;
10
- session_id?: string | null;
11
- cli_version?: string | null;
12
- cli_arguments?: (string | null)[] | null;
13
- cli_primary_command?: string | null;
14
- os_platform?: string | null;
15
- os_release?: string | null;
16
- os_architecture?: string | null;
17
- platform_versions?: Record<string, string | null> | null;
18
- selected_api?: string | null;
19
- app_id?: number | null;
20
- app_version_id?: number | null;
21
- execution_duration_ms?: number | null;
22
- success_flag: boolean;
23
- exit_code?: number | null;
24
- error_message?: string | null;
25
- command_category?: string | null;
26
- requires_auth?: boolean | null;
27
- is_ci_environment?: boolean | null;
28
- ci_platform?: string | null;
29
- package_manager?: string | null;
30
- made_network_requests?: boolean | null;
31
- files_modified_count?: number | null;
32
- files_created_count?: number | null;
33
- files_processed_size_bytes?: number | null;
34
- peak_memory_usage_bytes?: number | null;
35
- cpu_time_ms?: number | null;
36
- subprocess_count?: number | null;
37
- stdin_is_tty?: boolean | null;
38
- stdout_is_tty?: boolean | null;
39
- agent?: string | null;
40
- }
@@ -1,4 +0,0 @@
1
- /**
2
- * CLI-specific telemetry event definitions
3
- */
4
- export {};
@@ -1,6 +0,0 @@
1
- import type { ZapierSdk } from "@zapier/zapier-sdk";
2
- import type { BuildManifestPluginProvides } from "../plugins/buildManifest";
3
- import type { FeedbackPluginProvides } from "../plugins/feedback";
4
- import type { GenerateAppTypesPluginProvides } from "../plugins/generateAppTypes";
5
- import type { SignupPluginProvides } from "../plugins/signup";
6
- export type ZapierSdkCli = ZapierSdk & BuildManifestPluginProvides & FeedbackPluginProvides & GenerateAppTypesPluginProvides & SignupPluginProvides;
@@ -1 +0,0 @@
1
- export {};
@@ -1,15 +0,0 @@
1
- export interface ApiResponse<T = unknown> {
2
- data: T;
3
- status: number;
4
- }
5
- export declare const createApiClient: () => {
6
- post: <T = unknown>(url: string, data: Record<string, string>, options?: {
7
- headers?: Record<string, string>;
8
- }) => Promise<ApiResponse<T>>;
9
- };
10
- declare const api: {
11
- post: <T = unknown>(url: string, data: Record<string, string>, options?: {
12
- headers?: Record<string, string>;
13
- }) => Promise<ApiResponse<T>>;
14
- };
15
- export default api;
@@ -1,27 +0,0 @@
1
- export const createApiClient = () => {
2
- const post = async (url, data, options = {}) => {
3
- const { headers = {} } = options;
4
- const response = await fetch(url, {
5
- method: "POST",
6
- headers: {
7
- "Content-Type": "application/x-www-form-urlencoded",
8
- Connection: "close",
9
- ...headers,
10
- },
11
- body: new URLSearchParams(data),
12
- });
13
- if (!response.ok) {
14
- throw new Error(`${response.status} ${response.statusText}`);
15
- }
16
- const responseData = await response.json();
17
- return {
18
- data: responseData,
19
- status: response.status,
20
- };
21
- };
22
- return {
23
- post,
24
- };
25
- };
26
- const api = createApiClient();
27
- export default api;
@@ -1 +0,0 @@
1
- export declare function getApprovalReason(error: unknown): string | undefined;
@@ -1,9 +0,0 @@
1
- import { ZapierApprovalError } from "@zapier/zapier-sdk";
2
- export function getApprovalReason(error) {
3
- if (!(error instanceof ZapierApprovalError))
4
- return undefined;
5
- const { reason } = error;
6
- return typeof reason === "string" && reason.trim().length > 0
7
- ? reason.trim()
8
- : undefined;
9
- }
@@ -1,12 +0,0 @@
1
- export interface ApprovalProgressEvent {
2
- type: string;
3
- payload?: Record<string, unknown>;
4
- timestamp?: number;
5
- }
6
- export interface ApprovalProgressRenderer {
7
- onEvent(event: ApprovalProgressEvent): void;
8
- }
9
- export declare function createApprovalProgressRenderer({ enabled, onEvent, }: {
10
- enabled: boolean;
11
- onEvent?: (event: ApprovalProgressEvent) => void;
12
- }): ApprovalProgressRenderer;
@@ -1,179 +0,0 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import React from "react";
3
- const FALLBACK_PANEL_WIDTH = 72;
4
- const MIN_PANEL_WIDTH = 36;
5
- const MAX_PANEL_WIDTH = 88;
6
- const MAX_VISIBLE_MESSAGES = 5;
7
- const SPINNER_INTERVAL_MS = 80;
8
- const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
9
- let inkImportPromise;
10
- function loadInk() {
11
- inkImportPromise ?? (inkImportPromise = import("ink"));
12
- return inkImportPromise;
13
- }
14
- function createInitialState() {
15
- return {
16
- messages: [],
17
- active: false,
18
- };
19
- }
20
- function getPanelWidth() {
21
- const terminalColumns = process.stderr.columns;
22
- if (!terminalColumns)
23
- return FALLBACK_PANEL_WIDTH;
24
- return Math.min(Math.max(terminalColumns - 4, MIN_PANEL_WIDTH), MAX_PANEL_WIDTH);
25
- }
26
- function getPayloadString(event, key) {
27
- const value = event.payload?.[key];
28
- if (typeof value !== "string")
29
- return undefined;
30
- const trimmed = value.trim();
31
- return trimmed.length > 0 ? trimmed : undefined;
32
- }
33
- function getApprovedVerdict(decision, reason) {
34
- if (decision !== "approved")
35
- return undefined;
36
- return {
37
- icon: "✓",
38
- label: "Approved",
39
- color: "green",
40
- reason,
41
- };
42
- }
43
- function Spinner({ text }) {
44
- const [frameIndex, setFrameIndex] = React.useState(0);
45
- const InkText = text;
46
- React.useEffect(() => {
47
- const timer = setInterval(() => {
48
- setFrameIndex((index) => (index + 1) % SPINNER_FRAMES.length);
49
- }, SPINNER_INTERVAL_MS);
50
- return () => clearInterval(timer);
51
- }, []);
52
- return (_jsx(InkText, { color: "yellow", children: `${SPINNER_FRAMES[frameIndex]} Checking approval...` }));
53
- }
54
- function ApprovalProgressView({ state, box, text, }) {
55
- if (!state.active)
56
- return null;
57
- const InkBox = box;
58
- const InkText = text;
59
- const recentMessages = state.messages.slice(-MAX_VISIBLE_MESSAGES);
60
- const hasMessages = recentMessages.length > 0;
61
- return (_jsxs(InkBox, { borderColor: "cyan", borderStyle: "round", flexDirection: "column", paddingX: 1, width: getPanelWidth(), children: [_jsx(InkText, { bold: true, color: "cyan", children: "Approval review" }), _jsxs(InkBox, { flexDirection: "column", marginTop: 1, children: [!state.verdict && _jsx(Spinner, { text: text }), recentMessages.map((message, index) => (_jsxs(InkBox, { flexDirection: "row", children: [_jsx(InkText, { color: "cyan", children: "> " }), _jsx(InkText, { dimColor: Boolean(state.verdict) || index < recentMessages.length - 1, wrap: "wrap", children: message })] }, `${index}-${message}`))), state.streamError && (_jsxs(InkBox, { flexDirection: "column", marginTop: hasMessages || !state.verdict ? 1 : 0, children: [_jsx(InkText, { bold: true, color: "red", children: "Approval stream error" }), _jsx(InkText, { wrap: "wrap", children: ` ${state.streamError}` })] })), state.verdict && (_jsxs(InkBox, { flexDirection: "column", marginTop: hasMessages || state.streamError ? 1 : 0, children: [_jsx(InkText, { bold: true, color: state.verdict.color, children: `${state.verdict.icon} ${state.verdict.label}` }), state.verdict.reason && (_jsx(InkText, { wrap: "wrap", children: ` ${state.verdict.reason}` }))] }))] })] }));
62
- }
63
- export function createApprovalProgressRenderer({ enabled, onEvent, }) {
64
- let instance;
65
- let currentState = createInitialState();
66
- let renderQueue = Promise.resolve();
67
- let renderGeneration = 0;
68
- let renderEnabled = enabled;
69
- let renderErrorReported = false;
70
- function update(nextState, { complete = false } = {}) {
71
- const generation = renderGeneration;
72
- currentState = complete ? createInitialState() : nextState;
73
- renderQueue = renderQueue
74
- .then(async () => {
75
- if (generation !== renderGeneration)
76
- return;
77
- const { Box, Text, render } = await loadInk();
78
- if (generation !== renderGeneration)
79
- return;
80
- const element = (_jsx(ApprovalProgressView, { state: nextState, box: Box, text: Text }));
81
- if (!instance) {
82
- instance = render(element, {
83
- stdout: process.stderr,
84
- stderr: process.stderr,
85
- });
86
- }
87
- else {
88
- instance.rerender(element);
89
- }
90
- if (complete) {
91
- instance.unmount();
92
- instance = undefined;
93
- }
94
- })
95
- .catch((error) => {
96
- if (generation !== renderGeneration)
97
- return;
98
- renderEnabled = false;
99
- currentState = createInitialState();
100
- if (renderErrorReported)
101
- return;
102
- renderErrorReported = true;
103
- const message = error instanceof Error ? error.message : String(error);
104
- process.stderr.write(`Approval progress unavailable: ${message}\n`);
105
- });
106
- }
107
- function dismiss() {
108
- renderGeneration++;
109
- currentState = createInitialState();
110
- instance?.unmount();
111
- instance = undefined;
112
- }
113
- return {
114
- onEvent(event) {
115
- onEvent?.(event);
116
- if (!renderEnabled)
117
- return;
118
- if (event.type === "approval:required") {
119
- if (event.payload?.mode !== "auto")
120
- return;
121
- update({
122
- approvalId: getPayloadString(event, "approvalId"),
123
- messages: [],
124
- active: true,
125
- });
126
- return;
127
- }
128
- if (event.type === "approval:review_message") {
129
- if (!currentState.active)
130
- return;
131
- const message = getPayloadString(event, "message");
132
- if (!message)
133
- return;
134
- update({
135
- ...currentState,
136
- messages: [...currentState.messages, message],
137
- });
138
- return;
139
- }
140
- if (event.type === "approval:review_decision") {
141
- if (!currentState.active)
142
- return;
143
- const verdict = getApprovedVerdict(event.payload?.decision, getPayloadString(event, "reason"));
144
- if (!verdict)
145
- return;
146
- update({
147
- ...currentState,
148
- verdict,
149
- }, { complete: true });
150
- return;
151
- }
152
- if (event.type === "approval:review_stream_error") {
153
- if (!currentState.active)
154
- return;
155
- update({
156
- ...currentState,
157
- streamError: getPayloadString(event, "message") ??
158
- "Approval review stream failed",
159
- });
160
- return;
161
- }
162
- if (!currentState.active)
163
- return;
164
- if (event.type === "approval:approved") {
165
- update({
166
- ...currentState,
167
- verdict: getApprovedVerdict("approved", getPayloadString(event, "reason")),
168
- }, { complete: true });
169
- return;
170
- }
171
- if (event.type === "approval:denied" ||
172
- event.type === "approval:failed" ||
173
- event.type === "approval:timeout" ||
174
- event.type === "approval:error") {
175
- dismiss();
176
- }
177
- },
178
- };
179
- }
@@ -1,33 +0,0 @@
1
- import { type ApiClient, type EventEmissionProvides, type ResolvedCredentials } from "@zapier/zapier-sdk";
2
- export type AccountAuthEntryPoint = "login" | "signup";
3
- export interface AccountAuthOptions {
4
- name?: string;
5
- timeout?: string;
6
- useApprovals?: boolean;
7
- nonInteractive?: boolean;
8
- /** @deprecated Use `nonInteractive` instead. */
9
- skipPrompts?: boolean;
10
- headless?: boolean;
11
- }
12
- export interface AccountAuthCliContext {
13
- session_id?: string | null;
14
- selected_api?: string | null;
15
- app_id?: number | null;
16
- app_version_id?: number | null;
17
- resolveCredentials: () => Promise<ResolvedCredentials | undefined>;
18
- api: ApiClient;
19
- options?: {
20
- baseUrl?: string;
21
- credentials?: unknown;
22
- };
23
- }
24
- export type CliContext = AccountAuthCliContext;
25
- interface RunAccountAuthOptions<TOptions extends AccountAuthOptions> {
26
- sdk: EventEmissionProvides & {
27
- context: AccountAuthCliContext;
28
- };
29
- options: TOptions;
30
- entryPoint: AccountAuthEntryPoint;
31
- }
32
- export declare function runAccountAuth<TOptions extends AccountAuthOptions>({ sdk, options, entryPoint, }: RunAccountAuthOptions<TOptions>): Promise<void>;
33
- export {};
@@ -1,302 +0,0 @@
1
- import { hostname } from "node:os";
2
- import inquirer from "inquirer";
3
- import { AuthMechanism, buildApplicationLifecycleEvent, getOrCreateApiClient, isCredentialsObject, } from "@zapier/zapier-sdk";
4
- import { revokeCredentials } from "../../login/credentials-revoke";
5
- import { credentialNameExists, deleteStoredClientCredentials, getActiveCredentials, resolveAvailableCredentialName, } from "../../login/credentials-store";
6
- import { clearLegacyJwtState, hasLegacyJwtConfig, } from "../../login/legacy-jwt";
7
- import { resolveCredentialsBaseUrl } from "../../plugins/auth/credentials-base-url";
8
- import { resolveNonInteractive } from "../non-interactive";
9
- import { ZapierCliUserCancellationError, ZapierCliValidationError, } from "../errors";
10
- import { EMPTY_POLICY, setupClientCredentials } from "./client-credentials";
11
- import { runLoginOauthFlow, runSignupOauthFlow, } from "./oauth-flow";
12
- import { toRedactedOauthError } from "./oauth-errors";
13
- const 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?";
14
- const SIGNUP_RECOVERY_MESSAGE = "Restart `zapier-sdk signup` to generate a fresh signup URL and try again.";
15
- const HEADLESS_SIGNUP_RECOVERY_MESSAGE = "Restart `zapier-sdk signup --headless` to generate a fresh signup URL and try again.";
16
- function getEntryPointLabel(entryPoint) {
17
- return entryPoint === "signup" ? "Signup" : "Login";
18
- }
19
- function getActiveCredentialsAction(entryPoint) {
20
- return entryPoint === "signup" ? "continue signup" : "log in again";
21
- }
22
- function getCredentialsPromptMessage(entryPoint) {
23
- return entryPoint === "signup"
24
- ? "Enter a name to identify these credentials:"
25
- : "Enter a name to identify them:";
26
- }
27
- function getProfileMessage(entryPoint, email) {
28
- return entryPoint === "signup"
29
- ? `👤 Authenticated as ${email}`
30
- : `👤 Logged in as ${email}`;
31
- }
32
- function defaultCredentialsName(email) {
33
- return `${email}@${hostname()}`;
34
- }
35
- function validateCredentialsName(name) {
36
- const trimmedName = name.trim();
37
- if (!trimmedName)
38
- throw new ZapierCliValidationError("Name cannot be empty");
39
- return trimmedName;
40
- }
41
- async function promptCredentialsName({ email, promptMessage, }) {
42
- const { credentialName } = await inquirer.prompt([
43
- {
44
- type: "input",
45
- name: "credentialName",
46
- message: promptMessage,
47
- default: defaultCredentialsName(email),
48
- validate: (input) => {
49
- try {
50
- validateCredentialsName(input);
51
- return true;
52
- }
53
- catch (err) {
54
- return err instanceof Error ? err.message : String(err);
55
- }
56
- },
57
- },
58
- ]);
59
- return validateCredentialsName(credentialName);
60
- }
61
- function resolveDefaultCredentialsName({ email, }) {
62
- return validateCredentialsName(defaultCredentialsName(email));
63
- }
64
- async function resolveCredentialName({ email, interactive, baseUrl, entryPoint, }) {
65
- if (interactive) {
66
- return promptCredentialsName({
67
- email,
68
- promptMessage: getCredentialsPromptMessage(entryPoint),
69
- });
70
- }
71
- // Non-interactive login can't prompt for a new name, so a default name that
72
- // already exists locally would silently overwrite that credential. Suffix it
73
- // instead.
74
- const baseName = resolveDefaultCredentialsName({ email });
75
- return resolveAvailableCredentialName({ baseName, baseUrl });
76
- }
77
- function toPkceCredentials(credentials) {
78
- if (credentials &&
79
- isCredentialsObject(credentials) &&
80
- !("clientSecret" in credentials)) {
81
- return {
82
- type: "pkce",
83
- clientId: credentials.clientId,
84
- baseUrl: credentials.baseUrl,
85
- scope: credentials.scope,
86
- };
87
- }
88
- return undefined;
89
- }
90
- function parseTimeoutSeconds(timeout) {
91
- if (timeout === undefined)
92
- return 300;
93
- const timeoutSeconds = Number(timeout);
94
- if (!Number.isInteger(timeoutSeconds) || timeoutSeconds <= 0) {
95
- throw new ZapierCliValidationError("Timeout must be a positive integer (seconds).");
96
- }
97
- return timeoutSeconds;
98
- }
99
- async function promptConfirm({ message, defaultValue, }) {
100
- const { confirmed } = await inquirer.prompt([
101
- { type: "confirm", name: "confirmed", message, default: defaultValue },
102
- ]);
103
- return confirmed;
104
- }
105
- function promptlessCredentialResetError(credentials) {
106
- throw new ZapierCliValidationError(`Already logged in as "${credentials.name}". Run \`logout\` first or use an interactive terminal to re-authenticate.`);
107
- }
108
- function promptlessLegacyJwtUpgradeError() {
109
- throw new ZapierCliValidationError("Legacy JWT login detected. Run `logout` first or use an interactive terminal to migrate to client credentials.");
110
- }
111
- async function clearExistingAuthState({ sdk, baseUrl, interactive, entryPoint, }) {
112
- const activeCredentials = getActiveCredentials({ baseUrl });
113
- const flowLabel = getEntryPointLabel(entryPoint);
114
- if (activeCredentials) {
115
- const confirmed = interactive
116
- ? await promptConfirm({
117
- defaultValue: false,
118
- message: `You are already logged in as "${activeCredentials.name}".\n` +
119
- "Logging out will delete these credentials and may interrupt other Zapier SDK or CLI sessions using them.\n" +
120
- `Log out and ${getActiveCredentialsAction(entryPoint)}?`,
121
- })
122
- : promptlessCredentialResetError(activeCredentials);
123
- if (!confirmed) {
124
- console.log(`${flowLabel} cancelled.`);
125
- return false;
126
- }
127
- try {
128
- await revokeCredentials({
129
- api: sdk.context.api,
130
- credentials: activeCredentials,
131
- });
132
- }
133
- catch {
134
- if (!interactive) {
135
- throw new ZapierCliValidationError(`${flowLabel} cleanup failed and cannot be reset without confirmation. Re-run with an interactive terminal.`);
136
- }
137
- const reset = await promptConfirm({
138
- defaultValue: false,
139
- message: `${flowLabel} cleanup failed. Reset local session state and continue?`,
140
- });
141
- if (!reset) {
142
- console.log(`${flowLabel} cancelled.`);
143
- return false;
144
- }
145
- await deleteStoredClientCredentials({
146
- name: activeCredentials.name,
147
- baseUrl: activeCredentials.baseUrl,
148
- });
149
- }
150
- }
151
- else if (hasLegacyJwtConfig()) {
152
- const confirmed = interactive
153
- ? await promptConfirm({
154
- defaultValue: true,
155
- message: LEGACY_JWT_UPGRADE_PROMPT,
156
- })
157
- : promptlessLegacyJwtUpgradeError();
158
- if (!confirmed) {
159
- console.log(`${flowLabel} cancelled.`);
160
- return false;
161
- }
162
- }
163
- return true;
164
- }
165
- async function getProfile(api) {
166
- return api.get("/zapier/api/v4/profile/", {
167
- authRequired: true,
168
- });
169
- }
170
- async function saveClientCredentials({ api, name, credentialsBaseUrl, useApprovals, cleanupLogPrefix, }) {
171
- const { clientId } = await setupClientCredentials({
172
- api,
173
- name,
174
- credentialsBaseUrl,
175
- ...(useApprovals && { policy: EMPTY_POLICY }),
176
- });
177
- try {
178
- await clearLegacyJwtState();
179
- }
180
- catch (err) {
181
- console.error(`[${cleanupLogPrefix}] Best-effort legacy JWT cleanup failed:`, err);
182
- }
183
- return { clientId };
184
- }
185
- function emitAccountAuthSuccess({ sdk, profile, clientId, }) {
186
- sdk.context.eventEmission.emit("platform.sdk.ApplicationLifecycleEvent", buildApplicationLifecycleEvent({ lifecycle_event_type: "login_success" }, {
187
- customuser_id: profile.user_id,
188
- account_id: profile.roles[0]?.account_id ?? null,
189
- client_id: clientId,
190
- auth_mechanism: AuthMechanism.ClientCredentials,
191
- }));
192
- }
193
- function emitSignupSuccess({ sdk, }) {
194
- // `signup_success` tracks a valid signup OAuth callback being accepted.
195
- // It does not mean a new Zapier account was created or local credentials were provisioned.
196
- sdk.context.eventEmission.emit("platform.sdk.ApplicationLifecycleEvent", buildApplicationLifecycleEvent({ lifecycle_event_type: "signup_success" }));
197
- }
198
- async function runOauthWithRedaction(runOauth) {
199
- try {
200
- return await runOauth();
201
- }
202
- catch (error) {
203
- if (error instanceof ZapierCliUserCancellationError)
204
- throw error;
205
- throw toRedactedOauthError(error);
206
- }
207
- }
208
- async function runOauthForEntryPoint({ sdk, entryPoint, timeoutMs, pkceCredentials, baseUrl, headless, interactive, }) {
209
- if (entryPoint === "signup") {
210
- return runOauthWithRedaction(() => runSignupOauthFlow({
211
- timeoutMs,
212
- pkceCredentials,
213
- baseUrl,
214
- headless,
215
- interactive,
216
- recoveryMessage: headless
217
- ? HEADLESS_SIGNUP_RECOVERY_MESSAGE
218
- : SIGNUP_RECOVERY_MESSAGE,
219
- onProgress: (event) => {
220
- if (event.type === "callback_accepted") {
221
- emitSignupSuccess({ sdk });
222
- }
223
- },
224
- }));
225
- }
226
- return runOauthWithRedaction(() => runLoginOauthFlow({ timeoutMs, pkceCredentials, baseUrl }));
227
- }
228
- export async function runAccountAuth({ sdk, options, entryPoint, }) {
229
- const timeoutSeconds = parseTimeoutSeconds(options.timeout);
230
- const interactive = !resolveNonInteractive(options);
231
- const resolvedCredentials = await sdk.context.resolveCredentials();
232
- const pkceCredentials = toPkceCredentials(resolvedCredentials);
233
- const credentialsBaseUrl = await resolveCredentialsBaseUrl({
234
- ...sdk.context,
235
- resolvedCredentials,
236
- });
237
- // An explicitly-supplied name is validated and collision-checked up front,
238
- // before we tear down the existing session or run OAuth. Otherwise a blank or
239
- // already-taken name would only surface after revoking the active credential
240
- // and completing the browser flow, leaving the user logged out for nothing.
241
- // The name is trimmed but otherwise honored as given — never auto-suffixed —
242
- // so a collision is rejected rather than silently overwriting an existing
243
- // credential.
244
- const providedName = options.name !== undefined
245
- ? validateCredentialsName(options.name)
246
- : undefined;
247
- if (providedName !== undefined) {
248
- const activeCredentials = getActiveCredentials({
249
- baseUrl: credentialsBaseUrl,
250
- });
251
- // Re-login under the active credential's own name is a rotation, not a
252
- // collision — clearExistingAuthState frees it below.
253
- if (activeCredentials?.name !== providedName &&
254
- credentialNameExists({ name: providedName, baseUrl: credentialsBaseUrl })) {
255
- throw new ZapierCliValidationError(`A credential named "${providedName}" already exists. Choose a different --name.`);
256
- }
257
- }
258
- if (!(await clearExistingAuthState({
259
- sdk,
260
- baseUrl: credentialsBaseUrl,
261
- interactive,
262
- entryPoint,
263
- }))) {
264
- return;
265
- }
266
- const { accessToken } = await runOauthForEntryPoint({
267
- sdk,
268
- entryPoint,
269
- timeoutMs: timeoutSeconds * 1000,
270
- pkceCredentials,
271
- baseUrl: credentialsBaseUrl,
272
- headless: options.headless === true,
273
- interactive,
274
- });
275
- const scopedApi = getOrCreateApiClient({
276
- credentials: accessToken,
277
- baseUrl: credentialsBaseUrl,
278
- });
279
- const profile = await getProfile(scopedApi);
280
- console.log(getProfileMessage(entryPoint, profile.email));
281
- console.log("\nGenerating credentials so this machine can make authenticated requests on your behalf.");
282
- const credentialName = providedName ??
283
- (await resolveCredentialName({
284
- email: profile.email,
285
- interactive,
286
- baseUrl: credentialsBaseUrl,
287
- entryPoint,
288
- }));
289
- const useApprovals = options.useApprovals === true;
290
- const { clientId } = await saveClientCredentials({
291
- api: scopedApi,
292
- name: credentialName,
293
- credentialsBaseUrl,
294
- useApprovals,
295
- cleanupLogPrefix: entryPoint,
296
- });
297
- console.log(`✅ Credentials "${credentialName}" created and set as default. You are ready to use the Zapier SDK.`);
298
- if (useApprovals) {
299
- console.log("🔐 Approvals are enabled for these credentials.");
300
- }
301
- emitAccountAuthSuccess({ sdk, profile, clientId });
302
- }
@@ -1,26 +0,0 @@
1
- import type { Policy } from "@zapier/policy-schema";
2
- import type { ApiClient } from "@zapier/zapier-sdk";
3
- /**
4
- * The canonical empty approvals policy. Attaching this to a credential at
5
- * creation time tells the server that requests made with these credentials
6
- * are subject to approval. Server-side enforcement decides which specific
7
- * requests trigger the approval flow; the SDK only attaches the policy.
8
- */
9
- export declare const EMPTY_POLICY: Policy;
10
- export interface SetupClientCredentialsOptions {
11
- api: ApiClient;
12
- name: string;
13
- credentialsBaseUrl?: string;
14
- /** Optional policy document to attach to the new credential. */
15
- policy?: Policy;
16
- }
17
- export interface SetupClientCredentialsResult {
18
- clientId: string;
19
- }
20
- /**
21
- * Create a client credential server-side and persist it locally. If the
22
- * local store fails after the server-side credential is created, attempt
23
- * to roll back the orphan; if that rollback also fails, surface a
24
- * manual-fix message and re-throw the original store error.
25
- */
26
- export declare function setupClientCredentials({ api, name, credentialsBaseUrl, policy, }: SetupClientCredentialsOptions): Promise<SetupClientCredentialsResult>;