@zapier/zapier-sdk 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/dist/index.cjs +1962 -0
  2. package/dist/index.d.mts +892 -0
  3. package/dist/index.d.ts +892 -20
  4. package/dist/index.mjs +1914 -0
  5. package/package.json +19 -7
  6. package/src/api/client.ts +106 -25
  7. package/src/api/polling.ts +4 -8
  8. package/src/api/types.ts +8 -1
  9. package/src/auth.ts +19 -287
  10. package/src/functions/findFirstAuthentication/schemas.ts +3 -13
  11. package/src/functions/findUniqueAuthentication/schemas.ts +3 -13
  12. package/src/functions/generateTypes/index.ts +15 -0
  13. package/src/functions/generateTypes/schemas.ts +3 -10
  14. package/src/functions/getAction/schemas.ts +3 -13
  15. package/src/functions/getApp/schemas.ts +2 -13
  16. package/src/functions/getAuthentication/index.ts +0 -1
  17. package/src/functions/getAuthentication/schemas.ts +3 -17
  18. package/src/functions/listActions/schemas.ts +3 -13
  19. package/src/functions/listApps/schemas.ts +2 -13
  20. package/src/functions/listAuthentications/index.ts +0 -1
  21. package/src/functions/listAuthentications/schemas.ts +3 -15
  22. package/src/functions/listFields/schemas.ts +3 -13
  23. package/src/functions/request/index.ts +150 -0
  24. package/src/functions/request/info.ts +11 -0
  25. package/src/functions/request/schemas.ts +53 -0
  26. package/src/functions/runAction/index.ts +0 -1
  27. package/src/functions/runAction/schemas.ts +6 -15
  28. package/src/index.ts +8 -2
  29. package/src/plugins/apps/index.ts +34 -9
  30. package/src/plugins/apps/types.ts +17 -1
  31. package/src/plugins/fetch/index.ts +50 -0
  32. package/src/plugins/fetch/types.ts +2 -0
  33. package/src/sdk.ts +19 -23
  34. package/src/types/domain.ts +16 -0
  35. package/src/types/sdk.ts +17 -2
  36. package/tsconfig.json +2 -2
  37. package/tsup.config.ts +21 -0
  38. package/dist/api/auth.d.ts +0 -8
  39. package/dist/api/auth.js +0 -29
  40. package/dist/api/client.d.ts +0 -8
  41. package/dist/api/client.js +0 -119
  42. package/dist/api/debug.d.ts +0 -12
  43. package/dist/api/debug.js +0 -50
  44. package/dist/api/index.d.ts +0 -28
  45. package/dist/api/index.js +0 -52
  46. package/dist/api/polling.d.ts +0 -17
  47. package/dist/api/polling.js +0 -34
  48. package/dist/api/types.d.ts +0 -147
  49. package/dist/api/types.js +0 -9
  50. package/dist/auth.d.ts +0 -59
  51. package/dist/auth.js +0 -261
  52. package/dist/functions/bundleCode/index.d.ts +0 -11
  53. package/dist/functions/bundleCode/index.js +0 -91
  54. package/dist/functions/bundleCode/info.d.ts +0 -27
  55. package/dist/functions/bundleCode/info.js +0 -11
  56. package/dist/functions/bundleCode/schemas.d.ts +0 -27
  57. package/dist/functions/bundleCode/schemas.js +0 -22
  58. package/dist/functions/findFirstAuthentication/index.d.ts +0 -12
  59. package/dist/functions/findFirstAuthentication/index.js +0 -21
  60. package/dist/functions/findFirstAuthentication/info.d.ts +0 -30
  61. package/dist/functions/findFirstAuthentication/info.js +0 -11
  62. package/dist/functions/findFirstAuthentication/schemas.d.ts +0 -42
  63. package/dist/functions/findFirstAuthentication/schemas.js +0 -25
  64. package/dist/functions/findUniqueAuthentication/index.d.ts +0 -13
  65. package/dist/functions/findUniqueAuthentication/index.js +0 -28
  66. package/dist/functions/findUniqueAuthentication/info.d.ts +0 -30
  67. package/dist/functions/findUniqueAuthentication/info.js +0 -11
  68. package/dist/functions/findUniqueAuthentication/schemas.d.ts +0 -42
  69. package/dist/functions/findUniqueAuthentication/schemas.js +0 -25
  70. package/dist/functions/generateTypes/index.d.ts +0 -11
  71. package/dist/functions/generateTypes/index.js +0 -305
  72. package/dist/functions/generateTypes/info.d.ts +0 -21
  73. package/dist/functions/generateTypes/info.js +0 -11
  74. package/dist/functions/generateTypes/schemas.d.ts +0 -30
  75. package/dist/functions/generateTypes/schemas.js +0 -14
  76. package/dist/functions/getAction/index.d.ts +0 -12
  77. package/dist/functions/getAction/index.js +0 -26
  78. package/dist/functions/getAction/info.d.ts +0 -18
  79. package/dist/functions/getAction/info.js +0 -11
  80. package/dist/functions/getAction/schemas.d.ts +0 -30
  81. package/dist/functions/getAction/schemas.js +0 -13
  82. package/dist/functions/getApp/index.d.ts +0 -12
  83. package/dist/functions/getApp/index.js +0 -37
  84. package/dist/functions/getApp/info.d.ts +0 -12
  85. package/dist/functions/getApp/info.js +0 -11
  86. package/dist/functions/getApp/schemas.d.ts +0 -24
  87. package/dist/functions/getApp/schemas.js +0 -11
  88. package/dist/functions/getAuthentication/index.d.ts +0 -13
  89. package/dist/functions/getAuthentication/index.js +0 -38
  90. package/dist/functions/getAuthentication/info.d.ts +0 -12
  91. package/dist/functions/getAuthentication/info.js +0 -11
  92. package/dist/functions/getAuthentication/schemas.d.ts +0 -26
  93. package/dist/functions/getAuthentication/schemas.js +0 -16
  94. package/dist/functions/listActions/index.d.ts +0 -12
  95. package/dist/functions/listActions/index.js +0 -128
  96. package/dist/functions/listActions/info.d.ts +0 -15
  97. package/dist/functions/listActions/info.js +0 -11
  98. package/dist/functions/listActions/schemas.d.ts +0 -27
  99. package/dist/functions/listActions/schemas.js +0 -14
  100. package/dist/functions/listApps/index.d.ts +0 -12
  101. package/dist/functions/listApps/index.js +0 -50
  102. package/dist/functions/listApps/info.d.ts +0 -18
  103. package/dist/functions/listApps/info.js +0 -11
  104. package/dist/functions/listApps/schemas.d.ts +0 -30
  105. package/dist/functions/listApps/schemas.js +0 -15
  106. package/dist/functions/listAuthentications/index.d.ts +0 -12
  107. package/dist/functions/listAuthentications/index.js +0 -131
  108. package/dist/functions/listAuthentications/info.d.ts +0 -30
  109. package/dist/functions/listAuthentications/info.js +0 -11
  110. package/dist/functions/listAuthentications/schemas.d.ts +0 -44
  111. package/dist/functions/listAuthentications/schemas.js +0 -25
  112. package/dist/functions/listFields/index.d.ts +0 -12
  113. package/dist/functions/listFields/index.js +0 -65
  114. package/dist/functions/listFields/info.d.ts +0 -24
  115. package/dist/functions/listFields/info.js +0 -11
  116. package/dist/functions/listFields/schemas.d.ts +0 -36
  117. package/dist/functions/listFields/schemas.js +0 -17
  118. package/dist/functions/runAction/index.d.ts +0 -12
  119. package/dist/functions/runAction/index.js +0 -86
  120. package/dist/functions/runAction/info.d.ts +0 -24
  121. package/dist/functions/runAction/info.js +0 -11
  122. package/dist/functions/runAction/schemas.d.ts +0 -38
  123. package/dist/functions/runAction/schemas.js +0 -15
  124. package/dist/index.js +0 -57
  125. package/dist/plugins/apps/index.d.ts +0 -8
  126. package/dist/plugins/apps/index.js +0 -77
  127. package/dist/plugins/apps/info.d.ts +0 -6
  128. package/dist/plugins/apps/info.js +0 -13
  129. package/dist/plugins/apps/types.d.ts +0 -21
  130. package/dist/plugins/apps/types.js +0 -2
  131. package/dist/resolvers/actionKey.d.ts +0 -8
  132. package/dist/resolvers/actionKey.js +0 -20
  133. package/dist/resolvers/actionType.d.ts +0 -8
  134. package/dist/resolvers/actionType.js +0 -21
  135. package/dist/resolvers/appKey.d.ts +0 -6
  136. package/dist/resolvers/appKey.js +0 -8
  137. package/dist/resolvers/authenticationId.d.ts +0 -8
  138. package/dist/resolvers/authenticationId.js +0 -29
  139. package/dist/resolvers/index.d.ts +0 -39
  140. package/dist/resolvers/index.js +0 -105
  141. package/dist/resolvers/inputs.d.ts +0 -7
  142. package/dist/resolvers/inputs.js +0 -15
  143. package/dist/schema-utils.d.ts +0 -44
  144. package/dist/schema-utils.js +0 -76
  145. package/dist/schemas/Action.d.ts +0 -21
  146. package/dist/schemas/Action.js +0 -31
  147. package/dist/schemas/App.d.ts +0 -19
  148. package/dist/schemas/App.js +0 -32
  149. package/dist/schemas/Auth.d.ts +0 -27
  150. package/dist/schemas/Auth.js +0 -42
  151. package/dist/schemas/Field.d.ts +0 -15
  152. package/dist/schemas/Field.js +0 -25
  153. package/dist/sdk.d.ts +0 -6
  154. package/dist/sdk.js +0 -90
  155. package/dist/types/domain.d.ts +0 -25
  156. package/dist/types/domain.js +0 -21
  157. package/dist/types/events.d.ts +0 -37
  158. package/dist/types/events.js +0 -8
  159. package/dist/types/properties.d.ts +0 -21
  160. package/dist/types/properties.js +0 -52
  161. package/dist/types/sdk.d.ts +0 -24
  162. package/dist/types/sdk.js +0 -2
@@ -1,17 +0,0 @@
1
- /**
2
- * Polling Utilities
3
- *
4
- * This module provides utilities for polling HTTP endpoints until completion,
5
- * with configurable retry logic and exponential backoff.
6
- */
7
- export declare function pollUntilComplete(options: {
8
- fetch: typeof globalThis.fetch;
9
- url: string;
10
- headers?: Record<string, string>;
11
- maxAttempts?: number;
12
- initialDelay?: number;
13
- maxDelay?: number;
14
- successStatus?: number;
15
- pendingStatus?: number;
16
- resultExtractor?: (response: any) => any;
17
- }): Promise<any>;
@@ -1,34 +0,0 @@
1
- "use strict";
2
- /**
3
- * Polling Utilities
4
- *
5
- * This module provides utilities for polling HTTP endpoints until completion,
6
- * with configurable retry logic and exponential backoff.
7
- */
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.pollUntilComplete = pollUntilComplete;
10
- async function pollUntilComplete(options) {
11
- const { fetch, url, headers = {}, maxAttempts = 30, initialDelay = 50, maxDelay = 1000, successStatus = 200, pendingStatus = 202, resultExtractor = (response) => response, } = options;
12
- let delay = initialDelay;
13
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
14
- const response = await fetch(url, { headers });
15
- if (response.status === successStatus) {
16
- // Success - extract and return results
17
- const result = await response.json();
18
- return resultExtractor(result);
19
- }
20
- else if (response.status === pendingStatus) {
21
- // Still processing - wait and retry
22
- if (attempt < maxAttempts - 1) {
23
- await new Promise((resolve) => setTimeout(resolve, delay));
24
- delay = Math.min(delay * 2, maxDelay); // Exponential backoff
25
- continue;
26
- }
27
- }
28
- else {
29
- // Error occurred
30
- throw new Error(`Request failed: GET ${url} - ${response.status} ${response.statusText}`);
31
- }
32
- }
33
- throw new Error(`Operation timed out after ${maxAttempts} attempts`);
34
- }
@@ -1,147 +0,0 @@
1
- /**
2
- * API Client Type Definitions
3
- *
4
- * This module contains all type definitions related to the Zapier API client,
5
- * including configuration options, client interfaces, request/response types,
6
- * and API response models.
7
- */
8
- export interface ApiClientOptions {
9
- baseUrl: string;
10
- token?: string;
11
- getToken?: () => Promise<string | undefined>;
12
- debug?: boolean;
13
- fetch?: typeof globalThis.fetch;
14
- }
15
- export interface ApiClient {
16
- get: (path: string, options?: RequestOptions) => Promise<any>;
17
- post: (path: string, data?: any, options?: RequestOptions) => Promise<any>;
18
- put: (path: string, data?: any, options?: RequestOptions) => Promise<any>;
19
- delete: (path: string, options?: RequestOptions) => Promise<any>;
20
- poll: (path: string, options?: PollOptions) => Promise<any>;
21
- requireAuthTo: (operation: string) => void;
22
- }
23
- export interface RequestOptions {
24
- headers?: Record<string, string>;
25
- searchParams?: Record<string, string>;
26
- authRequired?: boolean;
27
- customErrorHandler?: (response: Response) => Error | undefined;
28
- }
29
- export interface PollOptions extends RequestOptions {
30
- maxAttempts?: number;
31
- initialDelay?: number;
32
- maxDelay?: number;
33
- successStatus?: number;
34
- pendingStatus?: number;
35
- resultExtractor?: (response: any) => any;
36
- }
37
- export interface DebugLogger {
38
- (message: string, data?: any): void;
39
- }
40
- export interface Integration {
41
- key: string;
42
- name: string;
43
- description: string;
44
- version: string;
45
- category?: string;
46
- actions: Action[];
47
- triggers: Trigger[];
48
- current_implementation_id?: string;
49
- }
50
- export interface Action {
51
- key: string;
52
- name: string;
53
- description: string;
54
- appKey: string;
55
- type: "read" | "read_bulk" | "write" | "run" | "search" | "search_or_write" | "search_and_write" | "filter";
56
- inputFields: Field[];
57
- outputFields: Field[];
58
- }
59
- export interface Trigger {
60
- key: string;
61
- name: string;
62
- description: string;
63
- appKey: string;
64
- type: "instant" | "polling" | "webhook";
65
- outputFields: Field[];
66
- }
67
- export interface Field {
68
- key: string;
69
- label: string;
70
- type: "string" | "number" | "boolean" | "datetime" | "file" | "object" | "array";
71
- required: boolean;
72
- description?: string;
73
- choices?: Choice[];
74
- }
75
- export interface Choice {
76
- value: string | number;
77
- label: string;
78
- }
79
- export interface ActionExecutionResult {
80
- success: boolean;
81
- data?: any;
82
- error?: string;
83
- metadata?: {
84
- executionTime?: number;
85
- requestId?: string;
86
- };
87
- }
88
- export interface ActionField {
89
- key: string;
90
- label?: string;
91
- required: boolean;
92
- type?: string;
93
- helpText?: string;
94
- helpTextHtml?: string;
95
- choices?: ActionFieldChoice[];
96
- default?: string;
97
- placeholder?: string;
98
- computed?: boolean;
99
- customField?: boolean;
100
- dependsOn?: string[];
101
- format?: string;
102
- inputFormat?: string[];
103
- }
104
- export interface ActionFieldChoice {
105
- value: string | number;
106
- label: string;
107
- }
108
- export interface NeedsRequest {
109
- selected_api: string;
110
- action: string;
111
- type_of: string;
112
- authentication_id?: number;
113
- params?: Record<string, any>;
114
- }
115
- export interface NeedsResponse {
116
- success: boolean;
117
- needs?: ActionField[];
118
- errors?: string[];
119
- }
120
- export interface Authentication {
121
- id: number;
122
- date: string;
123
- lastchanged?: string;
124
- account_id: number;
125
- customuser_id?: number;
126
- selected_api: string;
127
- destination_selected_api?: string | null;
128
- is_invite_only: boolean;
129
- is_private: boolean;
130
- shared_with_all: boolean;
131
- is_stale?: string;
132
- is_shared?: string;
133
- marked_stale_at?: string | null;
134
- label?: string | null;
135
- identifier?: string | null;
136
- title?: string | null;
137
- url?: string;
138
- groups?: string;
139
- members?: string;
140
- permissions?: Record<string, boolean>;
141
- }
142
- export interface AuthenticationsResponse {
143
- count: number;
144
- next?: string | null;
145
- previous?: string | null;
146
- results: Authentication[];
147
- }
package/dist/api/types.js DELETED
@@ -1,9 +0,0 @@
1
- "use strict";
2
- /**
3
- * API Client Type Definitions
4
- *
5
- * This module contains all type definitions related to the Zapier API client,
6
- * including configuration options, client interfaces, request/response types,
7
- * and API response models.
8
- */
9
- Object.defineProperty(exports, "__esModule", { value: true });
package/dist/auth.d.ts DELETED
@@ -1,59 +0,0 @@
1
- /**
2
- * SDK Authentication Utilities
3
- *
4
- * This module provides SDK-level authentication utilities, including
5
- * token acquisition, refresh, and user information extraction.
6
- */
7
- import type { EventCallback } from "./types/events";
8
- export type { SdkEvent, AuthEvent, ApiEvent, LoadingEvent, EventCallback, } from "./types/events";
9
- export interface AuthOptions {
10
- onEvent?: EventCallback;
11
- fetch?: typeof globalThis.fetch;
12
- }
13
- export interface LoginData {
14
- access_token: string;
15
- refresh_token: string;
16
- expires_in: number;
17
- }
18
- export declare function updateLogin(loginData: LoginData): void;
19
- /**
20
- * Attempts to read a valid JWT token from the CLI configuration.
21
- * Automatically refreshes expired tokens when possible.
22
- * Returns undefined if no valid token is found or refresh fails.
23
- */
24
- export declare function getTokenFromConfig(options?: AuthOptions): Promise<string | undefined>;
25
- /**
26
- * Gets the ZAPIER_TOKEN from environment variables.
27
- * Returns undefined if not set.
28
- */
29
- export declare function getTokenFromEnv(): string | undefined;
30
- /**
31
- * Attempts to get a token with the following precedence:
32
- * 1. ZAPIER_TOKEN environment variable
33
- * 2. Valid JWT from CLI configuration (with auto-refresh)
34
- *
35
- * Returns undefined if no valid token is found.
36
- */
37
- export declare function getTokenFromEnvOrConfig(options?: AuthOptions): Promise<string | undefined>;
38
- /**
39
- * Gets the current JWT token, refreshing if necessary.
40
- * Returns undefined if no valid token is available.
41
- */
42
- export declare function getValidJwt(options?: AuthOptions): Promise<string | undefined>;
43
- /**
44
- * Gets the logged-in user information from JWT token.
45
- * Automatically refreshes token if expired.
46
- */
47
- export declare function getLoggedInUser(options?: AuthOptions): Promise<{
48
- accountId: number;
49
- customUserId: number;
50
- email: string;
51
- }>;
52
- /**
53
- * Clears stored login information.
54
- */
55
- export declare function logout(options?: Pick<AuthOptions, "onEvent">): void;
56
- /**
57
- * Gets the path to the configuration file.
58
- */
59
- export declare function getConfigPath(): string;
package/dist/auth.js DELETED
@@ -1,261 +0,0 @@
1
- "use strict";
2
- /**
3
- * SDK Authentication Utilities
4
- *
5
- * This module provides SDK-level authentication utilities, including
6
- * token acquisition, refresh, and user information extraction.
7
- */
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.updateLogin = updateLogin;
10
- exports.getTokenFromConfig = getTokenFromConfig;
11
- exports.getTokenFromEnv = getTokenFromEnv;
12
- exports.getTokenFromEnvOrConfig = getTokenFromEnvOrConfig;
13
- exports.getValidJwt = getValidJwt;
14
- exports.getLoggedInUser = getLoggedInUser;
15
- exports.logout = logout;
16
- exports.getConfigPath = getConfigPath;
17
- // Import type { RequestOptions } from "./api/types"; // Commented out - not used yet
18
- let config;
19
- // Constants needed for token refresh
20
- const ZAPIER_BASE = "https://zapier.com";
21
- const LOGIN_CLIENT_ID = "K5eEnRE9TTmSFATdkkWhKF8NOKwoiOnYAyIqJjae";
22
- const AUTH_MODE_HEADER = "X-Auth";
23
- // Utility functions for config management
24
- function getConfig() {
25
- if (!config) {
26
- const ConfModule = require("conf");
27
- const Conf = ConfModule.default || ConfModule;
28
- config = new Conf({ projectName: "zapier-sdk-cli" });
29
- }
30
- return config;
31
- }
32
- function updateLogin(loginData) {
33
- const cfg = getConfig();
34
- cfg.set("login_jwt", loginData.access_token);
35
- cfg.set("login_refresh_token", loginData.refresh_token);
36
- cfg.set("login_expires_at", Date.now() + loginData.expires_in * 1000);
37
- }
38
- function clearLogin() {
39
- const cfg = getConfig();
40
- cfg.delete("login_jwt");
41
- cfg.delete("login_refresh_token");
42
- cfg.delete("login_expires_at");
43
- }
44
- // JWT utility functions
45
- function decodeJwtOrThrow(jwt) {
46
- if (typeof jwt !== "string") {
47
- throw new Error("Expected JWT to be a string");
48
- }
49
- let jsonwebtoken;
50
- try {
51
- jsonwebtoken = require("jsonwebtoken");
52
- }
53
- catch {
54
- throw new Error("jsonwebtoken not available - this function requires CLI dependencies");
55
- }
56
- const decodedJwt = jsonwebtoken.decode(jwt, { complete: true });
57
- if (!decodedJwt) {
58
- throw new Error("Could not decode JWT");
59
- }
60
- if (typeof decodedJwt.payload === "string") {
61
- throw new Error("Did not expect JWT payload to be a string");
62
- }
63
- return decodedJwt;
64
- }
65
- /**
66
- * Refreshes an expired JWT token using the refresh token.
67
- * Returns the new access token or throws an error.
68
- */
69
- async function refreshJwt(refreshToken, options = {}) {
70
- const { onEvent, fetch = globalThis.fetch } = options;
71
- try {
72
- onEvent?.({
73
- type: "auth_refreshing",
74
- payload: {
75
- message: "Refreshing your token...",
76
- operation: "token_refresh",
77
- },
78
- timestamp: Date.now(),
79
- });
80
- const response = await fetch(`${ZAPIER_BASE}/oauth/token/`, {
81
- method: "POST",
82
- headers: {
83
- "Content-Type": "application/x-www-form-urlencoded",
84
- [AUTH_MODE_HEADER]: "no",
85
- },
86
- body: new URLSearchParams({
87
- client_id: LOGIN_CLIENT_ID,
88
- refresh_token: refreshToken,
89
- grant_type: "refresh_token",
90
- }),
91
- });
92
- if (!response.ok) {
93
- throw new Error(`Token refresh failed: ${response.status} ${response.statusText}`);
94
- }
95
- const data = await response.json();
96
- // Update stored login data
97
- updateLogin(data);
98
- onEvent?.({
99
- type: "auth_success",
100
- payload: {
101
- message: "Token refreshed successfully",
102
- operation: "token_refresh",
103
- },
104
- timestamp: Date.now(),
105
- });
106
- return data.access_token;
107
- }
108
- catch (error) {
109
- // If refresh fails, clear stored login
110
- clearLogin();
111
- const errorMessage = `Token refresh failed: ${error instanceof Error ? error.message : "Unknown error"}`;
112
- onEvent?.({
113
- type: "auth_error",
114
- payload: {
115
- message: errorMessage,
116
- error: errorMessage,
117
- operation: "token_refresh",
118
- },
119
- timestamp: Date.now(),
120
- });
121
- throw error;
122
- }
123
- }
124
- /**
125
- * Attempts to read a valid JWT token from the CLI configuration.
126
- * Automatically refreshes expired tokens when possible.
127
- * Returns undefined if no valid token is found or refresh fails.
128
- */
129
- async function getTokenFromConfig(options = {}) {
130
- try {
131
- const cfg = getConfig();
132
- const jwt = cfg.get("login_jwt");
133
- const refreshToken = cfg.get("login_refresh_token");
134
- const expiresAt = cfg.get("login_expires_at");
135
- // Check if we have all required fields
136
- if (!jwt || !refreshToken || !expiresAt) {
137
- return undefined;
138
- }
139
- // Check if token is still valid (with 30 second buffer)
140
- if (expiresAt > Date.now() + 30 * 1000) {
141
- return jwt;
142
- }
143
- // Token is expired - attempt to refresh
144
- try {
145
- return await refreshJwt(refreshToken, options);
146
- }
147
- catch {
148
- // If refresh fails, return undefined
149
- return undefined;
150
- }
151
- }
152
- catch {
153
- // If conf is not available or any other error occurs, return undefined
154
- return undefined;
155
- }
156
- }
157
- /**
158
- * Gets the ZAPIER_TOKEN from environment variables.
159
- * Returns undefined if not set.
160
- */
161
- function getTokenFromEnv() {
162
- return process.env.ZAPIER_TOKEN;
163
- }
164
- /**
165
- * Attempts to get a token with the following precedence:
166
- * 1. ZAPIER_TOKEN environment variable
167
- * 2. Valid JWT from CLI configuration (with auto-refresh)
168
- *
169
- * Returns undefined if no valid token is found.
170
- */
171
- async function getTokenFromEnvOrConfig(options = {}) {
172
- // First priority: environment variable
173
- const envToken = getTokenFromEnv();
174
- if (envToken) {
175
- return envToken;
176
- }
177
- // Second priority: CLI configuration (with auto-refresh)
178
- return getTokenFromConfig(options);
179
- }
180
- /**
181
- * Gets the current JWT token, refreshing if necessary.
182
- * Returns undefined if no valid token is available.
183
- */
184
- async function getValidJwt(options = {}) {
185
- try {
186
- const cfg = getConfig();
187
- const jwt = cfg.get("login_jwt");
188
- const refreshToken = cfg.get("login_refresh_token");
189
- const expiresAt = cfg.get("login_expires_at");
190
- // Check if we have all required fields
191
- if (!jwt || !refreshToken || !expiresAt) {
192
- return undefined;
193
- }
194
- // Check if token is still valid (with 30 second buffer)
195
- if (expiresAt > Date.now() + 30 * 1000) {
196
- return jwt;
197
- }
198
- // Token is expired - attempt to refresh
199
- return await refreshJwt(refreshToken, options);
200
- }
201
- catch {
202
- return undefined;
203
- }
204
- }
205
- /**
206
- * Gets the logged-in user information from JWT token.
207
- * Automatically refreshes token if expired.
208
- */
209
- async function getLoggedInUser(options = {}) {
210
- const jwt = await getValidJwt(options);
211
- if (!jwt) {
212
- throw new Error("No valid authentication token available. Please login first.");
213
- }
214
- let decodedJwt = decodeJwtOrThrow(jwt);
215
- if (decodedJwt.payload["sub_type"] == "service") {
216
- decodedJwt = decodeJwtOrThrow(decodedJwt.payload["njwt"]);
217
- }
218
- if (typeof decodedJwt.payload["zap:acc"] !== "string") {
219
- throw new Error("JWT payload does not contain accountId");
220
- }
221
- const accountId = parseInt(decodedJwt.payload["zap:acc"], 10);
222
- if (isNaN(accountId)) {
223
- throw new Error("JWT accountId is not a number");
224
- }
225
- if (decodedJwt.payload["sub_type"] !== "customuser" ||
226
- typeof decodedJwt.payload["sub"] !== "string") {
227
- throw new Error("JWT payload does not contain customUserId");
228
- }
229
- const customUserId = parseInt(decodedJwt.payload["sub"], 10);
230
- if (isNaN(customUserId)) {
231
- throw new Error("JWT customUserId is not a number");
232
- }
233
- const email = decodedJwt.payload["zap:uname"];
234
- if (typeof email !== "string") {
235
- throw new Error("JWT payload does not contain email");
236
- }
237
- return {
238
- accountId,
239
- customUserId,
240
- email,
241
- };
242
- }
243
- /**
244
- * Clears stored login information.
245
- */
246
- function logout(options = {}) {
247
- const { onEvent } = options;
248
- clearLogin();
249
- onEvent?.({
250
- type: "auth_logout",
251
- payload: { message: "Logged out successfully", operation: "logout" },
252
- timestamp: Date.now(),
253
- });
254
- }
255
- /**
256
- * Gets the path to the configuration file.
257
- */
258
- function getConfigPath() {
259
- const cfg = getConfig();
260
- return cfg.path;
261
- }
@@ -1,11 +0,0 @@
1
- import type { BundleCodeOptions } from "./schemas";
2
- /**
3
- * Bundle TypeScript code into executable JavaScript
4
- *
5
- * This function can be used standalone without instantiating a full SDK,
6
- * which enables better tree-shaking in applications that only need this functionality.
7
- *
8
- * @param options - Bundling configuration options
9
- * @returns Promise<string> - Bundled JavaScript code
10
- */
11
- export declare function bundleCode(options: BundleCodeOptions): Promise<string>;
@@ -1,91 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.bundleCode = bundleCode;
37
- /**
38
- * Bundle TypeScript code into executable JavaScript
39
- *
40
- * This function can be used standalone without instantiating a full SDK,
41
- * which enables better tree-shaking in applications that only need this functionality.
42
- *
43
- * @param options - Bundling configuration options
44
- * @returns Promise<string> - Bundled JavaScript code
45
- */
46
- async function bundleCode(options) {
47
- const { input, output, target = "es2020", cjs = false, minify = false, string: returnString = false, } = options;
48
- // Dynamically import esbuild
49
- const { buildSync } = await Promise.resolve().then(() => __importStar(require("esbuild")));
50
- const fs = await Promise.resolve().then(() => __importStar(require("fs")));
51
- const path = await Promise.resolve().then(() => __importStar(require("path")));
52
- // Resolve input path
53
- const resolvedInput = path.resolve(process.cwd(), input);
54
- try {
55
- // Bundle with esbuild
56
- const result = buildSync({
57
- entryPoints: [resolvedInput],
58
- bundle: true,
59
- platform: "node",
60
- target: target,
61
- format: cjs ? "cjs" : "esm",
62
- minify: minify,
63
- write: false,
64
- external: [], // Bundle everything
65
- banner: {
66
- js: "#!/usr/bin/env node",
67
- },
68
- });
69
- if (result.errors.length > 0) {
70
- throw new Error(`Bundle failed: ${result.errors.map((e) => e.text).join(", ")}`);
71
- }
72
- const bundledCode = result.outputFiles?.[0]?.text;
73
- if (!bundledCode) {
74
- throw new Error("No output generated");
75
- }
76
- let finalOutput = bundledCode;
77
- if (returnString) {
78
- // Output as quoted string for node -e using JSON.stringify
79
- finalOutput = JSON.stringify(bundledCode);
80
- }
81
- // Write to file if output path specified
82
- if (output) {
83
- fs.mkdirSync(path.dirname(output), { recursive: true });
84
- fs.writeFileSync(output, finalOutput, "utf8");
85
- }
86
- return finalOutput;
87
- }
88
- catch (error) {
89
- throw new Error(`Bundle failed: ${error instanceof Error ? error.message : "Unknown error"}`);
90
- }
91
- }
@@ -1,27 +0,0 @@
1
- import { bundleCode } from "./index";
2
- export declare const bundleCodeInfo: {
3
- name: string;
4
- inputSchema: import("zod").ZodObject<{
5
- input: import("zod").ZodString;
6
- output: import("zod").ZodOptional<import("zod").ZodString>;
7
- string: import("zod").ZodDefault<import("zod").ZodBoolean>;
8
- minify: import("zod").ZodDefault<import("zod").ZodBoolean>;
9
- target: import("zod").ZodDefault<import("zod").ZodString>;
10
- cjs: import("zod").ZodDefault<import("zod").ZodBoolean>;
11
- }, "strip", import("zod").ZodTypeAny, {
12
- string: boolean;
13
- input: string;
14
- minify: boolean;
15
- target: string;
16
- cjs: boolean;
17
- output?: string | undefined;
18
- }, {
19
- input: string;
20
- string?: boolean | undefined;
21
- output?: string | undefined;
22
- minify?: boolean | undefined;
23
- target?: string | undefined;
24
- cjs?: boolean | undefined;
25
- }>;
26
- implementation: typeof bundleCode;
27
- };
@@ -1,11 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.bundleCodeInfo = void 0;
4
- const index_1 = require("./index");
5
- const schemas_1 = require("./schemas");
6
- // Function registry info - imports both function and schema
7
- exports.bundleCodeInfo = {
8
- name: index_1.bundleCode.name,
9
- inputSchema: schemas_1.BundleCodeSchema,
10
- implementation: index_1.bundleCode,
11
- };