@zapier/zapier-sdk 0.3.0 → 0.4.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 (158) hide show
  1. package/dist/index.cjs +2001 -0
  2. package/dist/index.d.mts +840 -0
  3. package/dist/index.d.ts +840 -20
  4. package/dist/index.mjs +1955 -0
  5. package/package.json +19 -7
  6. package/src/api/client.ts +84 -16
  7. package/src/api/types.ts +9 -1
  8. package/src/auth.ts +19 -287
  9. package/src/functions/fetch/index.ts +180 -0
  10. package/src/functions/fetch/info.ts +8 -0
  11. package/src/functions/fetch/schemas.ts +46 -0
  12. package/src/functions/findFirstAuthentication/schemas.ts +3 -13
  13. package/src/functions/findUniqueAuthentication/schemas.ts +3 -13
  14. package/src/functions/generateTypes/index.ts +15 -0
  15. package/src/functions/generateTypes/schemas.ts +3 -10
  16. package/src/functions/getAction/schemas.ts +3 -13
  17. package/src/functions/getApp/schemas.ts +2 -13
  18. package/src/functions/getAuthentication/index.ts +0 -1
  19. package/src/functions/getAuthentication/schemas.ts +3 -17
  20. package/src/functions/listActions/schemas.ts +3 -13
  21. package/src/functions/listApps/schemas.ts +2 -13
  22. package/src/functions/listAuthentications/index.ts +0 -1
  23. package/src/functions/listAuthentications/schemas.ts +3 -15
  24. package/src/functions/listFields/schemas.ts +3 -13
  25. package/src/functions/runAction/index.ts +0 -1
  26. package/src/functions/runAction/schemas.ts +6 -15
  27. package/src/index.ts +4 -2
  28. package/src/plugins/apps/index.ts +35 -9
  29. package/src/sdk.ts +20 -22
  30. package/src/types/domain.ts +16 -0
  31. package/src/types/sdk.ts +13 -1
  32. package/tsconfig.json +2 -2
  33. package/tsup.config.ts +21 -0
  34. package/dist/api/auth.d.ts +0 -8
  35. package/dist/api/auth.js +0 -29
  36. package/dist/api/client.d.ts +0 -8
  37. package/dist/api/client.js +0 -119
  38. package/dist/api/debug.d.ts +0 -12
  39. package/dist/api/debug.js +0 -50
  40. package/dist/api/index.d.ts +0 -28
  41. package/dist/api/index.js +0 -52
  42. package/dist/api/polling.d.ts +0 -17
  43. package/dist/api/polling.js +0 -34
  44. package/dist/api/types.d.ts +0 -147
  45. package/dist/api/types.js +0 -9
  46. package/dist/auth.d.ts +0 -59
  47. package/dist/auth.js +0 -261
  48. package/dist/functions/bundleCode/index.d.ts +0 -11
  49. package/dist/functions/bundleCode/index.js +0 -91
  50. package/dist/functions/bundleCode/info.d.ts +0 -27
  51. package/dist/functions/bundleCode/info.js +0 -11
  52. package/dist/functions/bundleCode/schemas.d.ts +0 -27
  53. package/dist/functions/bundleCode/schemas.js +0 -22
  54. package/dist/functions/findFirstAuthentication/index.d.ts +0 -12
  55. package/dist/functions/findFirstAuthentication/index.js +0 -21
  56. package/dist/functions/findFirstAuthentication/info.d.ts +0 -30
  57. package/dist/functions/findFirstAuthentication/info.js +0 -11
  58. package/dist/functions/findFirstAuthentication/schemas.d.ts +0 -42
  59. package/dist/functions/findFirstAuthentication/schemas.js +0 -25
  60. package/dist/functions/findUniqueAuthentication/index.d.ts +0 -13
  61. package/dist/functions/findUniqueAuthentication/index.js +0 -28
  62. package/dist/functions/findUniqueAuthentication/info.d.ts +0 -30
  63. package/dist/functions/findUniqueAuthentication/info.js +0 -11
  64. package/dist/functions/findUniqueAuthentication/schemas.d.ts +0 -42
  65. package/dist/functions/findUniqueAuthentication/schemas.js +0 -25
  66. package/dist/functions/generateTypes/index.d.ts +0 -11
  67. package/dist/functions/generateTypes/index.js +0 -305
  68. package/dist/functions/generateTypes/info.d.ts +0 -21
  69. package/dist/functions/generateTypes/info.js +0 -11
  70. package/dist/functions/generateTypes/schemas.d.ts +0 -30
  71. package/dist/functions/generateTypes/schemas.js +0 -14
  72. package/dist/functions/getAction/index.d.ts +0 -12
  73. package/dist/functions/getAction/index.js +0 -26
  74. package/dist/functions/getAction/info.d.ts +0 -18
  75. package/dist/functions/getAction/info.js +0 -11
  76. package/dist/functions/getAction/schemas.d.ts +0 -30
  77. package/dist/functions/getAction/schemas.js +0 -13
  78. package/dist/functions/getApp/index.d.ts +0 -12
  79. package/dist/functions/getApp/index.js +0 -37
  80. package/dist/functions/getApp/info.d.ts +0 -12
  81. package/dist/functions/getApp/info.js +0 -11
  82. package/dist/functions/getApp/schemas.d.ts +0 -24
  83. package/dist/functions/getApp/schemas.js +0 -11
  84. package/dist/functions/getAuthentication/index.d.ts +0 -13
  85. package/dist/functions/getAuthentication/index.js +0 -38
  86. package/dist/functions/getAuthentication/info.d.ts +0 -12
  87. package/dist/functions/getAuthentication/info.js +0 -11
  88. package/dist/functions/getAuthentication/schemas.d.ts +0 -26
  89. package/dist/functions/getAuthentication/schemas.js +0 -16
  90. package/dist/functions/listActions/index.d.ts +0 -12
  91. package/dist/functions/listActions/index.js +0 -128
  92. package/dist/functions/listActions/info.d.ts +0 -15
  93. package/dist/functions/listActions/info.js +0 -11
  94. package/dist/functions/listActions/schemas.d.ts +0 -27
  95. package/dist/functions/listActions/schemas.js +0 -14
  96. package/dist/functions/listApps/index.d.ts +0 -12
  97. package/dist/functions/listApps/index.js +0 -50
  98. package/dist/functions/listApps/info.d.ts +0 -18
  99. package/dist/functions/listApps/info.js +0 -11
  100. package/dist/functions/listApps/schemas.d.ts +0 -30
  101. package/dist/functions/listApps/schemas.js +0 -15
  102. package/dist/functions/listAuthentications/index.d.ts +0 -12
  103. package/dist/functions/listAuthentications/index.js +0 -131
  104. package/dist/functions/listAuthentications/info.d.ts +0 -30
  105. package/dist/functions/listAuthentications/info.js +0 -11
  106. package/dist/functions/listAuthentications/schemas.d.ts +0 -44
  107. package/dist/functions/listAuthentications/schemas.js +0 -25
  108. package/dist/functions/listFields/index.d.ts +0 -12
  109. package/dist/functions/listFields/index.js +0 -65
  110. package/dist/functions/listFields/info.d.ts +0 -24
  111. package/dist/functions/listFields/info.js +0 -11
  112. package/dist/functions/listFields/schemas.d.ts +0 -36
  113. package/dist/functions/listFields/schemas.js +0 -17
  114. package/dist/functions/runAction/index.d.ts +0 -12
  115. package/dist/functions/runAction/index.js +0 -86
  116. package/dist/functions/runAction/info.d.ts +0 -24
  117. package/dist/functions/runAction/info.js +0 -11
  118. package/dist/functions/runAction/schemas.d.ts +0 -38
  119. package/dist/functions/runAction/schemas.js +0 -15
  120. package/dist/index.js +0 -57
  121. package/dist/plugins/apps/index.d.ts +0 -8
  122. package/dist/plugins/apps/index.js +0 -77
  123. package/dist/plugins/apps/info.d.ts +0 -6
  124. package/dist/plugins/apps/info.js +0 -13
  125. package/dist/plugins/apps/types.d.ts +0 -21
  126. package/dist/plugins/apps/types.js +0 -2
  127. package/dist/resolvers/actionKey.d.ts +0 -8
  128. package/dist/resolvers/actionKey.js +0 -20
  129. package/dist/resolvers/actionType.d.ts +0 -8
  130. package/dist/resolvers/actionType.js +0 -21
  131. package/dist/resolvers/appKey.d.ts +0 -6
  132. package/dist/resolvers/appKey.js +0 -8
  133. package/dist/resolvers/authenticationId.d.ts +0 -8
  134. package/dist/resolvers/authenticationId.js +0 -29
  135. package/dist/resolvers/index.d.ts +0 -39
  136. package/dist/resolvers/index.js +0 -105
  137. package/dist/resolvers/inputs.d.ts +0 -7
  138. package/dist/resolvers/inputs.js +0 -15
  139. package/dist/schema-utils.d.ts +0 -44
  140. package/dist/schema-utils.js +0 -76
  141. package/dist/schemas/Action.d.ts +0 -21
  142. package/dist/schemas/Action.js +0 -31
  143. package/dist/schemas/App.d.ts +0 -19
  144. package/dist/schemas/App.js +0 -32
  145. package/dist/schemas/Auth.d.ts +0 -27
  146. package/dist/schemas/Auth.js +0 -42
  147. package/dist/schemas/Field.d.ts +0 -15
  148. package/dist/schemas/Field.js +0 -25
  149. package/dist/sdk.d.ts +0 -6
  150. package/dist/sdk.js +0 -90
  151. package/dist/types/domain.d.ts +0 -25
  152. package/dist/types/domain.js +0 -21
  153. package/dist/types/events.d.ts +0 -37
  154. package/dist/types/events.js +0 -8
  155. package/dist/types/properties.d.ts +0 -21
  156. package/dist/types/properties.js +0 -52
  157. package/dist/types/sdk.d.ts +0 -24
  158. package/dist/types/sdk.js +0 -2
@@ -2,13 +2,11 @@ import {
2
2
  ActionExecutionOptions,
3
3
  ActionExecutionResult,
4
4
  } from "../../types/domain";
5
- import { type ApiClient } from "../../api";
6
- import { runAction } from "../../functions/runAction";
7
5
  import type { ActionProxy } from "./types";
6
+ import type { ZapierSdk } from "../../types/sdk";
8
7
 
9
8
  export interface AppsPluginOptions {
10
- api: ApiClient;
11
- token?: string;
9
+ sdk: ZapierSdk;
12
10
  }
13
11
 
14
12
  interface AppFactoryOptions {
@@ -25,7 +23,7 @@ function createActionFunction(
25
23
  return async (
26
24
  actionOptions: ActionExecutionOptions = {},
27
25
  ): Promise<ActionExecutionResult> => {
28
- const { api, token } = options;
26
+ const { sdk } = options;
29
27
  const { inputs, authenticationId: providedAuthenticationId } =
30
28
  actionOptions;
31
29
 
@@ -38,15 +36,13 @@ function createActionFunction(
38
36
  );
39
37
  }
40
38
 
41
- // Call runAction with the resolved parameters
42
- return runAction({
39
+ // Call sdk.runAction with the resolved parameters
40
+ return sdk.runAction({
43
41
  appKey,
44
42
  actionType: actionType as any,
45
43
  actionKey,
46
44
  inputs,
47
45
  authenticationId,
48
- api: api,
49
- token,
50
46
  });
51
47
  };
52
48
  }
@@ -57,6 +53,36 @@ function createActionTypeProxy(
57
53
  options: AppsPluginOptions,
58
54
  pinnedAuthId?: number,
59
55
  ) {
56
+ // Special handling for "fetch" action type
57
+ if (actionType === "fetch") {
58
+ return async (fetchOptions: {
59
+ url: string;
60
+ method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS";
61
+ body?: string;
62
+ headers?: Record<string, string>;
63
+ callbackUrl?: string;
64
+ authenticationTemplate?: string;
65
+ authenticationId?: number;
66
+ }) => {
67
+ const { sdk } = options;
68
+
69
+ // Use pinned auth ID first, then provided auth ID
70
+ const authenticationId = pinnedAuthId || fetchOptions.authenticationId;
71
+
72
+ if (!authenticationId) {
73
+ throw new Error(
74
+ `Authentication ID is required for fetch. Either use the factory pattern: sdk.apps.${appKey}({ authenticationId }).fetch(...) or provide authenticationId in the fetch call.`,
75
+ );
76
+ }
77
+
78
+ // Call sdk.fetch with the resolved authenticationId
79
+ return sdk.fetch({
80
+ ...fetchOptions,
81
+ authenticationId,
82
+ });
83
+ };
84
+ }
85
+
60
86
  return new Proxy(
61
87
  {},
62
88
  {
package/src/sdk.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { createZapierApi } from "./api";
2
2
  import { BaseSdkOptions } from "./types/domain";
3
- import { getTokenFromEnvOrConfig } from "./auth";
4
3
  // Import function implementations
5
4
  import { listApps } from "./functions/listApps";
6
5
  import { getApp } from "./functions/getApp";
@@ -14,6 +13,7 @@ import { findUniqueAuthentication } from "./functions/findUniqueAuthentication";
14
13
  import { listFields } from "./functions/listFields";
15
14
  import { generateTypes } from "./functions/generateTypes";
16
15
  import { bundleCode } from "./functions/bundleCode";
16
+ import { fetch } from "./functions/fetch";
17
17
 
18
18
  // Import function registry info objects (only for CLI registry)
19
19
  import { listAppsInfo } from "./functions/listApps/info";
@@ -28,6 +28,7 @@ import { findUniqueAuthenticationInfo } from "./functions/findUniqueAuthenticati
28
28
  import { listFieldsInfo } from "./functions/listFields/info";
29
29
  import { generateTypesInfo } from "./functions/generateTypes/info";
30
30
  import { bundleCodeInfo } from "./functions/bundleCode/info";
31
+ import { fetchInfo } from "./functions/fetch/info";
31
32
 
32
33
  // Function registry as array - uses names from function info objects
33
34
  const functionRegistry = [
@@ -43,10 +44,11 @@ const functionRegistry = [
43
44
  listFieldsInfo,
44
45
  generateTypesInfo,
45
46
  bundleCodeInfo,
47
+ fetchInfo,
46
48
  ];
47
49
 
48
- // Import the properly typed SDK interface
49
- import type { ZapierSdk } from "./types/sdk";
50
+ // Import the properly typed SDK interfaces
51
+ import type { BaseZapierSdk, ZapierSdk } from "./types/sdk";
50
52
 
51
53
  // Import plugin functions
52
54
  import { createAppsPlugin } from "./plugins/apps/index";
@@ -68,30 +70,18 @@ export function createZapierSdk(options: ZapierSdkOptions = {}): ZapierSdk {
68
70
  debug = false,
69
71
  } = options;
70
72
 
71
- // If no explicit token or getToken provided, try env var then CLI config with event callbacks
72
- const resolvedGetToken =
73
- getToken ||
74
- (!token
75
- ? () => getTokenFromEnvOrConfig({ onEvent, fetch: customFetch })
76
- : undefined);
77
-
78
- // Create the API client
73
+ // Create the API client - it will handle token resolution internally
79
74
  const api = createZapierApi({
80
75
  baseUrl,
81
76
  token,
82
- getToken: resolvedGetToken,
77
+ getToken,
83
78
  debug,
84
79
  fetch: customFetch,
80
+ onEvent,
85
81
  });
86
82
 
87
- // Create plugins directly - TypeScript will enforce correct implementation
88
- const appsPlugin = createAppsPlugin({
89
- api,
90
- token,
91
- });
92
-
93
- // Compose final SDK - TypeScript will enforce we have all required properties
94
- const fullSdk: ZapierSdk = {
83
+ // Create base SDK with core functions only - TypeScript will enforce completeness
84
+ const baseSdk: BaseZapierSdk = {
95
85
  // Registry for CLI
96
86
  __registry: functionRegistry,
97
87
 
@@ -111,9 +101,17 @@ export function createZapierSdk(options: ZapierSdkOptions = {}): ZapierSdk {
111
101
  listFields: (options) => listFields({ ...options, api }),
112
102
  generateTypes: (options) => generateTypes({ ...options, api }),
113
103
  bundleCode: (options) => bundleCode(options), // No API config needed
104
+ fetch: (options) => fetch({ ...options, api }),
105
+ };
114
106
 
115
- // Add plugins
116
- apps: appsPlugin,
107
+ // Now extend the base SDK with plugins to create the full SDK
108
+ const fullSdk: ZapierSdk = {
109
+ ...baseSdk,
110
+ // Add plugins - apps plugin gets the base SDK cast as full ZapierSdk type
111
+ // This is safe because by the time plugin functions are called, fullSdk will be complete
112
+ apps: createAppsPlugin({
113
+ sdk: baseSdk as ZapierSdk,
114
+ }),
117
115
  };
118
116
 
119
117
  return fullSdk;
@@ -36,6 +36,22 @@ export interface BaseSdkOptions {
36
36
  debug?: boolean;
37
37
  }
38
38
 
39
+ // Common options shared across all function types
40
+ export interface FunctionOptions {
41
+ /** Base URL for Zapier API */
42
+ baseUrl?: string;
43
+ /** Authentication token */
44
+ token?: string;
45
+ /** Function to dynamically resolve authentication token */
46
+ getToken?: () => Promise<string | undefined>;
47
+ /** Optional pre-instantiated API client */
48
+ api?: any;
49
+ /** Enable debug logging */
50
+ debug?: boolean;
51
+ /** Custom fetch implementation */
52
+ fetch?: typeof globalThis.fetch;
53
+ }
54
+
39
55
  // Error Classes
40
56
  export class ZapierSdkError extends Error {
41
57
  constructor(
package/src/types/sdk.ts CHANGED
@@ -11,6 +11,7 @@ import type { FindUniqueAuthenticationSdkFunction } from "../functions/findUniqu
11
11
  import type { GenerateTypesSdkFunction } from "../functions/generateTypes/schemas";
12
12
  import type { ListAppsSdkFunction } from "../functions/listApps/schemas";
13
13
  import type { BundleCodeSdkFunction } from "../functions/bundleCode/schemas";
14
+ import type { RelayFetchSdkFunction } from "../functions/fetch/schemas";
14
15
 
15
16
  // Plugin interfaces
16
17
  import type { AppsPluginSdkExtension } from "../plugins/apps/types";
@@ -28,7 +29,8 @@ export interface ZapierSdkFunctions
28
29
  FindUniqueAuthenticationSdkFunction,
29
30
  GenerateTypesSdkFunction,
30
31
  ListAppsSdkFunction,
31
- BundleCodeSdkFunction {
32
+ BundleCodeSdkFunction,
33
+ RelayFetchSdkFunction {
32
34
  // All functions now properly typed!
33
35
  }
34
36
 
@@ -37,6 +39,16 @@ export interface ZapierSdkPlugins extends AppsPluginSdkExtension {
37
39
  // All plugins now properly typed!
38
40
  }
39
41
 
42
+ // Base SDK interface with core functions only (no plugins)
43
+ export interface BaseZapierSdk extends ZapierSdkFunctions {
44
+ // Special property for CLI to access schemas
45
+ __registry: Array<{
46
+ name: string;
47
+ inputSchema: any;
48
+ implementation: Function;
49
+ }>;
50
+ }
51
+
40
52
  // Main SDK interface with functions and plugins
41
53
  export interface ZapierSdk extends ZapierSdkFunctions, ZapierSdkPlugins {
42
54
  // Special property for CLI to access schemas
package/tsconfig.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "compilerOptions": {
3
3
  "target": "ES2020",
4
- "module": "CommonJS",
4
+ "module": "ES2020",
5
5
  "declaration": true,
6
6
  "outDir": "./dist",
7
7
  "rootDir": "./src",
@@ -11,7 +11,7 @@
11
11
  "esModuleInterop": true,
12
12
  "skipLibCheck": true,
13
13
  "forceConsistentCasingInFileNames": true,
14
- "moduleResolution": "node"
14
+ "moduleResolution": "bundler"
15
15
  },
16
16
  "include": ["src/**/*"],
17
17
  "exclude": ["dist", "node_modules"]
package/tsup.config.ts ADDED
@@ -0,0 +1,21 @@
1
+ import { defineConfig } from "tsup";
2
+
3
+ export default defineConfig({
4
+ entry: ["src/index.ts"],
5
+ format: ["cjs", "esm"],
6
+ dts: true,
7
+ clean: true,
8
+ splitting: false,
9
+ sourcemap: false,
10
+ // Preserve tree shaking by maintaining individual module exports
11
+ treeshake: true,
12
+ // Output to separate directories for each format
13
+ outDir: "dist",
14
+ outExtension({ format }) {
15
+ return {
16
+ js: format === "cjs" ? ".cjs" : ".mjs",
17
+ };
18
+ },
19
+ // Make the optional CLI login package external so it doesn't cause build issues
20
+ external: ["@zapier/zapier-sdk-cli-login"],
21
+ });
@@ -1,8 +0,0 @@
1
- /**
2
- * Authentication Utilities
3
- *
4
- * This module provides utilities for handling authentication tokens,
5
- * including JWT detection and authorization header generation.
6
- */
7
- export declare function isJwt(token: string): boolean;
8
- export declare function getAuthorizationHeader(token: string): string;
package/dist/api/auth.js DELETED
@@ -1,29 +0,0 @@
1
- "use strict";
2
- /**
3
- * Authentication Utilities
4
- *
5
- * This module provides utilities for handling authentication tokens,
6
- * including JWT detection and authorization header generation.
7
- */
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.isJwt = isJwt;
10
- exports.getAuthorizationHeader = getAuthorizationHeader;
11
- function isJwt(token) {
12
- // JWT tokens have exactly 3 parts separated by dots
13
- const parts = token.split(".");
14
- if (parts.length !== 3) {
15
- return false;
16
- }
17
- // Each part should be base64url encoded (no padding)
18
- // Basic validation - each part should be non-empty and contain valid base64url characters
19
- const base64UrlPattern = /^[A-Za-z0-9_-]+$/;
20
- return parts.every((part) => part.length > 0 && base64UrlPattern.test(part));
21
- }
22
- function getAuthorizationHeader(token) {
23
- // Check if token is a JWT (has 3 parts separated by dots)
24
- if (isJwt(token)) {
25
- return `JWT ${token}`;
26
- }
27
- // Default to Bearer for other token types
28
- return `Bearer ${token}`;
29
- }
@@ -1,8 +0,0 @@
1
- /**
2
- * API Client Implementation
3
- *
4
- * This module contains the core API client implementation, including
5
- * HTTP method handlers, response processing, and client factory functions.
6
- */
7
- import type { ApiClient, ApiClientOptions } from "./types";
8
- export declare function createZapierApi(options: ApiClientOptions): ApiClient;
@@ -1,119 +0,0 @@
1
- "use strict";
2
- /**
3
- * API Client Implementation
4
- *
5
- * This module contains the core API client implementation, including
6
- * HTTP method handlers, response processing, and client factory functions.
7
- */
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.createZapierApi = createZapierApi;
10
- const auth_1 = require("./auth");
11
- const debug_1 = require("./debug");
12
- const polling_1 = require("./polling");
13
- const auth_2 = require("../auth");
14
- function createZapierApi(options) {
15
- const { baseUrl, token, getToken, debug = false, fetch: originalFetch = globalThis.fetch, } = options;
16
- const debugLog = (0, debug_1.createDebugLogger)(debug);
17
- const fetch = (0, debug_1.createDebugFetch)({ originalFetch, debugLog });
18
- // Helper to build full URLs
19
- function buildUrl(path, searchParams) {
20
- const url = new URL(path, baseUrl);
21
- if (searchParams) {
22
- Object.entries(searchParams).forEach(([key, value]) => {
23
- url.searchParams.set(key, value);
24
- });
25
- }
26
- return url.toString();
27
- }
28
- // Helper to build headers
29
- async function buildHeaders(options = {}) {
30
- const headers = {
31
- ...options.headers,
32
- };
33
- // Add auth header if token provided and not explicitly disabled
34
- if (options.authRequired !== false) {
35
- let resolvedToken = token;
36
- // Token resolution precedence: explicit token > getToken() > env var
37
- if (!resolvedToken && getToken) {
38
- resolvedToken = await getToken();
39
- }
40
- if (!resolvedToken) {
41
- resolvedToken = (0, auth_2.getTokenFromEnv)();
42
- }
43
- if (resolvedToken) {
44
- headers.Authorization = (0, auth_1.getAuthorizationHeader)(resolvedToken);
45
- }
46
- }
47
- return headers;
48
- }
49
- // Helper to handle responses
50
- async function handleResponse(response, customErrorHandler) {
51
- if (!response.ok) {
52
- // Check for custom error handling first
53
- if (customErrorHandler) {
54
- const customError = customErrorHandler(response);
55
- if (customError) {
56
- throw customError;
57
- }
58
- }
59
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
60
- }
61
- // Try to parse JSON, fall back to text if that fails
62
- try {
63
- return await response.json();
64
- }
65
- catch {
66
- return await response.text();
67
- }
68
- }
69
- // Helper to perform HTTP requests with JSON handling
70
- async function fetchJson(method, path, data, options = {}) {
71
- const url = buildUrl(path, options.searchParams);
72
- const headers = await buildHeaders(options);
73
- // Add Content-Type for JSON requests with body data
74
- if (data && typeof data === "object") {
75
- headers["Content-Type"] = "application/json";
76
- }
77
- const response = await fetch(url, {
78
- method,
79
- headers,
80
- body: data ? JSON.stringify(data) : undefined,
81
- });
82
- return handleResponse(response, options.customErrorHandler);
83
- }
84
- return {
85
- async get(path, options = {}) {
86
- return fetchJson("GET", path, undefined, options);
87
- },
88
- async post(path, data, options = {}) {
89
- return fetchJson("POST", path, data, options);
90
- },
91
- async put(path, data, options = {}) {
92
- return fetchJson("PUT", path, data, options);
93
- },
94
- async delete(path, options = {}) {
95
- return fetchJson("DELETE", path, undefined, options);
96
- },
97
- async poll(path, options = {}) {
98
- const url = buildUrl(path, options.searchParams);
99
- const headers = await buildHeaders(options);
100
- return (0, polling_1.pollUntilComplete)({
101
- fetch,
102
- url,
103
- headers,
104
- maxAttempts: options.maxAttempts,
105
- initialDelay: options.initialDelay,
106
- maxDelay: options.maxDelay,
107
- successStatus: options.successStatus,
108
- pendingStatus: options.pendingStatus,
109
- resultExtractor: options.resultExtractor,
110
- });
111
- },
112
- requireAuthTo(operation) {
113
- // Check if any authentication method is available
114
- if (!token && !getToken && !(0, auth_2.getTokenFromEnv)()) {
115
- throw new Error(`Authentication token is required to ${operation}. Please provide token in options or set ZAPIER_TOKEN environment variable.`);
116
- }
117
- },
118
- };
119
- }
@@ -1,12 +0,0 @@
1
- /**
2
- * Debug Logging Utilities
3
- *
4
- * This module provides debug logging capabilities for API requests and responses,
5
- * including request timing and detailed logging of HTTP interactions.
6
- */
7
- import type { DebugLogger } from "./types";
8
- export declare function createDebugLogger(enabled: boolean): DebugLogger;
9
- export declare function createDebugFetch(options: {
10
- originalFetch: typeof globalThis.fetch;
11
- debugLog: DebugLogger;
12
- }): (input: RequestInfo | URL, options?: RequestInit) => Promise<Response>;
package/dist/api/debug.js DELETED
@@ -1,50 +0,0 @@
1
- "use strict";
2
- /**
3
- * Debug Logging Utilities
4
- *
5
- * This module provides debug logging capabilities for API requests and responses,
6
- * including request timing and detailed logging of HTTP interactions.
7
- */
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.createDebugLogger = createDebugLogger;
10
- exports.createDebugFetch = createDebugFetch;
11
- function createDebugLogger(enabled) {
12
- if (!enabled) {
13
- return () => { }; // No-op function when debug is disabled
14
- }
15
- return (message, data) => {
16
- console.log(`[Zapier SDK] ${message}`, data || "");
17
- };
18
- }
19
- function createDebugFetch(options) {
20
- const { originalFetch, debugLog } = options;
21
- return async (input, options) => {
22
- const startTime = Date.now();
23
- // Convert input to URL string for logging
24
- const url = typeof input === "string" ? input : input.toString();
25
- const method = options?.method || "GET";
26
- debugLog(`→ ${method} ${url}`, {
27
- headers: options?.headers,
28
- body: options?.body ? JSON.parse(options.body) : undefined,
29
- });
30
- try {
31
- const response = await originalFetch(input, options);
32
- const duration = Date.now() - startTime;
33
- debugLog(`← ${response.status} ${response.statusText} (${duration}ms)`, {
34
- url,
35
- method,
36
- status: response.status,
37
- });
38
- return response;
39
- }
40
- catch (error) {
41
- const duration = Date.now() - startTime;
42
- debugLog(`✖ Request failed (${duration}ms)`, {
43
- url,
44
- method,
45
- error: error instanceof Error ? error.message : error,
46
- });
47
- throw error;
48
- }
49
- };
50
- }
@@ -1,28 +0,0 @@
1
- /**
2
- * Zapier API Client Module
3
- *
4
- * This module provides a centralized API layer for all HTTP interactions
5
- * with Zapier's various APIs. It handles authentication, error handling,
6
- * polling, and provides consistent patterns across all services.
7
- */
8
- export type { ApiClient, ApiClientOptions, RequestOptions, PollOptions, DebugLogger, Integration, Action, Trigger, Field, Choice, ActionExecutionResult, ActionField, ActionFieldChoice, NeedsRequest, NeedsResponse, Authentication, AuthenticationsResponse, } from "./types";
9
- import type { ApiClient } from "./types";
10
- export { isJwt, getAuthorizationHeader } from "./auth";
11
- export { createDebugLogger, createDebugFetch } from "./debug";
12
- export { pollUntilComplete } from "./polling";
13
- export { createZapierApi } from "./client";
14
- export declare function generateRequestId(): string;
15
- /**
16
- * Utility function to get or create an API client for standalone functions
17
- *
18
- * @param config - Configuration that may include an existing API client
19
- * @returns ApiClient instance
20
- */
21
- export declare function getOrCreateApiClient(config: {
22
- baseUrl?: string;
23
- token?: string;
24
- getToken?: () => Promise<string | undefined>;
25
- api?: ApiClient;
26
- debug?: boolean;
27
- fetch?: typeof globalThis.fetch;
28
- }): ApiClient;
package/dist/api/index.js DELETED
@@ -1,52 +0,0 @@
1
- "use strict";
2
- /**
3
- * Zapier API Client Module
4
- *
5
- * This module provides a centralized API layer for all HTTP interactions
6
- * with Zapier's various APIs. It handles authentication, error handling,
7
- * polling, and provides consistent patterns across all services.
8
- */
9
- Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.createZapierApi = exports.pollUntilComplete = exports.createDebugFetch = exports.createDebugLogger = exports.getAuthorizationHeader = exports.isJwt = void 0;
11
- exports.generateRequestId = generateRequestId;
12
- exports.getOrCreateApiClient = getOrCreateApiClient;
13
- // Re-export authentication utilities
14
- var auth_1 = require("./auth");
15
- Object.defineProperty(exports, "isJwt", { enumerable: true, get: function () { return auth_1.isJwt; } });
16
- Object.defineProperty(exports, "getAuthorizationHeader", { enumerable: true, get: function () { return auth_1.getAuthorizationHeader; } });
17
- // Re-export debug utilities
18
- var debug_1 = require("./debug");
19
- Object.defineProperty(exports, "createDebugLogger", { enumerable: true, get: function () { return debug_1.createDebugLogger; } });
20
- Object.defineProperty(exports, "createDebugFetch", { enumerable: true, get: function () { return debug_1.createDebugFetch; } });
21
- // Re-export polling utilities
22
- var polling_1 = require("./polling");
23
- Object.defineProperty(exports, "pollUntilComplete", { enumerable: true, get: function () { return polling_1.pollUntilComplete; } });
24
- // Re-export the main client factory
25
- var client_1 = require("./client");
26
- Object.defineProperty(exports, "createZapierApi", { enumerable: true, get: function () { return client_1.createZapierApi; } });
27
- // Import for local use
28
- const client_2 = require("./client");
29
- // Utility Functions
30
- function generateRequestId() {
31
- return Math.random().toString(36).substring(2) + Date.now().toString(36);
32
- }
33
- /**
34
- * Utility function to get or create an API client for standalone functions
35
- *
36
- * @param config - Configuration that may include an existing API client
37
- * @returns ApiClient instance
38
- */
39
- function getOrCreateApiClient(config) {
40
- const { baseUrl = "https://zapier.com", token, getToken, api: providedApi, debug = false, fetch: customFetch, } = config;
41
- // Use provided API client or create a new one
42
- if (providedApi) {
43
- return providedApi;
44
- }
45
- return (0, client_2.createZapierApi)({
46
- baseUrl,
47
- token,
48
- getToken,
49
- debug,
50
- fetch: customFetch,
51
- });
52
- }
@@ -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
- }