@zapier/zapier-sdk 0.0.1 → 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/actions-sdk.d.ts +47 -0
- package/dist/actions-sdk.js +208 -0
- package/dist/api.d.ts +62 -0
- package/dist/api.js +227 -0
- package/dist/functions/bundleCode.d.ts +18 -0
- package/dist/functions/bundleCode.js +91 -0
- package/dist/functions/generateTypes.d.ts +16 -0
- package/dist/functions/generateTypes.js +271 -0
- package/dist/functions/getAction.d.ts +16 -0
- package/dist/functions/getAction.js +25 -0
- package/dist/functions/getApp.d.ts +14 -0
- package/dist/functions/getApp.js +41 -0
- package/dist/functions/listActions.d.ts +15 -0
- package/dist/functions/listActions.js +127 -0
- package/dist/functions/listApps.d.ts +16 -0
- package/dist/functions/listApps.js +50 -0
- package/dist/functions/listAuths.d.ts +18 -0
- package/dist/functions/listAuths.js +118 -0
- package/dist/functions/listFields.d.ts +18 -0
- package/dist/functions/listFields.js +67 -0
- package/dist/functions/runAction.d.ts +18 -0
- package/dist/functions/runAction.js +156 -0
- package/dist/index.d.ts +12 -3
- package/dist/index.js +24 -5
- package/dist/output-schemas.d.ts +95 -0
- package/dist/output-schemas.js +138 -0
- package/dist/schemas.d.ts +338 -0
- package/dist/schemas.js +336 -0
- package/dist/sdk.d.ts +5 -5
- package/dist/sdk.js +8 -8
- package/dist/types.d.ts +196 -0
- package/dist/types.js +41 -0
- package/package.json +5 -3
- package/src/actions-sdk.ts +356 -0
- package/src/api.ts +361 -0
- package/src/functions/bundleCode.ts +85 -0
- package/src/functions/generateTypes.ts +309 -0
- package/src/functions/getAction.ts +34 -0
- package/src/functions/getApp.ts +47 -0
- package/src/functions/listActions.ts +151 -0
- package/src/functions/listApps.ts +65 -0
- package/src/functions/listAuths.ts +161 -0
- package/src/functions/listFields.ts +95 -0
- package/src/functions/runAction.ts +256 -0
- package/src/index.ts +15 -4
- package/src/output-schemas.ts +196 -0
- package/src/schemas.ts +467 -0
- package/src/sdk.ts +13 -13
- package/src/types.ts +257 -0
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { Integration, Action, ActionExecutionOptions, ActionExecutionResult, ActionField, Authentication, BaseSdkOptions } from "./types";
|
|
2
|
+
import { AppsListOptions, AppsGetOptions, ActionsListOptions, ActionsGetOptions, ActionsRunOptions, AuthsListOptions, AuthsFindOptions, FieldsListOptions, GenerateOptions, BundleOptions } from "./schemas";
|
|
3
|
+
export * from "./schemas";
|
|
4
|
+
export * from "./output-schemas";
|
|
5
|
+
export interface ActionsSdk {
|
|
6
|
+
apps: AppsService;
|
|
7
|
+
actions: ActionsService;
|
|
8
|
+
auths: AuthsService;
|
|
9
|
+
fields: FieldsService;
|
|
10
|
+
generate: GenerateFunction;
|
|
11
|
+
bundle: BundleFunction;
|
|
12
|
+
}
|
|
13
|
+
export interface AppsService {
|
|
14
|
+
list(options?: AppsListOptions): Promise<Integration[]>;
|
|
15
|
+
get(options: AppsGetOptions): Promise<Integration>;
|
|
16
|
+
}
|
|
17
|
+
interface ActionRunner {
|
|
18
|
+
(params: ActionsRunOptions): Promise<ActionExecutionResult>;
|
|
19
|
+
}
|
|
20
|
+
interface ActionProxy {
|
|
21
|
+
[app: string]: {
|
|
22
|
+
[type: string]: {
|
|
23
|
+
[action: string]: (options?: ActionExecutionOptions) => Promise<ActionExecutionResult>;
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
export interface GenerateFunction {
|
|
28
|
+
(options: GenerateOptions): Promise<string>;
|
|
29
|
+
}
|
|
30
|
+
export interface BundleFunction {
|
|
31
|
+
(options: BundleOptions): Promise<string>;
|
|
32
|
+
}
|
|
33
|
+
export interface ActionsService {
|
|
34
|
+
list(options?: ActionsListOptions): Promise<Action[]>;
|
|
35
|
+
get(options: ActionsGetOptions): Promise<Action>;
|
|
36
|
+
run: ActionRunner & ActionProxy;
|
|
37
|
+
}
|
|
38
|
+
export interface AuthsService {
|
|
39
|
+
list(options?: AuthsListOptions): Promise<Authentication[]>;
|
|
40
|
+
find(options: AuthsFindOptions): number;
|
|
41
|
+
}
|
|
42
|
+
export interface FieldsService {
|
|
43
|
+
list(options: FieldsListOptions): Promise<ActionField[]>;
|
|
44
|
+
}
|
|
45
|
+
export interface ActionsSdkOptions extends BaseSdkOptions {
|
|
46
|
+
}
|
|
47
|
+
export declare function createActionsSdk(options?: ActionsSdkOptions): ActionsSdk;
|
|
@@ -0,0 +1,208 @@
|
|
|
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.createActionsSdk = createActionsSdk;
|
|
18
|
+
const api_1 = require("./api");
|
|
19
|
+
const listAuths_1 = require("./functions/listAuths");
|
|
20
|
+
const listApps_1 = require("./functions/listApps");
|
|
21
|
+
const getApp_1 = require("./functions/getApp");
|
|
22
|
+
const listActions_1 = require("./functions/listActions");
|
|
23
|
+
const getAction_1 = require("./functions/getAction");
|
|
24
|
+
const runAction_1 = require("./functions/runAction");
|
|
25
|
+
const listFields_1 = require("./functions/listFields");
|
|
26
|
+
const generateTypes_1 = require("./functions/generateTypes");
|
|
27
|
+
const bundleCode_1 = require("./functions/bundleCode");
|
|
28
|
+
__exportStar(require("./schemas"), exports);
|
|
29
|
+
__exportStar(require("./output-schemas"), exports);
|
|
30
|
+
function createActionsSdk(options = {}) {
|
|
31
|
+
// Auto-load .env files (searches up directory tree)
|
|
32
|
+
try {
|
|
33
|
+
const { findUpSync } = require("find-up");
|
|
34
|
+
const envPath = findUpSync(".env");
|
|
35
|
+
if (envPath) {
|
|
36
|
+
require("dotenv").config({ path: envPath, quiet: true });
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
// Silently fail if dotenv/find-up not available or .env not found
|
|
41
|
+
}
|
|
42
|
+
const { fetch: customFetch = globalThis.fetch, baseUrl = "https://zapier.com", token, authentications = {}, debug = false, } = options;
|
|
43
|
+
// If no token provided, try to get it from environment variable
|
|
44
|
+
const finalToken = token || process.env.ZAPIER_TOKEN;
|
|
45
|
+
// Create the API client
|
|
46
|
+
const api = (0, api_1.createZapierApi)({
|
|
47
|
+
baseUrl,
|
|
48
|
+
token: finalToken,
|
|
49
|
+
debug,
|
|
50
|
+
fetch: customFetch,
|
|
51
|
+
});
|
|
52
|
+
// Create SDK object - we'll populate services after creation to avoid circular dependency
|
|
53
|
+
const sdk = {};
|
|
54
|
+
const appsService = createAppsService({
|
|
55
|
+
api,
|
|
56
|
+
token: finalToken,
|
|
57
|
+
authentications,
|
|
58
|
+
sdk,
|
|
59
|
+
});
|
|
60
|
+
const actionsService = createActionsService({
|
|
61
|
+
api,
|
|
62
|
+
token: finalToken,
|
|
63
|
+
authentications,
|
|
64
|
+
sdk,
|
|
65
|
+
});
|
|
66
|
+
const authsService = createAuthsService({
|
|
67
|
+
api,
|
|
68
|
+
token: finalToken,
|
|
69
|
+
authentications,
|
|
70
|
+
sdk,
|
|
71
|
+
});
|
|
72
|
+
const fieldsService = createFieldsService({
|
|
73
|
+
api,
|
|
74
|
+
token: finalToken,
|
|
75
|
+
authentications,
|
|
76
|
+
sdk,
|
|
77
|
+
});
|
|
78
|
+
// Create root namespace tools
|
|
79
|
+
const generateFunction = async (options) => {
|
|
80
|
+
return (0, generateTypes_1.generateTypes)({ ...options, api, token: finalToken });
|
|
81
|
+
};
|
|
82
|
+
const bundleFunction = async (options) => {
|
|
83
|
+
return (0, bundleCode_1.bundleCode)(options);
|
|
84
|
+
};
|
|
85
|
+
// Populate the SDK object
|
|
86
|
+
sdk.apps = appsService;
|
|
87
|
+
sdk.actions = actionsService;
|
|
88
|
+
sdk.auths = authsService;
|
|
89
|
+
sdk.fields = fieldsService;
|
|
90
|
+
sdk.generate = generateFunction;
|
|
91
|
+
sdk.bundle = bundleFunction;
|
|
92
|
+
// Note: Debug logging for SDK initialization is now handled by the API client
|
|
93
|
+
return sdk;
|
|
94
|
+
}
|
|
95
|
+
function createAppsService(options) {
|
|
96
|
+
const { api, token } = options;
|
|
97
|
+
return {
|
|
98
|
+
async list(options) {
|
|
99
|
+
return (0, listApps_1.listApps)({ ...options, api, token });
|
|
100
|
+
},
|
|
101
|
+
async get(options) {
|
|
102
|
+
return (0, getApp_1.getApp)({ ...options, api, token });
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
function createAuthsService(options) {
|
|
107
|
+
const { api, token, authentications } = options;
|
|
108
|
+
return {
|
|
109
|
+
async list(options) {
|
|
110
|
+
return (0, listAuths_1.listAuths)({ ...options, api, token });
|
|
111
|
+
},
|
|
112
|
+
find(options) {
|
|
113
|
+
if (!authentications) {
|
|
114
|
+
throw new Error(`No authentication configured`);
|
|
115
|
+
}
|
|
116
|
+
const auths = authentications[options.appKey] || [];
|
|
117
|
+
if (auths.length === 0) {
|
|
118
|
+
throw new Error(`No authentication configured for app "${options.appKey}"`);
|
|
119
|
+
}
|
|
120
|
+
if (auths.length > 1) {
|
|
121
|
+
throw new Error(`Multiple authentications found for app "${options.appKey}". Please specify which one to use.`);
|
|
122
|
+
}
|
|
123
|
+
return auths[0].id;
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
function createFieldsService(options) {
|
|
128
|
+
const { api, token } = options;
|
|
129
|
+
return {
|
|
130
|
+
async list(options) {
|
|
131
|
+
return (0, listFields_1.listFields)({ ...options, api, token });
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
function createActionsService(options) {
|
|
136
|
+
const { api, token, authentications } = options;
|
|
137
|
+
// Create the base service with named methods
|
|
138
|
+
const baseService = {
|
|
139
|
+
async list(options) {
|
|
140
|
+
return (0, listActions_1.listActions)({ ...options, api, token });
|
|
141
|
+
},
|
|
142
|
+
async get(options) {
|
|
143
|
+
return (0, getAction_1.getAction)({ ...options, api, token });
|
|
144
|
+
},
|
|
145
|
+
// run will be replaced with function/proxy pattern below
|
|
146
|
+
};
|
|
147
|
+
// Create the run function with proxy capabilities
|
|
148
|
+
const runFunction = async (params) => {
|
|
149
|
+
const { app, type, action, inputs, authId: providedAuthId } = params;
|
|
150
|
+
// Resolve auth ID for this specific app
|
|
151
|
+
let authId = providedAuthId;
|
|
152
|
+
if (!authId && authentications) {
|
|
153
|
+
const auths = authentications[app] || [];
|
|
154
|
+
if (auths.length === 0) {
|
|
155
|
+
throw new Error(`No authentication configured for app "${app}"`);
|
|
156
|
+
}
|
|
157
|
+
if (auths.length > 1) {
|
|
158
|
+
throw new Error(`Multiple authentications found for app "${app}". Please specify which one to use.`);
|
|
159
|
+
}
|
|
160
|
+
authId = auths[0].id;
|
|
161
|
+
}
|
|
162
|
+
// Delegate to standalone runAction function
|
|
163
|
+
return (0, runAction_1.runAction)({
|
|
164
|
+
app,
|
|
165
|
+
type,
|
|
166
|
+
action,
|
|
167
|
+
inputs,
|
|
168
|
+
authId,
|
|
169
|
+
api,
|
|
170
|
+
token,
|
|
171
|
+
});
|
|
172
|
+
};
|
|
173
|
+
// Create proxy wrapper for the run function
|
|
174
|
+
const runWithProxy = new Proxy(runFunction, {
|
|
175
|
+
get(target, prop) {
|
|
176
|
+
if (typeof prop === "string") {
|
|
177
|
+
// Return app-level proxy
|
|
178
|
+
return new Proxy({}, {
|
|
179
|
+
get(_target, actionType) {
|
|
180
|
+
if (typeof actionType !== "string")
|
|
181
|
+
return undefined;
|
|
182
|
+
return new Proxy({}, {
|
|
183
|
+
get(_target, actionKey) {
|
|
184
|
+
if (typeof actionKey !== "string")
|
|
185
|
+
return undefined;
|
|
186
|
+
// Return function that calls the main run function
|
|
187
|
+
return async (options = {}) => {
|
|
188
|
+
return await runFunction({
|
|
189
|
+
app: prop,
|
|
190
|
+
type: actionType, // Cast because proxy string can't be typed as enum
|
|
191
|
+
action: actionKey,
|
|
192
|
+
inputs: options.inputs,
|
|
193
|
+
authId: options.authId,
|
|
194
|
+
});
|
|
195
|
+
};
|
|
196
|
+
},
|
|
197
|
+
});
|
|
198
|
+
},
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
return target[prop];
|
|
202
|
+
},
|
|
203
|
+
});
|
|
204
|
+
// Add the run function/proxy to the base service
|
|
205
|
+
baseService.run = runWithProxy;
|
|
206
|
+
// Return the service with the new run function/proxy
|
|
207
|
+
return baseService;
|
|
208
|
+
}
|
package/dist/api.d.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
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 interface ApiClientOptions {
|
|
9
|
+
baseUrl: string;
|
|
10
|
+
token?: string;
|
|
11
|
+
debug?: boolean;
|
|
12
|
+
fetch?: typeof globalThis.fetch;
|
|
13
|
+
}
|
|
14
|
+
export interface ApiClient {
|
|
15
|
+
get: (path: string, options?: RequestOptions) => Promise<any>;
|
|
16
|
+
post: (path: string, data?: any, options?: RequestOptions) => Promise<any>;
|
|
17
|
+
put: (path: string, data?: any, options?: RequestOptions) => Promise<any>;
|
|
18
|
+
delete: (path: string, options?: RequestOptions) => Promise<any>;
|
|
19
|
+
poll: (path: string, options?: PollOptions) => Promise<any>;
|
|
20
|
+
}
|
|
21
|
+
export interface RequestOptions {
|
|
22
|
+
headers?: Record<string, string>;
|
|
23
|
+
searchParams?: Record<string, string>;
|
|
24
|
+
authRequired?: boolean;
|
|
25
|
+
customErrorHandler?: (response: Response) => Error | undefined;
|
|
26
|
+
}
|
|
27
|
+
export interface PollOptions extends RequestOptions {
|
|
28
|
+
maxAttempts?: number;
|
|
29
|
+
initialDelay?: number;
|
|
30
|
+
maxDelay?: number;
|
|
31
|
+
successStatus?: number;
|
|
32
|
+
pendingStatus?: number;
|
|
33
|
+
resultExtractor?: (response: any) => any;
|
|
34
|
+
}
|
|
35
|
+
export declare function isJwt(token: string): boolean;
|
|
36
|
+
export declare function getAuthorizationHeader(token: string): string;
|
|
37
|
+
export declare function pollUntilComplete(options: {
|
|
38
|
+
fetch: typeof globalThis.fetch;
|
|
39
|
+
url: string;
|
|
40
|
+
headers?: Record<string, string>;
|
|
41
|
+
maxAttempts?: number;
|
|
42
|
+
initialDelay?: number;
|
|
43
|
+
maxDelay?: number;
|
|
44
|
+
successStatus?: number;
|
|
45
|
+
pendingStatus?: number;
|
|
46
|
+
resultExtractor?: (response: any) => any;
|
|
47
|
+
}): Promise<any>;
|
|
48
|
+
export declare function createZapierApi(options: ApiClientOptions): ApiClient;
|
|
49
|
+
export declare function generateRequestId(): string;
|
|
50
|
+
/**
|
|
51
|
+
* Utility function to get or create an API client for standalone functions
|
|
52
|
+
*
|
|
53
|
+
* @param config - Configuration that may include an existing API client
|
|
54
|
+
* @returns ApiClient instance
|
|
55
|
+
*/
|
|
56
|
+
export declare function getOrCreateApiClient(config: {
|
|
57
|
+
baseUrl?: string;
|
|
58
|
+
token?: string;
|
|
59
|
+
api?: ApiClient;
|
|
60
|
+
debug?: boolean;
|
|
61
|
+
fetch?: typeof globalThis.fetch;
|
|
62
|
+
}): ApiClient;
|
package/dist/api.js
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
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.isJwt = isJwt;
|
|
11
|
+
exports.getAuthorizationHeader = getAuthorizationHeader;
|
|
12
|
+
exports.pollUntilComplete = pollUntilComplete;
|
|
13
|
+
exports.createZapierApi = createZapierApi;
|
|
14
|
+
exports.generateRequestId = generateRequestId;
|
|
15
|
+
exports.getOrCreateApiClient = getOrCreateApiClient;
|
|
16
|
+
// ============================================================================
|
|
17
|
+
// Authentication Utilities
|
|
18
|
+
// ============================================================================
|
|
19
|
+
function isJwt(token) {
|
|
20
|
+
// JWT tokens have exactly 3 parts separated by dots
|
|
21
|
+
const parts = token.split(".");
|
|
22
|
+
if (parts.length !== 3) {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
// Each part should be base64url encoded (no padding)
|
|
26
|
+
// Basic validation - each part should be non-empty and contain valid base64url characters
|
|
27
|
+
const base64UrlPattern = /^[A-Za-z0-9_-]+$/;
|
|
28
|
+
return parts.every((part) => part.length > 0 && base64UrlPattern.test(part));
|
|
29
|
+
}
|
|
30
|
+
function getAuthorizationHeader(token) {
|
|
31
|
+
// Check if token is a JWT (has 3 parts separated by dots)
|
|
32
|
+
if (isJwt(token)) {
|
|
33
|
+
return `JWT ${token}`;
|
|
34
|
+
}
|
|
35
|
+
// Default to Bearer for other token types
|
|
36
|
+
return `Bearer ${token}`;
|
|
37
|
+
}
|
|
38
|
+
// ============================================================================
|
|
39
|
+
// Debug Logging
|
|
40
|
+
// ============================================================================
|
|
41
|
+
function createDebugLogger(enabled) {
|
|
42
|
+
if (!enabled) {
|
|
43
|
+
return () => { }; // No-op function when debug is disabled
|
|
44
|
+
}
|
|
45
|
+
return (message, data) => {
|
|
46
|
+
console.log(`[Zapier SDK] ${message}`, data || "");
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
function createDebugFetch(options) {
|
|
50
|
+
const { originalFetch, debugLog } = options;
|
|
51
|
+
return async (input, options) => {
|
|
52
|
+
const startTime = Date.now();
|
|
53
|
+
// Convert input to URL string for logging
|
|
54
|
+
const url = typeof input === "string" ? input : input.toString();
|
|
55
|
+
const method = options?.method || "GET";
|
|
56
|
+
debugLog(`→ ${method} ${url}`, {
|
|
57
|
+
headers: options?.headers,
|
|
58
|
+
body: options?.body ? JSON.parse(options.body) : undefined,
|
|
59
|
+
});
|
|
60
|
+
try {
|
|
61
|
+
const response = await originalFetch(input, options);
|
|
62
|
+
const duration = Date.now() - startTime;
|
|
63
|
+
debugLog(`← ${response.status} ${response.statusText} (${duration}ms)`, {
|
|
64
|
+
url,
|
|
65
|
+
method,
|
|
66
|
+
status: response.status,
|
|
67
|
+
});
|
|
68
|
+
return response;
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
const duration = Date.now() - startTime;
|
|
72
|
+
debugLog(`✖ Request failed (${duration}ms)`, {
|
|
73
|
+
url,
|
|
74
|
+
method,
|
|
75
|
+
error: error instanceof Error ? error.message : error,
|
|
76
|
+
});
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
// ============================================================================
|
|
82
|
+
// Polling Utilities
|
|
83
|
+
// ============================================================================
|
|
84
|
+
async function pollUntilComplete(options) {
|
|
85
|
+
const { fetch, url, headers = {}, maxAttempts = 30, initialDelay = 50, maxDelay = 1000, successStatus = 200, pendingStatus = 202, resultExtractor = (response) => response, } = options;
|
|
86
|
+
let delay = initialDelay;
|
|
87
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
88
|
+
const response = await fetch(url, { headers });
|
|
89
|
+
if (response.status === successStatus) {
|
|
90
|
+
// Success - extract and return results
|
|
91
|
+
const result = await response.json();
|
|
92
|
+
return resultExtractor(result);
|
|
93
|
+
}
|
|
94
|
+
else if (response.status === pendingStatus) {
|
|
95
|
+
// Still processing - wait and retry
|
|
96
|
+
if (attempt < maxAttempts - 1) {
|
|
97
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
98
|
+
delay = Math.min(delay * 2, maxDelay); // Exponential backoff
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
else {
|
|
103
|
+
// Error occurred
|
|
104
|
+
throw new Error(`Request failed: GET ${url} - ${response.status} ${response.statusText}`);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
throw new Error(`Operation timed out after ${maxAttempts} attempts`);
|
|
108
|
+
}
|
|
109
|
+
// ============================================================================
|
|
110
|
+
// API Client Factory
|
|
111
|
+
// ============================================================================
|
|
112
|
+
function createZapierApi(options) {
|
|
113
|
+
const { baseUrl, token, debug = false, fetch: originalFetch = globalThis.fetch, } = options;
|
|
114
|
+
const debugLog = createDebugLogger(debug);
|
|
115
|
+
const fetch = createDebugFetch({ originalFetch, debugLog });
|
|
116
|
+
// Helper to build full URLs
|
|
117
|
+
function buildUrl(path, searchParams) {
|
|
118
|
+
const url = new URL(path, baseUrl);
|
|
119
|
+
if (searchParams) {
|
|
120
|
+
Object.entries(searchParams).forEach(([key, value]) => {
|
|
121
|
+
url.searchParams.set(key, value);
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
return url.toString();
|
|
125
|
+
}
|
|
126
|
+
// Helper to build headers
|
|
127
|
+
function buildHeaders(options = {}) {
|
|
128
|
+
const headers = {
|
|
129
|
+
...options.headers,
|
|
130
|
+
};
|
|
131
|
+
// Add auth header if token provided and not explicitly disabled
|
|
132
|
+
if (token && options.authRequired !== false) {
|
|
133
|
+
headers.Authorization = getAuthorizationHeader(token);
|
|
134
|
+
}
|
|
135
|
+
return headers;
|
|
136
|
+
}
|
|
137
|
+
// Helper to handle responses
|
|
138
|
+
async function handleResponse(response, customErrorHandler) {
|
|
139
|
+
if (!response.ok) {
|
|
140
|
+
// Check for custom error handling first
|
|
141
|
+
if (customErrorHandler) {
|
|
142
|
+
const customError = customErrorHandler(response);
|
|
143
|
+
if (customError) {
|
|
144
|
+
throw customError;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
148
|
+
}
|
|
149
|
+
// Try to parse JSON, fall back to text if that fails
|
|
150
|
+
try {
|
|
151
|
+
return await response.json();
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
return await response.text();
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
// Helper to perform HTTP requests with JSON handling
|
|
158
|
+
async function fetchJson(method, path, data, options = {}) {
|
|
159
|
+
const url = buildUrl(path, options.searchParams);
|
|
160
|
+
const headers = buildHeaders(options);
|
|
161
|
+
// Add Content-Type for JSON requests with body data
|
|
162
|
+
if (data && typeof data === "object") {
|
|
163
|
+
headers["Content-Type"] = "application/json";
|
|
164
|
+
}
|
|
165
|
+
const response = await fetch(url, {
|
|
166
|
+
method,
|
|
167
|
+
headers,
|
|
168
|
+
body: data ? JSON.stringify(data) : undefined,
|
|
169
|
+
});
|
|
170
|
+
return handleResponse(response, options.customErrorHandler);
|
|
171
|
+
}
|
|
172
|
+
return {
|
|
173
|
+
async get(path, options = {}) {
|
|
174
|
+
return fetchJson("GET", path, undefined, options);
|
|
175
|
+
},
|
|
176
|
+
async post(path, data, options = {}) {
|
|
177
|
+
return fetchJson("POST", path, data, options);
|
|
178
|
+
},
|
|
179
|
+
async put(path, data, options = {}) {
|
|
180
|
+
return fetchJson("PUT", path, data, options);
|
|
181
|
+
},
|
|
182
|
+
async delete(path, options = {}) {
|
|
183
|
+
return fetchJson("DELETE", path, undefined, options);
|
|
184
|
+
},
|
|
185
|
+
async poll(path, options = {}) {
|
|
186
|
+
const url = buildUrl(path, options.searchParams);
|
|
187
|
+
const headers = buildHeaders(options);
|
|
188
|
+
return pollUntilComplete({
|
|
189
|
+
fetch,
|
|
190
|
+
url,
|
|
191
|
+
headers,
|
|
192
|
+
maxAttempts: options.maxAttempts,
|
|
193
|
+
initialDelay: options.initialDelay,
|
|
194
|
+
maxDelay: options.maxDelay,
|
|
195
|
+
successStatus: options.successStatus,
|
|
196
|
+
pendingStatus: options.pendingStatus,
|
|
197
|
+
resultExtractor: options.resultExtractor,
|
|
198
|
+
});
|
|
199
|
+
},
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
// ============================================================================
|
|
203
|
+
// Utility Functions
|
|
204
|
+
// ============================================================================
|
|
205
|
+
function generateRequestId() {
|
|
206
|
+
return Math.random().toString(36).substring(2) + Date.now().toString(36);
|
|
207
|
+
}
|
|
208
|
+
// ============================================================================
|
|
209
|
+
// Utility Functions for Standalone Functions
|
|
210
|
+
// ============================================================================
|
|
211
|
+
/**
|
|
212
|
+
* Utility function to get or create an API client for standalone functions
|
|
213
|
+
*
|
|
214
|
+
* @param config - Configuration that may include an existing API client
|
|
215
|
+
* @returns ApiClient instance
|
|
216
|
+
*/
|
|
217
|
+
function getOrCreateApiClient(config) {
|
|
218
|
+
const { baseUrl = "https://zapier.com", token = process.env.ZAPIER_TOKEN, api: providedApi, debug = false, fetch: customFetch, } = config;
|
|
219
|
+
// Use provided API client or create a new one
|
|
220
|
+
return (providedApi ||
|
|
221
|
+
createZapierApi({
|
|
222
|
+
baseUrl,
|
|
223
|
+
token,
|
|
224
|
+
debug,
|
|
225
|
+
fetch: customFetch,
|
|
226
|
+
}));
|
|
227
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export interface BundleCodeOptions {
|
|
2
|
+
input: string;
|
|
3
|
+
output?: string;
|
|
4
|
+
target?: string;
|
|
5
|
+
cjs?: boolean;
|
|
6
|
+
minify?: boolean;
|
|
7
|
+
string?: boolean;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Bundle TypeScript code into executable JavaScript
|
|
11
|
+
*
|
|
12
|
+
* This function can be used standalone without instantiating a full SDK,
|
|
13
|
+
* which enables better tree-shaking in applications that only need this functionality.
|
|
14
|
+
*
|
|
15
|
+
* @param options - Bundling configuration options
|
|
16
|
+
* @returns Promise<string> - Bundled JavaScript code
|
|
17
|
+
*/
|
|
18
|
+
export declare function bundleCode(options: BundleCodeOptions): Promise<string>;
|
|
@@ -0,0 +1,91 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { FunctionConfig } from "../types";
|
|
2
|
+
export interface GenerateTypesOptions extends FunctionConfig {
|
|
3
|
+
appKey: string;
|
|
4
|
+
authId?: number;
|
|
5
|
+
output?: string;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Generate TypeScript types for a specific app
|
|
9
|
+
*
|
|
10
|
+
* This function can be used standalone without instantiating a full SDK,
|
|
11
|
+
* which enables better tree-shaking in applications that only need this functionality.
|
|
12
|
+
*
|
|
13
|
+
* @param options - App key, auth ID, output path, and API configuration options
|
|
14
|
+
* @returns Promise<string> - Generated TypeScript code
|
|
15
|
+
*/
|
|
16
|
+
export declare function generateTypes(options: GenerateTypesOptions): Promise<string>;
|