@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
package/dist/index.mjs ADDED
@@ -0,0 +1,1914 @@
1
+ import { z } from 'zod';
2
+
3
+ // src/types/domain.ts
4
+ var ZapierSdkError = class extends Error {
5
+ constructor(message, code) {
6
+ super(message);
7
+ this.code = code;
8
+ this.name = "ZapierSdkError";
9
+ }
10
+ };
11
+ var AppNotFoundError = class extends ZapierSdkError {
12
+ constructor(appKey) {
13
+ super(`App "${appKey}" not found`);
14
+ this.name = "AppNotFoundError";
15
+ this.code = "APP_NOT_FOUND";
16
+ this.appKey = appKey;
17
+ }
18
+ };
19
+ function withFormatter(schema, formatMeta) {
20
+ schema._def.formatMeta = formatMeta;
21
+ return schema;
22
+ }
23
+ function withOutputSchema(inputSchema, outputSchema) {
24
+ inputSchema._def.outputSchema = outputSchema;
25
+ return inputSchema;
26
+ }
27
+ function withPositional(schema) {
28
+ schema._def.positionalMeta = { positional: true };
29
+ return schema;
30
+ }
31
+ function isPositional(schema) {
32
+ if (schema._def.positionalMeta?.positional) {
33
+ return true;
34
+ }
35
+ if (schema instanceof z.ZodOptional) {
36
+ return isPositional(schema._def.innerType);
37
+ }
38
+ if (schema instanceof z.ZodDefault) {
39
+ return isPositional(schema._def.innerType);
40
+ }
41
+ return false;
42
+ }
43
+
44
+ // src/types/properties.ts
45
+ var AppKeyPropertySchema = withPositional(
46
+ z.string().min(1).describe("App slug (e.g., 'slack', 'github')")
47
+ );
48
+ var ActionTypePropertySchema = z.enum([
49
+ "read",
50
+ "read_bulk",
51
+ "write",
52
+ "run",
53
+ "search",
54
+ "search_or_write",
55
+ "search_and_write",
56
+ "filter"
57
+ ]).describe("Action type that matches the action's defined type");
58
+ var ActionKeyPropertySchema = z.string().min(1).describe("Action key to execute");
59
+ var AuthenticationIdPropertySchema = z.number().int().describe("Authentication ID to use for this action");
60
+ var InputsPropertySchema = z.record(z.any()).describe("Input parameters for the action");
61
+ var LimitPropertySchema = z.number().int().min(1).max(1e3).default(50).describe("Maximum number of items to return");
62
+ var OffsetPropertySchema = z.number().int().min(0).default(0).describe("Number of items to skip for pagination");
63
+ var OutputPropertySchema = z.string().describe("Output file path");
64
+ var DebugPropertySchema = z.boolean().default(false).describe("Enable debug logging");
65
+ var ParamsPropertySchema = z.record(z.any()).describe("Additional parameters");
66
+
67
+ // src/plugins/apps/index.ts
68
+ function createActionFunction(appKey, actionType, actionKey, options, pinnedAuthId) {
69
+ return async (actionOptions = {}) => {
70
+ const { sdk } = options;
71
+ const { inputs, authenticationId: providedAuthenticationId } = actionOptions;
72
+ const authenticationId = pinnedAuthId || providedAuthenticationId;
73
+ if (!authenticationId) {
74
+ throw new Error(
75
+ `Authentication ID is required. Either use the factory pattern: sdk.apps.${appKey}({ authenticationId }) or provide authenticationId in the action call.`
76
+ );
77
+ }
78
+ return sdk.runAction({
79
+ appKey,
80
+ actionType,
81
+ actionKey,
82
+ inputs,
83
+ authenticationId
84
+ });
85
+ };
86
+ }
87
+ function createActionTypeProxy(appKey, actionType, options, pinnedAuthId) {
88
+ if (actionType === "fetch") {
89
+ return async (url, init) => {
90
+ const { sdk } = options;
91
+ const authenticationId = pinnedAuthId || init?.authenticationId;
92
+ if (!authenticationId) {
93
+ throw new Error(
94
+ `Authentication ID is required for fetch. Either use the factory pattern: sdk.apps.${appKey}({ authenticationId }).fetch(...) or provide authenticationId in the fetch call.`
95
+ );
96
+ }
97
+ return sdk.fetch(url, {
98
+ ...init,
99
+ authenticationId
100
+ });
101
+ };
102
+ }
103
+ return new Proxy(
104
+ {},
105
+ {
106
+ get(_, actionKey) {
107
+ if (typeof actionKey === "string") {
108
+ return createActionFunction(
109
+ appKey,
110
+ actionType,
111
+ actionKey,
112
+ options,
113
+ pinnedAuthId
114
+ );
115
+ }
116
+ return void 0;
117
+ }
118
+ }
119
+ );
120
+ }
121
+ function createPinnedAppProxy(appKey, options, pinnedAuthId) {
122
+ return new Proxy(
123
+ {},
124
+ {
125
+ get(_, actionType) {
126
+ if (typeof actionType === "string") {
127
+ return createActionTypeProxy(
128
+ appKey,
129
+ actionType,
130
+ options,
131
+ pinnedAuthId
132
+ );
133
+ }
134
+ return void 0;
135
+ }
136
+ }
137
+ );
138
+ }
139
+ function createAppProxy(appKey, options) {
140
+ const appFactory = (factoryOptions) => {
141
+ return createPinnedAppProxy(
142
+ appKey,
143
+ options,
144
+ factoryOptions.authenticationId
145
+ );
146
+ };
147
+ return new Proxy(appFactory, {
148
+ get(_, actionType) {
149
+ if (typeof actionType === "string") {
150
+ return createActionTypeProxy(appKey, actionType, options);
151
+ }
152
+ return void 0;
153
+ }
154
+ });
155
+ }
156
+ function createAppsProxy(options) {
157
+ const appsProxy = new Proxy({}, {
158
+ get(_, prop) {
159
+ if (typeof prop === "string") {
160
+ return createAppProxy(prop, options);
161
+ }
162
+ return void 0;
163
+ }
164
+ });
165
+ return appsProxy;
166
+ }
167
+ function createAppsPlugin(options) {
168
+ return createAppsProxy(options);
169
+ }
170
+
171
+ // src/plugins/fetch/index.ts
172
+ function createFetchPlugin(options) {
173
+ const { sdk } = options;
174
+ return async function fetch(url, init) {
175
+ const {
176
+ authenticationId,
177
+ callbackUrl,
178
+ authenticationTemplate,
179
+ ...fetchInit
180
+ } = init || {};
181
+ return sdk.request({
182
+ url: url.toString(),
183
+ method: fetchInit.method,
184
+ body: fetchInit.body,
185
+ headers: fetchInit.headers,
186
+ authenticationId,
187
+ callbackUrl,
188
+ authenticationTemplate
189
+ });
190
+ };
191
+ }
192
+
193
+ // src/auth.ts
194
+ function getTokenFromEnv() {
195
+ return process.env.ZAPIER_TOKEN;
196
+ }
197
+ async function getTokenFromCliLogin(options = {}) {
198
+ try {
199
+ const { getToken } = await import('@zapier/zapier-sdk-cli-login');
200
+ return await getToken(options);
201
+ } catch {
202
+ return void 0;
203
+ }
204
+ }
205
+ async function getTokenFromEnvOrConfig(options = {}) {
206
+ const envToken = getTokenFromEnv();
207
+ if (envToken) {
208
+ return envToken;
209
+ }
210
+ return getTokenFromCliLogin(options);
211
+ }
212
+
213
+ // src/resolvers/appKey.ts
214
+ var appKeyResolver = {
215
+ type: "static",
216
+ inputType: "text",
217
+ placeholder: "Enter app slug (e.g., 'slack', 'github')"
218
+ };
219
+
220
+ // src/resolvers/actionType.ts
221
+ var actionTypeResolver = {
222
+ type: "dynamic",
223
+ depends: ["appKey"],
224
+ fetch: async (sdk, resolvedParams) => {
225
+ const actions = await sdk.listActions({ appKey: resolvedParams.appKey });
226
+ const types = [...new Set(actions.map((action) => action.type))];
227
+ return types.map((type) => ({ key: type, name: type }));
228
+ },
229
+ prompt: (types) => ({
230
+ type: "list",
231
+ name: "actionType",
232
+ message: "Select action type:",
233
+ choices: types.map((type) => ({
234
+ name: type.name,
235
+ value: type.key
236
+ }))
237
+ })
238
+ };
239
+
240
+ // src/resolvers/actionKey.ts
241
+ var actionKeyResolver = {
242
+ type: "dynamic",
243
+ depends: ["appKey", "actionType"],
244
+ fetch: async (sdk, resolvedParams) => {
245
+ const actions = await sdk.listActions({ appKey: resolvedParams.appKey });
246
+ return actions.filter(
247
+ (action) => action.type === resolvedParams.actionType
248
+ );
249
+ },
250
+ prompt: (actions) => ({
251
+ type: "list",
252
+ name: "actionKey",
253
+ message: "Select action:",
254
+ choices: actions.map((action) => ({
255
+ name: `${action.name || action.key} - ${action.description || "No description"}`,
256
+ value: action.key
257
+ }))
258
+ })
259
+ };
260
+
261
+ // src/resolvers/authenticationId.ts
262
+ var authenticationIdResolver = {
263
+ type: "dynamic",
264
+ depends: ["appKey"],
265
+ fetch: async (sdk, resolvedParams) => {
266
+ return await sdk.listAuthentications({
267
+ appKey: resolvedParams.appKey,
268
+ limit: 1e3
269
+ });
270
+ },
271
+ prompt: (auths, params) => ({
272
+ type: "list",
273
+ name: "authenticationId",
274
+ message: `Select authentication for ${params.appKey}:`,
275
+ choices: [
276
+ ...auths.map((auth) => ({
277
+ name: `${auth.title || auth.label || "Authentication"} (ID: ${auth.id})`,
278
+ value: auth.id
279
+ })),
280
+ {
281
+ name: "\u2197 Skip authentication (may fail)",
282
+ value: null
283
+ }
284
+ ]
285
+ })
286
+ };
287
+
288
+ // src/resolvers/inputs.ts
289
+ var inputsResolver = {
290
+ type: "fields",
291
+ depends: ["appKey", "actionKey", "actionType", "authenticationId"],
292
+ fetch: async (sdk, resolvedParams) => {
293
+ return await sdk.listFields({
294
+ appKey: resolvedParams.appKey,
295
+ actionKey: resolvedParams.actionKey,
296
+ actionType: resolvedParams.actionType,
297
+ authenticationId: resolvedParams.authenticationId
298
+ });
299
+ }
300
+ };
301
+
302
+ // src/resolvers/index.ts
303
+ var resolverRegistry = {
304
+ appKey: appKeyResolver,
305
+ actionType: actionTypeResolver,
306
+ actionKey: actionKeyResolver,
307
+ authenticationId: authenticationIdResolver,
308
+ inputs: inputsResolver
309
+ };
310
+ function getResolver(name) {
311
+ return resolverRegistry[name];
312
+ }
313
+ function getResolversForMissingParams(missingParams) {
314
+ const resolvers = {};
315
+ for (const param of missingParams) {
316
+ const resolver = resolverRegistry[param];
317
+ if (resolver) {
318
+ resolvers[param] = resolver;
319
+ }
320
+ }
321
+ return resolvers;
322
+ }
323
+ function hasResolver(paramName) {
324
+ return paramName in resolverRegistry;
325
+ }
326
+ function getResolvableParams() {
327
+ return Object.keys(resolverRegistry);
328
+ }
329
+ function getResolutionOrder(paramName, resolved = /* @__PURE__ */ new Set()) {
330
+ const resolver = getResolver(paramName);
331
+ if (!resolver || resolver.type === "static") {
332
+ return [paramName];
333
+ }
334
+ const order = [];
335
+ if ("depends" in resolver && resolver.depends) {
336
+ for (const dependency of resolver.depends) {
337
+ if (!resolved.has(dependency)) {
338
+ order.push(...getResolutionOrder(dependency, resolved));
339
+ resolved.add(dependency);
340
+ }
341
+ }
342
+ }
343
+ if (!resolved.has(paramName)) {
344
+ order.push(paramName);
345
+ resolved.add(paramName);
346
+ }
347
+ return order;
348
+ }
349
+ function getResolutionOrderForParams(paramNames) {
350
+ const resolved = /* @__PURE__ */ new Set();
351
+ const order = [];
352
+ for (const paramName of paramNames) {
353
+ const paramOrder = getResolutionOrder(paramName, resolved);
354
+ for (const param of paramOrder) {
355
+ if (!order.includes(param)) {
356
+ order.push(param);
357
+ }
358
+ }
359
+ }
360
+ return order;
361
+ }
362
+
363
+ // src/api/auth.ts
364
+ function isJwt(token) {
365
+ const parts = token.split(".");
366
+ if (parts.length !== 3) {
367
+ return false;
368
+ }
369
+ const base64UrlPattern = /^[A-Za-z0-9_-]+$/;
370
+ return parts.every((part) => part.length > 0 && base64UrlPattern.test(part));
371
+ }
372
+ function getAuthorizationHeader(token) {
373
+ if (isJwt(token)) {
374
+ return `JWT ${token}`;
375
+ }
376
+ return `Bearer ${token}`;
377
+ }
378
+
379
+ // src/api/debug.ts
380
+ function createDebugLogger(enabled) {
381
+ if (!enabled) {
382
+ return () => {
383
+ };
384
+ }
385
+ return (message, data) => {
386
+ console.log(`[Zapier SDK] ${message}`, data || "");
387
+ };
388
+ }
389
+ function createDebugFetch(options) {
390
+ const { originalFetch, debugLog } = options;
391
+ return async (input, options2) => {
392
+ const startTime = Date.now();
393
+ const url = typeof input === "string" ? input : input.toString();
394
+ const method = options2?.method || "GET";
395
+ debugLog(`\u2192 ${method} ${url}`, {
396
+ headers: options2?.headers,
397
+ body: options2?.body ? JSON.parse(options2.body) : void 0
398
+ });
399
+ try {
400
+ const response = await originalFetch(input, options2);
401
+ const duration = Date.now() - startTime;
402
+ debugLog(`\u2190 ${response.status} ${response.statusText} (${duration}ms)`, {
403
+ url,
404
+ method,
405
+ status: response.status
406
+ });
407
+ return response;
408
+ } catch (error) {
409
+ const duration = Date.now() - startTime;
410
+ debugLog(`\u2716 Request failed (${duration}ms)`, {
411
+ url,
412
+ method,
413
+ error: error instanceof Error ? error.message : error
414
+ });
415
+ throw error;
416
+ }
417
+ };
418
+ }
419
+
420
+ // src/api/polling.ts
421
+ async function pollUntilComplete(options) {
422
+ const {
423
+ fetchPoll,
424
+ maxAttempts = 30,
425
+ initialDelay = 50,
426
+ maxDelay = 1e3,
427
+ successStatus = 200,
428
+ pendingStatus = 202,
429
+ resultExtractor = (response) => response
430
+ } = options;
431
+ let delay = initialDelay;
432
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
433
+ const response = await fetchPoll();
434
+ if (response.status === successStatus) {
435
+ const result = await response.json();
436
+ return resultExtractor(result);
437
+ } else if (response.status === pendingStatus) {
438
+ if (attempt < maxAttempts - 1) {
439
+ await new Promise((resolve) => setTimeout(resolve, delay));
440
+ delay = Math.min(delay * 2, maxDelay);
441
+ continue;
442
+ }
443
+ } else {
444
+ throw new Error(
445
+ `Poll request failed: ${response.status} ${response.statusText}`
446
+ );
447
+ }
448
+ }
449
+ throw new Error(`Operation timed out after ${maxAttempts} attempts`);
450
+ }
451
+
452
+ // src/api/client.ts
453
+ var SUBDOMAIN_PREFIXES = {
454
+ relay: {
455
+ authHeader: "X-Relay-Authorization"
456
+ }
457
+ };
458
+ function createZapierApi(options) {
459
+ const {
460
+ baseUrl,
461
+ token,
462
+ getToken,
463
+ debug = false,
464
+ fetch: originalFetch = globalThis.fetch,
465
+ onEvent
466
+ } = options;
467
+ const debugLog = createDebugLogger(debug);
468
+ const fetch = createDebugFetch({ originalFetch, debugLog });
469
+ function buildUrl(path, searchParams) {
470
+ const pathSegments = path.split("/").filter(Boolean);
471
+ let finalBaseUrl = baseUrl;
472
+ let subdomainConfig;
473
+ if (pathSegments.length > 0 && pathSegments[0] in SUBDOMAIN_PREFIXES) {
474
+ const subdomain = pathSegments[0];
475
+ subdomainConfig = SUBDOMAIN_PREFIXES[subdomain];
476
+ const baseUrlObj = new URL(baseUrl);
477
+ baseUrlObj.hostname = `${subdomain}.${baseUrlObj.hostname}`;
478
+ finalBaseUrl = baseUrlObj.toString();
479
+ path = "/" + pathSegments.slice(1).join("/");
480
+ }
481
+ const url = new URL(path, finalBaseUrl);
482
+ if (searchParams) {
483
+ Object.entries(searchParams).forEach(([key, value]) => {
484
+ url.searchParams.set(key, value);
485
+ });
486
+ }
487
+ return { url: url.toString(), subdomainConfig };
488
+ }
489
+ async function buildHeaders(options2 = {}, subdomainConfig) {
490
+ const headers = {
491
+ ...options2.headers
492
+ };
493
+ if (options2.authRequired !== false) {
494
+ let resolvedToken = token;
495
+ if (!resolvedToken && getToken) {
496
+ resolvedToken = await getToken();
497
+ }
498
+ if (!resolvedToken) {
499
+ resolvedToken = await getTokenFromEnvOrConfig({
500
+ onEvent,
501
+ fetch: originalFetch
502
+ });
503
+ }
504
+ if (resolvedToken) {
505
+ const authHeaderName = subdomainConfig?.authHeader || "Authorization";
506
+ headers[authHeaderName] = getAuthorizationHeader(resolvedToken);
507
+ }
508
+ }
509
+ return headers;
510
+ }
511
+ async function handleResponse(response, customErrorHandler, hadAuthToken) {
512
+ if (!response.ok) {
513
+ if (customErrorHandler) {
514
+ const customError = customErrorHandler(response);
515
+ if (customError) {
516
+ throw customError;
517
+ }
518
+ }
519
+ if (response.status >= 400 && response.status < 500 && true) {
520
+ throw new Error(
521
+ `Authentication required (HTTP ${response.status}). Please provide a token in options or set ZAPIER_TOKEN environment variable.`
522
+ );
523
+ }
524
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
525
+ }
526
+ try {
527
+ return await response.json();
528
+ } catch {
529
+ return await response.text();
530
+ }
531
+ }
532
+ async function plainFetch(path, init) {
533
+ if (!path.startsWith("/")) {
534
+ throw new Error(
535
+ `plainFetch expects a path starting with '/', got: ${path}`
536
+ );
537
+ }
538
+ const { url, subdomainConfig } = buildUrl(path, init?.searchParams);
539
+ const headers = await buildHeaders(init, subdomainConfig);
540
+ const finalHeaders = {
541
+ ...headers,
542
+ ...init?.headers ? init.headers instanceof Headers ? Object.fromEntries(init.headers.entries()) : init.headers : {}
543
+ };
544
+ return await fetch(url, {
545
+ ...init,
546
+ headers: finalHeaders
547
+ });
548
+ }
549
+ async function fetchJson(method, path, data, options2 = {}) {
550
+ const headers = { ...options2.headers };
551
+ if (data && typeof data === "object") {
552
+ headers["Content-Type"] = "application/json";
553
+ }
554
+ const response = await plainFetch(path, {
555
+ method,
556
+ body: data ? JSON.stringify(data) : void 0,
557
+ headers,
558
+ searchParams: options2.searchParams,
559
+ authRequired: options2.authRequired
560
+ });
561
+ return handleResponse(response, options2.customErrorHandler);
562
+ }
563
+ return {
564
+ async get(path, options2 = {}) {
565
+ return fetchJson("GET", path, void 0, options2);
566
+ },
567
+ async post(path, data, options2 = {}) {
568
+ return fetchJson("POST", path, data, options2);
569
+ },
570
+ async put(path, data, options2 = {}) {
571
+ return fetchJson("PUT", path, data, options2);
572
+ },
573
+ async delete(path, options2 = {}) {
574
+ return fetchJson("DELETE", path, void 0, options2);
575
+ },
576
+ async poll(path, options2 = {}) {
577
+ return pollUntilComplete({
578
+ fetchPoll: () => plainFetch(path, {
579
+ method: "GET",
580
+ searchParams: options2.searchParams,
581
+ authRequired: options2.authRequired
582
+ }),
583
+ maxAttempts: options2.maxAttempts,
584
+ initialDelay: options2.initialDelay,
585
+ maxDelay: options2.maxDelay,
586
+ successStatus: options2.successStatus,
587
+ pendingStatus: options2.pendingStatus,
588
+ resultExtractor: options2.resultExtractor
589
+ });
590
+ },
591
+ async fetch(path, init) {
592
+ return plainFetch(path, init);
593
+ }
594
+ };
595
+ }
596
+
597
+ // src/api/index.ts
598
+ function generateRequestId() {
599
+ return Math.random().toString(36).substring(2) + Date.now().toString(36);
600
+ }
601
+ function getOrCreateApiClient(config) {
602
+ const {
603
+ baseUrl = "https://zapier.com",
604
+ token,
605
+ getToken,
606
+ api: providedApi,
607
+ debug = false,
608
+ fetch: customFetch
609
+ } = config;
610
+ if (providedApi) {
611
+ return providedApi;
612
+ }
613
+ return createZapierApi({
614
+ baseUrl,
615
+ token,
616
+ getToken,
617
+ debug,
618
+ fetch: customFetch
619
+ });
620
+ }
621
+
622
+ // src/functions/getApp/index.ts
623
+ async function getApp(options) {
624
+ const api = getOrCreateApiClient(options);
625
+ const { appKey } = options;
626
+ const app = await api.get(`/api/v4/apps/${appKey}/`, {
627
+ customErrorHandler: (response) => {
628
+ if (response.status === 404) {
629
+ return new AppNotFoundError(appKey);
630
+ }
631
+ return void 0;
632
+ }
633
+ });
634
+ return {
635
+ key: app.slug,
636
+ name: app.name,
637
+ description: app.description,
638
+ version: "1.0.0",
639
+ category: app.category?.name,
640
+ actions: [],
641
+ triggers: [],
642
+ current_implementation_id: app.current_implementation_id
643
+ };
644
+ }
645
+
646
+ // src/functions/listAuthentications/index.ts
647
+ async function listAuthentications(options = {}) {
648
+ const api = getOrCreateApiClient(options);
649
+ const listAuthenticationsInternal = async (options2 = {}) => {
650
+ const searchParams = {};
651
+ if (options2.appKey) {
652
+ try {
653
+ const app = await getApp({
654
+ appKey: options2.appKey,
655
+ api,
656
+ token: options2.token,
657
+ baseUrl: options2.baseUrl,
658
+ debug: options2.debug,
659
+ fetch: options2.fetch
660
+ });
661
+ const selectedApi = app.current_implementation_id;
662
+ if (selectedApi) {
663
+ const versionlessApi = selectedApi.split("@")[0];
664
+ searchParams.versionless_selected_api = versionlessApi;
665
+ }
666
+ } catch (error) {
667
+ if (error instanceof Error && error.name === "AppNotFoundError") {
668
+ throw error;
669
+ }
670
+ console.warn(
671
+ `Warning: Could not filter by app ${options2.appKey}:`,
672
+ error instanceof Error ? error.message : "Unknown error"
673
+ );
674
+ }
675
+ }
676
+ if (options2.search) {
677
+ searchParams.search = options2.search;
678
+ } else if (options2.title) {
679
+ searchParams.search = options2.title;
680
+ }
681
+ if (options2.account_id) {
682
+ searchParams.account_id = options2.account_id;
683
+ }
684
+ if (options2.owner) {
685
+ searchParams.owner = options2.owner;
686
+ }
687
+ if (options2.limit) {
688
+ searchParams.limit = options2.limit.toString();
689
+ }
690
+ if (options2.offset) {
691
+ searchParams.offset = options2.offset.toString();
692
+ }
693
+ const data = await api.get(
694
+ "/api/v4/authentications/",
695
+ {
696
+ searchParams,
697
+ customErrorHandler: (response) => {
698
+ if (response.status === 401) {
699
+ return new Error(
700
+ `Authentication failed. Your token may not have permission to access authentications or may be expired. (HTTP ${response.status})`
701
+ );
702
+ }
703
+ if (response.status === 403) {
704
+ return new Error(
705
+ `Access forbidden. Your token may not have the required scopes to list authentications. (HTTP ${response.status})`
706
+ );
707
+ }
708
+ return void 0;
709
+ }
710
+ }
711
+ );
712
+ let auths = data.results || [];
713
+ auths = auths.map((auth) => ({
714
+ ...auth,
715
+ title: auth.title || auth.label || void 0
716
+ }));
717
+ if (options2.title) {
718
+ auths = auths.filter((auth) => auth.title === options2.title);
719
+ }
720
+ if (auths.length > 0) {
721
+ auths.__pagination = {
722
+ count: data.count,
723
+ hasNext: !!data.next,
724
+ hasPrevious: !!data.previous,
725
+ nextUrl: data.next,
726
+ previousUrl: data.previous
727
+ };
728
+ }
729
+ return auths;
730
+ };
731
+ if (options.limit && options.owner === void 0) {
732
+ const ownedAuths = await listAuthenticationsInternal({
733
+ ...options,
734
+ owner: "me"
735
+ });
736
+ if (ownedAuths.length >= options.limit) {
737
+ return ownedAuths.slice(0, options.limit);
738
+ }
739
+ const allAuths = await listAuthenticationsInternal({
740
+ ...options,
741
+ owner: void 0
742
+ });
743
+ const ownedAuthenticationIds = new Set(ownedAuths.map((auth) => auth.id));
744
+ const additionalAuths = allAuths.filter(
745
+ (auth) => !ownedAuthenticationIds.has(auth.id)
746
+ );
747
+ const combined = [...ownedAuths, ...additionalAuths];
748
+ return combined.slice(0, options.limit);
749
+ }
750
+ return listAuthenticationsInternal(options);
751
+ }
752
+
753
+ // src/functions/getAuthentication/index.ts
754
+ async function getAuthentication(options) {
755
+ const { authenticationId } = options;
756
+ const api = getOrCreateApiClient(options);
757
+ const data = await api.get(
758
+ `/api/v4/authentications/${authenticationId}/`,
759
+ {
760
+ customErrorHandler: (response) => {
761
+ if (response.status === 401) {
762
+ return new Error(
763
+ `Authentication failed. Your token may not have permission to access authentications or may be expired. (HTTP ${response.status})`
764
+ );
765
+ }
766
+ if (response.status === 403) {
767
+ return new Error(
768
+ `Access forbidden. Your token may not have the required scopes to get authentication ${authenticationId}. (HTTP ${response.status})`
769
+ );
770
+ }
771
+ if (response.status === 404) {
772
+ return new Error(
773
+ `Authentication ${authenticationId} not found. It may not exist or you may not have access to it. (HTTP ${response.status})`
774
+ );
775
+ }
776
+ return void 0;
777
+ }
778
+ }
779
+ );
780
+ return {
781
+ ...data,
782
+ title: data.title || data.label || void 0
783
+ };
784
+ }
785
+
786
+ // src/functions/findFirstAuthentication/index.ts
787
+ async function findFirstAuthentication(options = {}) {
788
+ const auths = await listAuthentications({
789
+ ...options,
790
+ limit: 1
791
+ });
792
+ return auths.length > 0 ? auths[0] : null;
793
+ }
794
+
795
+ // src/functions/findUniqueAuthentication/index.ts
796
+ async function findUniqueAuthentication(options = {}) {
797
+ const auths = await listAuthentications({
798
+ ...options,
799
+ limit: 2
800
+ // Get up to 2 to check for uniqueness
801
+ });
802
+ if (auths.length === 0) {
803
+ throw new Error("No authentication found matching the specified criteria");
804
+ }
805
+ if (auths.length > 1) {
806
+ throw new Error(
807
+ "Multiple authentications found matching the specified criteria. Expected exactly one."
808
+ );
809
+ }
810
+ return auths[0];
811
+ }
812
+
813
+ // src/functions/listApps/index.ts
814
+ async function listApps(options = {}) {
815
+ const api = getOrCreateApiClient(options);
816
+ const searchParams = {};
817
+ if (options.category) {
818
+ searchParams.category = options.category;
819
+ }
820
+ if (options.limit) {
821
+ searchParams.limit = options.limit.toString();
822
+ }
823
+ if (options.offset) {
824
+ searchParams.offset = options.offset.toString();
825
+ }
826
+ const data = await api.get("/api/v4/apps/", { searchParams });
827
+ const apps = data.results?.map(
828
+ (app) => ({
829
+ key: app.slug,
830
+ name: app.name,
831
+ description: app.description,
832
+ version: "1.0.0",
833
+ // API doesn't provide version
834
+ category: app.category?.name,
835
+ actions: [],
836
+ // Will be populated separately
837
+ triggers: [],
838
+ current_implementation_id: app.current_implementation_id
839
+ })
840
+ ) || [];
841
+ if (apps.length > 0) {
842
+ apps.__pagination = {
843
+ count: data.count,
844
+ hasNext: !!data.next,
845
+ hasPrevious: !!data.previous,
846
+ nextUrl: data.next,
847
+ previousUrl: data.previous
848
+ };
849
+ }
850
+ return apps;
851
+ }
852
+
853
+ // src/functions/listActions/index.ts
854
+ async function listActions(options = {}) {
855
+ const api = getOrCreateApiClient(options);
856
+ if (options.appKey) {
857
+ try {
858
+ const appData = await getApp({
859
+ appKey: options.appKey,
860
+ api,
861
+ token: options.token,
862
+ baseUrl: options.baseUrl,
863
+ debug: options.debug,
864
+ fetch: options.fetch
865
+ });
866
+ const implementationId = appData.current_implementation_id?.split("@")[0];
867
+ if (!implementationId) {
868
+ throw new Error("No current_implementation_id found for app");
869
+ }
870
+ const searchParams2 = {
871
+ global: "true",
872
+ public_only: "true",
873
+ selected_apis: implementationId
874
+ };
875
+ const data2 = await api.get("/api/v4/implementations/", {
876
+ searchParams: searchParams2
877
+ });
878
+ const actions2 = [];
879
+ for (const implementation of data2.results || []) {
880
+ if (implementation.actions) {
881
+ for (const action of implementation.actions) {
882
+ const transformedAction = {
883
+ key: action.key,
884
+ name: action.name || action.label,
885
+ description: action.description || "",
886
+ appKey: implementation.slug || "",
887
+ type: action.type || action.type_of || "read",
888
+ inputFields: [],
889
+ // Would need additional API call for detailed fields
890
+ outputFields: []
891
+ };
892
+ if (options?.type && transformedAction.type !== options.type) {
893
+ continue;
894
+ }
895
+ actions2.push(transformedAction);
896
+ }
897
+ }
898
+ }
899
+ if (actions2.length > 0) {
900
+ actions2.__pagination = {
901
+ count: data2.count,
902
+ hasNext: !!data2.next,
903
+ hasPrevious: !!data2.previous,
904
+ nextUrl: data2.next,
905
+ previousUrl: data2.previous
906
+ };
907
+ }
908
+ return actions2;
909
+ } catch (error) {
910
+ if (error instanceof Error && error.name === "AppNotFoundError") {
911
+ throw error;
912
+ }
913
+ console.warn(
914
+ "Optimized app lookup failed, falling back to full scan:",
915
+ error
916
+ );
917
+ }
918
+ }
919
+ const searchParams = {
920
+ global: "true",
921
+ public_only: "true"
922
+ };
923
+ const data = await api.get("/api/v4/implementations/", { searchParams });
924
+ const actions = [];
925
+ for (const implementation of data.results || []) {
926
+ if (implementation.actions) {
927
+ for (const action of implementation.actions) {
928
+ const transformedAction = {
929
+ key: action.key,
930
+ name: action.name || action.label,
931
+ description: action.description || "",
932
+ appKey: implementation.slug || "",
933
+ type: action.type || action.type_of || "read",
934
+ inputFields: [],
935
+ // Would need additional API call for detailed fields
936
+ outputFields: []
937
+ };
938
+ if (options?.appKey && transformedAction.appKey !== options.appKey) {
939
+ continue;
940
+ }
941
+ if (options?.type && transformedAction.type !== options.type) {
942
+ continue;
943
+ }
944
+ actions.push(transformedAction);
945
+ }
946
+ }
947
+ }
948
+ if (actions.length > 0) {
949
+ actions.__pagination = {
950
+ count: data.count,
951
+ hasNext: !!data.next,
952
+ hasPrevious: !!data.previous,
953
+ nextUrl: data.next,
954
+ previousUrl: data.previous
955
+ };
956
+ }
957
+ return actions;
958
+ }
959
+
960
+ // src/functions/getAction/index.ts
961
+ async function getAction(options) {
962
+ const { appKey, actionKey, actionType } = options;
963
+ const actions = await listActions({
964
+ ...options,
965
+ appKey
966
+ });
967
+ const action = actions.find(
968
+ (a) => a.key === actionKey && a.type === actionType
969
+ );
970
+ if (!action) {
971
+ throw new Error(`Action not found: ${actionKey} with type ${actionType}`);
972
+ }
973
+ return action;
974
+ }
975
+
976
+ // src/functions/runAction/index.ts
977
+ async function runAction(options) {
978
+ const {
979
+ appKey,
980
+ actionType,
981
+ actionKey,
982
+ inputs,
983
+ authenticationId: providedAuthenticationId
984
+ } = options;
985
+ const api = getOrCreateApiClient(options);
986
+ const actionData = await getAction({
987
+ ...options,
988
+ appKey,
989
+ actionKey,
990
+ actionType
991
+ });
992
+ if (actionData.type !== actionType) {
993
+ throw new Error(
994
+ `Action type mismatch: expected ${actionType}, got ${actionData.type}`
995
+ );
996
+ }
997
+ const startTime = Date.now();
998
+ const result = await executeAction({
999
+ api,
1000
+ appSlug: appKey,
1001
+ actionKey,
1002
+ actionType: actionData.type,
1003
+ executionOptions: { inputs: inputs || {} },
1004
+ authenticationId: providedAuthenticationId,
1005
+ options
1006
+ });
1007
+ const executionTime = Date.now() - startTime;
1008
+ return {
1009
+ success: true,
1010
+ data: result,
1011
+ metadata: {
1012
+ executionTime,
1013
+ requestId: generateRequestId()
1014
+ }
1015
+ };
1016
+ }
1017
+ async function executeAction(actionOptions) {
1018
+ const {
1019
+ api,
1020
+ appSlug,
1021
+ actionKey,
1022
+ actionType,
1023
+ executionOptions,
1024
+ authenticationId,
1025
+ options
1026
+ } = actionOptions;
1027
+ const appData = await getApp({
1028
+ appKey: appSlug,
1029
+ api,
1030
+ token: options.token,
1031
+ baseUrl: options.baseUrl,
1032
+ debug: options.debug,
1033
+ fetch: options.fetch
1034
+ });
1035
+ const selectedApi = appData.current_implementation_id;
1036
+ if (!selectedApi) {
1037
+ throw new Error("No current_implementation_id found for app");
1038
+ }
1039
+ const runRequest = {
1040
+ data: {
1041
+ authentication_id: authenticationId || 1,
1042
+ selected_api: selectedApi,
1043
+ action_key: actionKey,
1044
+ action_type: actionType,
1045
+ inputs: executionOptions.inputs || {}
1046
+ }
1047
+ };
1048
+ const runData = await api.post("/api/actions/v1/runs", runRequest);
1049
+ const runId = runData.data.id;
1050
+ return await api.poll(`/api/actions/v1/runs/${runId}`, {
1051
+ successStatus: 200,
1052
+ pendingStatus: 202,
1053
+ resultExtractor: (result) => result.data
1054
+ });
1055
+ }
1056
+
1057
+ // src/functions/listFields/index.ts
1058
+ async function listFields(options) {
1059
+ const api = getOrCreateApiClient(options);
1060
+ const { appKey, actionKey, actionType, authenticationId, params } = options;
1061
+ const appData = await getApp({
1062
+ appKey,
1063
+ api,
1064
+ token: options.token,
1065
+ baseUrl: options.baseUrl,
1066
+ debug: options.debug,
1067
+ fetch: options.fetch
1068
+ });
1069
+ const selectedApi = appData.current_implementation_id;
1070
+ if (!selectedApi) {
1071
+ throw new Error("No current_implementation_id found for app");
1072
+ }
1073
+ const needsRequest = {
1074
+ selected_api: selectedApi,
1075
+ action: actionKey,
1076
+ type_of: actionType,
1077
+ authentication_id: authenticationId,
1078
+ params: params || {}
1079
+ };
1080
+ const needsData = await api.post(
1081
+ "/api/v4/implementations/needs/",
1082
+ needsRequest
1083
+ );
1084
+ if (!needsData.success) {
1085
+ throw new Error(
1086
+ `Failed to get action fields: ${needsData.errors?.join(", ") || "Unknown error"}`
1087
+ );
1088
+ }
1089
+ return (needsData.needs || []).map((need) => ({
1090
+ key: need.key,
1091
+ label: need.label,
1092
+ required: need.required || false,
1093
+ type: need.type,
1094
+ helpText: need.help_text,
1095
+ helpTextHtml: need.help_text_html,
1096
+ choices: need.choices?.map((choice) => ({
1097
+ value: choice.value,
1098
+ label: choice.label
1099
+ })),
1100
+ default: need.default,
1101
+ placeholder: need.placeholder,
1102
+ computed: need.computed,
1103
+ customField: need.custom_field,
1104
+ dependsOn: need.depends_on,
1105
+ format: need.format,
1106
+ inputFormat: need.input_format
1107
+ }));
1108
+ }
1109
+
1110
+ // src/functions/generateTypes/index.ts
1111
+ function generateFetchMethodSignature() {
1112
+ return ` /** Make authenticated HTTP requests through Zapier's Relay service */
1113
+ fetch: (options: Omit<z.infer<typeof RelayFetchSchema>, 'authenticationId'>) => Promise<Response>`;
1114
+ }
1115
+ async function generateTypes(options) {
1116
+ const {
1117
+ appKey,
1118
+ authenticationId,
1119
+ output = `./types/${appKey}.d.ts`
1120
+ } = options;
1121
+ const { app, version } = parseAppIdentifier(appKey);
1122
+ const actions = await listActions({
1123
+ ...options,
1124
+ appKey: app
1125
+ });
1126
+ if (actions.length === 0) {
1127
+ const typeDefinitions2 = generateEmptyTypesFile(app, version);
1128
+ if (output) {
1129
+ const fs = await import('fs');
1130
+ const path = await import('path');
1131
+ fs.mkdirSync(path.dirname(output), { recursive: true });
1132
+ fs.writeFileSync(output, typeDefinitions2, "utf8");
1133
+ }
1134
+ return typeDefinitions2;
1135
+ }
1136
+ const actionsWithFields = [];
1137
+ if (authenticationId) {
1138
+ for (const action of actions) {
1139
+ try {
1140
+ const fields = await listFields({
1141
+ ...options,
1142
+ appKey: action.appKey,
1143
+ actionKey: action.key,
1144
+ actionType: action.type,
1145
+ authenticationId
1146
+ });
1147
+ actionsWithFields.push({ ...action, inputFields: fields });
1148
+ } catch {
1149
+ actionsWithFields.push({ ...action, inputFields: [] });
1150
+ }
1151
+ }
1152
+ } else {
1153
+ actions.forEach((action) => {
1154
+ actionsWithFields.push({ ...action, inputFields: [] });
1155
+ });
1156
+ }
1157
+ const typeDefinitions = generateTypeDefinitions(
1158
+ app,
1159
+ actionsWithFields,
1160
+ version
1161
+ );
1162
+ if (output) {
1163
+ const fs = await import('fs');
1164
+ const path = await import('path');
1165
+ fs.mkdirSync(path.dirname(output), { recursive: true });
1166
+ fs.writeFileSync(output, typeDefinitions, "utf8");
1167
+ }
1168
+ return typeDefinitions;
1169
+ }
1170
+ function parseAppIdentifier(identifier) {
1171
+ const parts = identifier.split("@");
1172
+ return {
1173
+ app: parts[0],
1174
+ version: parts[1]
1175
+ };
1176
+ }
1177
+ function generateTypeDefinitions(appKey, actions, version) {
1178
+ if (actions.length === 0) {
1179
+ return generateEmptyTypesFile(appKey, version);
1180
+ }
1181
+ const actionsByType = actions.reduce(
1182
+ (acc, action) => {
1183
+ if (!acc[action.type]) {
1184
+ acc[action.type] = [];
1185
+ }
1186
+ acc[action.type].push(action);
1187
+ return acc;
1188
+ },
1189
+ {}
1190
+ );
1191
+ const appName = capitalize(appKey);
1192
+ const versionComment = version ? ` * Generated for ${appKey}@${version}` : ` * Generated for ${appKey}`;
1193
+ let output = `/* eslint-disable @typescript-eslint/naming-convention */
1194
+ /**
1195
+ * Auto-generated TypeScript types for Zapier ${appKey} actions
1196
+ ${versionComment}
1197
+ * Generated on: ${(/* @__PURE__ */ new Date()).toISOString()}
1198
+ *
1199
+ * Usage:
1200
+ * import type { ${appName}Sdk } from './path/to/this/file'
1201
+ * const sdk = createZapierSdk() as unknown as ${appName}Sdk
1202
+ *
1203
+ * // Direct usage (per-call auth):
1204
+ * await sdk.apps.${appKey}.search.user_by_email({ authenticationId: 123, inputs: { email } })
1205
+ *
1206
+ * // Factory usage (pinned auth):
1207
+ * const my${appName} = sdk.apps.${appKey}({ authenticationId: 123 })
1208
+ * await my${appName}.search.user_by_email({ inputs: { email } })
1209
+ */
1210
+
1211
+ import type { ActionExecutionOptions, ActionExecutionResult } from '@zapier/zapier-sdk'
1212
+ import { z } from 'zod'
1213
+ import { RelayFetchSchema } from '@zapier/zapier-sdk'
1214
+
1215
+ `;
1216
+ actions.forEach((action) => {
1217
+ if (action.inputFields.length > 0) {
1218
+ const inputTypeName = `${appName}${capitalize(action.type)}${capitalize(
1219
+ sanitizeActionName(action.key)
1220
+ )}Inputs`;
1221
+ output += `interface ${inputTypeName} {
1222
+ `;
1223
+ action.inputFields.forEach((field) => {
1224
+ const isOptional = !field.required;
1225
+ const fieldType = mapFieldTypeToTypeScript(field);
1226
+ const description = field.helpText ? ` /** ${escapeComment(field.helpText)} */
1227
+ ` : "";
1228
+ output += `${description} ${sanitizeFieldName(field.key)}${isOptional ? "?" : ""}: ${fieldType}
1229
+ `;
1230
+ });
1231
+ output += `}
1232
+
1233
+ `;
1234
+ }
1235
+ });
1236
+ Object.entries(actionsByType).forEach(([actionType, typeActions]) => {
1237
+ const typeName = `${appName}${capitalize(actionType)}Actions`;
1238
+ output += `interface ${typeName} {
1239
+ `;
1240
+ typeActions.forEach((action) => {
1241
+ const actionName = sanitizeActionName(action.key);
1242
+ const description = action.description ? ` /** ${escapeComment(action.description)} */
1243
+ ` : "";
1244
+ if (action.inputFields.length > 0) {
1245
+ const inputTypeName = `${appName}${capitalize(action.type)}${capitalize(
1246
+ sanitizeActionName(action.key)
1247
+ )}Inputs`;
1248
+ output += `${description} ${actionName}: (options: { inputs: ${inputTypeName} } & Omit<ActionExecutionOptions, 'inputs'>) => Promise<ActionExecutionResult>
1249
+ `;
1250
+ } else {
1251
+ output += `${description} ${actionName}: (options?: { inputs?: Record<string, any> } & ActionExecutionOptions) => Promise<ActionExecutionResult>
1252
+ `;
1253
+ }
1254
+ });
1255
+ output += `}
1256
+
1257
+ `;
1258
+ });
1259
+ output += `interface ${appName}AppProxy {
1260
+ `;
1261
+ Object.keys(actionsByType).forEach((actionType) => {
1262
+ const typeName = `${appName}${capitalize(actionType)}Actions`;
1263
+ output += ` ${actionType}: ${typeName}
1264
+ `;
1265
+ });
1266
+ output += generateFetchMethodSignature() + "\n";
1267
+ output += `}
1268
+
1269
+ `;
1270
+ output += `interface ${appName}AppFactory {
1271
+ `;
1272
+ output += ` (options: { authenticationId: number }): ${appName}AppProxy
1273
+ `;
1274
+ output += `}
1275
+
1276
+ `;
1277
+ output += `type ${appName}AppWithFactory = ${appName}AppFactory & ${appName}AppProxy
1278
+
1279
+ `;
1280
+ output += `export interface ${appName}Sdk {
1281
+ `;
1282
+ output += ` apps: {
1283
+ `;
1284
+ output += ` ${appKey}: ${appName}AppWithFactory
1285
+ `;
1286
+ output += ` }
1287
+ `;
1288
+ output += `}
1289
+ `;
1290
+ return output;
1291
+ }
1292
+ function generateEmptyTypesFile(appKey, version) {
1293
+ const appName = capitalize(appKey);
1294
+ const versionComment = version ? ` * Generated for ${appKey}@${version}` : ` * Generated for ${appKey}`;
1295
+ return `/* eslint-disable @typescript-eslint/naming-convention */
1296
+ /**
1297
+ * Auto-generated TypeScript types for Zapier ${appKey} actions
1298
+ ${versionComment}
1299
+ * Generated on: ${(/* @__PURE__ */ new Date()).toISOString()}
1300
+ *
1301
+ * No actions found for this app.
1302
+ */
1303
+
1304
+ import type { ActionExecutionOptions, ActionExecutionResult } from '@zapier/zapier-sdk'
1305
+ import { z } from 'zod'
1306
+ import { RelayFetchSchema } from '@zapier/zapier-sdk'
1307
+
1308
+ interface ${appName}AppProxy {
1309
+ // No actions available
1310
+ ${generateFetchMethodSignature()}
1311
+ }
1312
+
1313
+ interface ${appName}AppFactory {
1314
+ (options: { authenticationId: number }): ${appName}AppProxy
1315
+ }
1316
+
1317
+ type ${appName}AppWithFactory = ${appName}AppFactory & ${appName}AppProxy
1318
+
1319
+ export interface ${appName}Sdk {
1320
+ apps: {
1321
+ ${appKey}: ${appName}AppWithFactory
1322
+ }
1323
+ }
1324
+ `;
1325
+ }
1326
+ function capitalize(str) {
1327
+ return str.charAt(0).toUpperCase() + str.slice(1).replace(/[-_]/g, "");
1328
+ }
1329
+ function sanitizeActionName(actionKey) {
1330
+ let sanitized = actionKey.replace(/[^a-zA-Z0-9_$]/g, "_");
1331
+ if (/^[0-9]/.test(sanitized)) {
1332
+ sanitized = "_" + sanitized;
1333
+ }
1334
+ return sanitized;
1335
+ }
1336
+ function sanitizeFieldName(fieldKey) {
1337
+ let sanitized = fieldKey.replace(/[^a-zA-Z0-9_$]/g, "_");
1338
+ if (/^[0-9]/.test(sanitized)) {
1339
+ sanitized = "_" + sanitized;
1340
+ }
1341
+ return sanitized;
1342
+ }
1343
+ function escapeComment(comment) {
1344
+ return comment.replace(/\*\//g, "*\\/").replace(/\r?\n/g, " ");
1345
+ }
1346
+ function mapFieldTypeToTypeScript(field) {
1347
+ if (field.choices && field.choices.length > 0) {
1348
+ const choiceValues = field.choices.filter(
1349
+ (choice) => choice.value !== void 0 && choice.value !== null && choice.value !== ""
1350
+ ).map(
1351
+ (choice) => typeof choice.value === "string" ? `"${choice.value}"` : choice.value
1352
+ );
1353
+ if (choiceValues.length > 0) {
1354
+ return choiceValues.join(" | ");
1355
+ }
1356
+ }
1357
+ switch (field.type?.toLowerCase()) {
1358
+ case "string":
1359
+ case "text":
1360
+ case "email":
1361
+ case "url":
1362
+ case "password":
1363
+ return "string";
1364
+ case "integer":
1365
+ case "number":
1366
+ return "number";
1367
+ case "boolean":
1368
+ return "boolean";
1369
+ case "datetime":
1370
+ case "date":
1371
+ return "string";
1372
+ // ISO date strings
1373
+ case "file":
1374
+ return "string";
1375
+ // File URL or content
1376
+ case "array":
1377
+ return "any[]";
1378
+ case "object":
1379
+ return "Record<string, any>";
1380
+ default:
1381
+ return "string | number | boolean";
1382
+ }
1383
+ }
1384
+
1385
+ // src/functions/bundleCode/index.ts
1386
+ async function bundleCode(options) {
1387
+ const {
1388
+ input,
1389
+ output,
1390
+ target = "es2020",
1391
+ cjs = false,
1392
+ minify = false,
1393
+ string: returnString = false
1394
+ } = options;
1395
+ const { buildSync } = await import('esbuild');
1396
+ const fs = await import('fs');
1397
+ const path = await import('path');
1398
+ const resolvedInput = path.resolve(process.cwd(), input);
1399
+ try {
1400
+ const result = buildSync({
1401
+ entryPoints: [resolvedInput],
1402
+ bundle: true,
1403
+ platform: "node",
1404
+ target,
1405
+ format: cjs ? "cjs" : "esm",
1406
+ minify,
1407
+ write: false,
1408
+ external: [],
1409
+ // Bundle everything
1410
+ banner: {
1411
+ js: "#!/usr/bin/env node"
1412
+ }
1413
+ });
1414
+ if (result.errors.length > 0) {
1415
+ throw new Error(
1416
+ `Bundle failed: ${result.errors.map((e) => e.text).join(", ")}`
1417
+ );
1418
+ }
1419
+ const bundledCode = result.outputFiles?.[0]?.text;
1420
+ if (!bundledCode) {
1421
+ throw new Error("No output generated");
1422
+ }
1423
+ let finalOutput = bundledCode;
1424
+ if (returnString) {
1425
+ finalOutput = JSON.stringify(bundledCode);
1426
+ }
1427
+ if (output) {
1428
+ fs.mkdirSync(path.dirname(output), { recursive: true });
1429
+ fs.writeFileSync(output, finalOutput, "utf8");
1430
+ }
1431
+ return finalOutput;
1432
+ } catch (error) {
1433
+ throw new Error(
1434
+ `Bundle failed: ${error instanceof Error ? error.message : "Unknown error"}`
1435
+ );
1436
+ }
1437
+ }
1438
+
1439
+ // src/functions/request/index.ts
1440
+ function transformUrlToRelayPath(url) {
1441
+ const targetUrl = new URL(url);
1442
+ const relayPath = `/relay/${targetUrl.hostname}${targetUrl.pathname}${targetUrl.search}${targetUrl.hash}`;
1443
+ return relayPath;
1444
+ }
1445
+ async function request(options) {
1446
+ const {
1447
+ url,
1448
+ method = "GET",
1449
+ body,
1450
+ headers,
1451
+ authenticationId,
1452
+ callbackUrl,
1453
+ authenticationTemplate,
1454
+ ...config
1455
+ } = options;
1456
+ return relayFetch(
1457
+ url,
1458
+ {
1459
+ method,
1460
+ body,
1461
+ headers,
1462
+ authenticationId,
1463
+ callbackUrl,
1464
+ authenticationTemplate
1465
+ },
1466
+ config
1467
+ );
1468
+ }
1469
+ async function relayFetch(url, options = {}, config = {}) {
1470
+ const api = getOrCreateApiClient(config);
1471
+ const {
1472
+ authenticationId,
1473
+ callbackUrl,
1474
+ authenticationTemplate,
1475
+ method = "GET",
1476
+ body,
1477
+ ...fetchOptions
1478
+ } = options;
1479
+ const relayPath = transformUrlToRelayPath(url);
1480
+ const headers = {};
1481
+ if (fetchOptions.headers) {
1482
+ const headerEntries = fetchOptions.headers instanceof Headers ? Array.from(fetchOptions.headers.entries()) : Object.entries(fetchOptions.headers);
1483
+ for (const [key, value] of headerEntries) {
1484
+ headers[key] = value;
1485
+ }
1486
+ }
1487
+ if (authenticationId) {
1488
+ headers["X-Relay-Authentication-Id"] = authenticationId.toString();
1489
+ }
1490
+ if (callbackUrl) {
1491
+ headers["X-Relay-Callback-Url"] = callbackUrl;
1492
+ }
1493
+ if (authenticationTemplate) {
1494
+ headers["X-Authentication-Template"] = authenticationTemplate;
1495
+ }
1496
+ return await api.fetch(relayPath, {
1497
+ method,
1498
+ body,
1499
+ headers
1500
+ });
1501
+ }
1502
+ var RelayRequestSchema = z.object({
1503
+ url: z.string().url().describe("The URL to request (will be proxied through Relay)"),
1504
+ method: z.enum(["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"]).optional().describe("HTTP method"),
1505
+ body: z.string().optional().describe("Request body as a string"),
1506
+ authenticationId: z.number().int().optional().describe("Zapier authentication ID to use for the request"),
1507
+ callbackUrl: z.string().url().optional().describe("URL to send async response to (makes request async)"),
1508
+ authenticationTemplate: z.string().optional().describe(
1509
+ "Optional JSON string authentication template to bypass Notary lookup"
1510
+ ),
1511
+ headers: z.record(z.string()).optional().describe("Request headers")
1512
+ }).describe("Make authenticated HTTP requests through Zapier's Relay service");
1513
+ var RelayFetchSchema = RelayRequestSchema;
1514
+ var AppItemSchema = withFormatter(
1515
+ z.object({
1516
+ key: z.string(),
1517
+ name: z.string().optional(),
1518
+ description: z.string().optional(),
1519
+ category: z.string().optional()
1520
+ }),
1521
+ {
1522
+ format: (item) => {
1523
+ const details = [];
1524
+ if (item.description) {
1525
+ details.push({ text: item.description, style: "dim" });
1526
+ }
1527
+ if (item.category) {
1528
+ details.push({
1529
+ text: `Category: ${item.category}`,
1530
+ style: "accent"
1531
+ });
1532
+ }
1533
+ return {
1534
+ title: item.name || item.key,
1535
+ subtitle: `(${item.key})`,
1536
+ details
1537
+ };
1538
+ }
1539
+ }
1540
+ );
1541
+
1542
+ // src/functions/listApps/schemas.ts
1543
+ var ListAppsSchema = withOutputSchema(
1544
+ z.object({
1545
+ category: z.string().optional().describe("Filter apps by category"),
1546
+ limit: LimitPropertySchema.optional().describe(
1547
+ "Maximum number of items to return (1-200)"
1548
+ ),
1549
+ offset: OffsetPropertySchema.optional().describe(
1550
+ "Number of items to skip for pagination"
1551
+ )
1552
+ }).describe("List all available apps with optional filtering"),
1553
+ AppItemSchema
1554
+ );
1555
+
1556
+ // src/functions/listApps/info.ts
1557
+ var listAppsInfo = {
1558
+ name: listApps.name,
1559
+ inputSchema: ListAppsSchema,
1560
+ implementation: listApps
1561
+ };
1562
+ var GetAppSchema = z.object({
1563
+ appKey: AppKeyPropertySchema.describe(
1564
+ "App key or slug to fetch (e.g., google-sheets, slack, github)"
1565
+ )
1566
+ }).describe("Get detailed information about a specific app");
1567
+
1568
+ // src/functions/getApp/info.ts
1569
+ var getAppInfo = {
1570
+ name: getApp.name,
1571
+ inputSchema: GetAppSchema,
1572
+ implementation: getApp
1573
+ };
1574
+ var ActionItemSchema = withFormatter(
1575
+ z.object({
1576
+ key: z.string(),
1577
+ name: z.string().optional(),
1578
+ type: z.string(),
1579
+ appKey: z.string().optional(),
1580
+ description: z.string().optional()
1581
+ }),
1582
+ {
1583
+ format: (item) => {
1584
+ const details = [];
1585
+ details.push({ text: `Type: ${item.type}`, style: "accent" });
1586
+ if (item.appKey) {
1587
+ details.push({ text: `App: ${item.appKey}`, style: "normal" });
1588
+ }
1589
+ if (item.description) {
1590
+ details.push({ text: item.description, style: "dim" });
1591
+ }
1592
+ return {
1593
+ title: item.name || item.key,
1594
+ subtitle: `(${item.key})`,
1595
+ details
1596
+ };
1597
+ }
1598
+ }
1599
+ );
1600
+
1601
+ // src/functions/listActions/schemas.ts
1602
+ var ListActionsSchema = withOutputSchema(
1603
+ z.object({
1604
+ appKey: AppKeyPropertySchema.optional(),
1605
+ type: ActionTypePropertySchema.optional().describe(
1606
+ "Filter actions by type"
1607
+ )
1608
+ }).describe("List all actions for a specific app"),
1609
+ ActionItemSchema
1610
+ );
1611
+
1612
+ // src/functions/listActions/info.ts
1613
+ var listActionsInfo = {
1614
+ name: listActions.name,
1615
+ inputSchema: ListActionsSchema,
1616
+ implementation: listActions
1617
+ };
1618
+ var GetActionSchema = z.object({
1619
+ appKey: AppKeyPropertySchema,
1620
+ actionType: ActionTypePropertySchema,
1621
+ actionKey: ActionKeyPropertySchema
1622
+ }).describe("Get detailed information about a specific action");
1623
+
1624
+ // src/functions/getAction/info.ts
1625
+ var getActionInfo = {
1626
+ name: getAction.name,
1627
+ inputSchema: GetActionSchema,
1628
+ implementation: getAction
1629
+ };
1630
+ var RunActionSchema = z.object({
1631
+ appKey: AppKeyPropertySchema,
1632
+ actionType: ActionTypePropertySchema,
1633
+ actionKey: ActionKeyPropertySchema,
1634
+ inputs: InputsPropertySchema.optional().describe(
1635
+ "Input parameters for the action"
1636
+ ),
1637
+ authenticationId: AuthenticationIdPropertySchema.optional()
1638
+ }).describe("Execute an action with the given inputs");
1639
+
1640
+ // src/functions/runAction/info.ts
1641
+ var runActionInfo = {
1642
+ name: runAction.name,
1643
+ inputSchema: RunActionSchema,
1644
+ implementation: runAction
1645
+ };
1646
+ var AuthItemSchema = withFormatter(
1647
+ z.object({
1648
+ id: z.number(),
1649
+ title: z.string().optional(),
1650
+ identifier: z.string().optional(),
1651
+ account_id: z.string().optional(),
1652
+ is_private: z.boolean().optional(),
1653
+ shared_with_all: z.boolean().optional(),
1654
+ marked_stale_at: z.string().optional()
1655
+ }),
1656
+ {
1657
+ format: (item) => {
1658
+ const details = [];
1659
+ if (item.identifier) {
1660
+ details.push({
1661
+ text: `Identifier: ${item.identifier}`,
1662
+ style: "accent"
1663
+ });
1664
+ }
1665
+ details.push({
1666
+ text: `Account: ${item.account_id || "unknown"} | Private: ${item.is_private || false} | Shared: ${item.shared_with_all || false}`,
1667
+ style: "dim"
1668
+ });
1669
+ if (item.marked_stale_at) {
1670
+ details.push({
1671
+ text: `\u26A0\uFE0F Marked stale: ${new Date(item.marked_stale_at).toLocaleDateString()}`,
1672
+ style: "warning"
1673
+ });
1674
+ }
1675
+ return {
1676
+ title: item.title || `Authentication ${item.id}`,
1677
+ subtitle: `(ID: ${item.id})`,
1678
+ details
1679
+ };
1680
+ }
1681
+ }
1682
+ );
1683
+
1684
+ // src/functions/listAuthentications/schemas.ts
1685
+ var ListAuthenticationsSchema = withOutputSchema(
1686
+ z.object({
1687
+ appKey: AppKeyPropertySchema.optional().describe(
1688
+ "App slug to get authentications for (e.g., 'slack', 'github')"
1689
+ ),
1690
+ search: z.string().optional().describe("Search term to filter authentications by title"),
1691
+ title: z.string().optional().describe("Filter authentications by exact title match"),
1692
+ account_id: z.string().optional().describe("Filter by account ID"),
1693
+ owner: z.string().optional().describe("Filter by owner"),
1694
+ limit: LimitPropertySchema.optional().describe(
1695
+ "Maximum number of items to return (1-200)"
1696
+ ),
1697
+ offset: OffsetPropertySchema.optional().describe(
1698
+ "Number of items to skip for pagination"
1699
+ )
1700
+ }).describe("List available authentications with optional filtering"),
1701
+ AuthItemSchema
1702
+ );
1703
+
1704
+ // src/functions/listAuthentications/info.ts
1705
+ var listAuthenticationsInfo = {
1706
+ name: listAuthentications.name,
1707
+ inputSchema: ListAuthenticationsSchema,
1708
+ implementation: listAuthentications
1709
+ };
1710
+ var GetAuthenticationSchema = withOutputSchema(
1711
+ z.object({
1712
+ authenticationId: z.number().int().positive().describe("Authentication ID to retrieve")
1713
+ }).describe("Get a specific authentication by ID"),
1714
+ AuthItemSchema
1715
+ );
1716
+
1717
+ // src/functions/getAuthentication/info.ts
1718
+ var getAuthenticationInfo = {
1719
+ name: getAuthentication.name,
1720
+ inputSchema: GetAuthenticationSchema,
1721
+ implementation: getAuthentication
1722
+ };
1723
+ var FindFirstAuthenticationSchema = withOutputSchema(
1724
+ z.object({
1725
+ appKey: AppKeyPropertySchema.optional().describe(
1726
+ "App slug to get authentications for (e.g., 'slack', 'github')"
1727
+ ),
1728
+ search: z.string().optional().describe("Search term to filter authentications by title"),
1729
+ title: z.string().optional().describe("Filter authentications by exact title match"),
1730
+ account_id: z.string().optional().describe("Filter by account ID"),
1731
+ owner: z.string().optional().describe("Filter by owner"),
1732
+ limit: LimitPropertySchema.optional().describe(
1733
+ "Maximum number of items to return (1-200)"
1734
+ ),
1735
+ offset: OffsetPropertySchema.optional().describe(
1736
+ "Number of items to skip for pagination"
1737
+ )
1738
+ }).describe("Find the first authentication matching the criteria"),
1739
+ AuthItemSchema
1740
+ );
1741
+
1742
+ // src/functions/findFirstAuthentication/info.ts
1743
+ var findFirstAuthenticationInfo = {
1744
+ name: findFirstAuthentication.name,
1745
+ inputSchema: FindFirstAuthenticationSchema,
1746
+ implementation: findFirstAuthentication
1747
+ };
1748
+ var FindUniqueAuthenticationSchema = withOutputSchema(
1749
+ z.object({
1750
+ appKey: AppKeyPropertySchema.optional().describe(
1751
+ "App slug to get authentications for (e.g., 'slack', 'github')"
1752
+ ),
1753
+ search: z.string().optional().describe("Search term to filter authentications by title"),
1754
+ title: z.string().optional().describe("Filter authentications by exact title match"),
1755
+ account_id: z.string().optional().describe("Filter by account ID"),
1756
+ owner: z.string().optional().describe("Filter by owner"),
1757
+ limit: LimitPropertySchema.optional().describe(
1758
+ "Maximum number of items to return (1-200)"
1759
+ ),
1760
+ offset: OffsetPropertySchema.optional().describe(
1761
+ "Number of items to skip for pagination"
1762
+ )
1763
+ }).describe("Find a unique authentication matching the criteria"),
1764
+ AuthItemSchema
1765
+ );
1766
+
1767
+ // src/functions/findUniqueAuthentication/info.ts
1768
+ var findUniqueAuthenticationInfo = {
1769
+ name: findUniqueAuthentication.name,
1770
+ inputSchema: FindUniqueAuthenticationSchema,
1771
+ implementation: findUniqueAuthentication
1772
+ };
1773
+ var FieldItemSchema = withFormatter(
1774
+ z.object({
1775
+ key: z.string(),
1776
+ name: z.string().optional(),
1777
+ description: z.string().optional()
1778
+ }),
1779
+ {
1780
+ format: (item) => {
1781
+ const details = [];
1782
+ if (item.description) {
1783
+ details.push({ text: item.description, style: "dim" });
1784
+ }
1785
+ return {
1786
+ title: item.name || item.key,
1787
+ subtitle: `(${item.key})`,
1788
+ details
1789
+ };
1790
+ }
1791
+ }
1792
+ );
1793
+
1794
+ // src/functions/listFields/schemas.ts
1795
+ var ListFieldsSchema = withOutputSchema(
1796
+ z.object({
1797
+ appKey: AppKeyPropertySchema,
1798
+ actionType: ActionTypePropertySchema,
1799
+ actionKey: ActionKeyPropertySchema,
1800
+ authenticationId: AuthenticationIdPropertySchema.optional(),
1801
+ params: ParamsPropertySchema.optional().describe(
1802
+ "Additional parameters that may affect available fields"
1803
+ )
1804
+ }).describe("Get the input fields required for a specific action"),
1805
+ FieldItemSchema
1806
+ );
1807
+
1808
+ // src/functions/listFields/info.ts
1809
+ var listFieldsInfo = {
1810
+ name: listFields.name,
1811
+ inputSchema: ListFieldsSchema,
1812
+ implementation: listFields
1813
+ };
1814
+ var GenerateTypesSchema = z.object({
1815
+ appKey: AppKeyPropertySchema.describe("App key to generate SDK code for"),
1816
+ authenticationId: AuthenticationIdPropertySchema.optional(),
1817
+ output: OutputPropertySchema.optional().describe(
1818
+ "Output file path (defaults to generated/<appKey>.ts)"
1819
+ ),
1820
+ debug: DebugPropertySchema.describe(
1821
+ "Enable debug logging during generation"
1822
+ )
1823
+ }).describe("Generate TypeScript SDK code for a specific app");
1824
+
1825
+ // src/functions/generateTypes/info.ts
1826
+ var generateTypesInfo = {
1827
+ name: generateTypes.name,
1828
+ inputSchema: GenerateTypesSchema,
1829
+ implementation: generateTypes
1830
+ };
1831
+ var BundleCodeSchema = z.object({
1832
+ input: z.string().min(1).describe("Input TypeScript file path to bundle"),
1833
+ output: OutputPropertySchema.optional().describe(
1834
+ "Output file path (defaults to input with .js extension)"
1835
+ ),
1836
+ string: z.boolean().default(false).describe("Return bundled code as string instead of writing to file"),
1837
+ minify: z.boolean().default(false).describe("Minify the bundled output"),
1838
+ target: z.string().default("es2017").describe("ECMAScript target version"),
1839
+ cjs: z.boolean().default(false).describe("Output CommonJS format instead of ESM")
1840
+ }).describe("Bundle TypeScript code into executable JavaScript");
1841
+
1842
+ // src/functions/bundleCode/info.ts
1843
+ var bundleCodeInfo = {
1844
+ name: bundleCode.name,
1845
+ inputSchema: BundleCodeSchema,
1846
+ implementation: bundleCode
1847
+ };
1848
+
1849
+ // src/functions/request/info.ts
1850
+ var requestInfo = {
1851
+ name: "request",
1852
+ inputSchema: RelayRequestSchema,
1853
+ implementation: request
1854
+ };
1855
+
1856
+ // src/sdk.ts
1857
+ var functionRegistry = [
1858
+ listAppsInfo,
1859
+ getAppInfo,
1860
+ listActionsInfo,
1861
+ getActionInfo,
1862
+ runActionInfo,
1863
+ listAuthenticationsInfo,
1864
+ getAuthenticationInfo,
1865
+ findFirstAuthenticationInfo,
1866
+ findUniqueAuthenticationInfo,
1867
+ listFieldsInfo,
1868
+ generateTypesInfo,
1869
+ bundleCodeInfo,
1870
+ requestInfo
1871
+ ];
1872
+ function createZapierSdk(options = {}) {
1873
+ const {
1874
+ fetch: customFetch = globalThis.fetch,
1875
+ baseUrl = "https://zapier.com",
1876
+ token,
1877
+ getToken,
1878
+ onEvent,
1879
+ debug = false
1880
+ } = options;
1881
+ const api = createZapierApi({
1882
+ baseUrl,
1883
+ token,
1884
+ getToken,
1885
+ debug,
1886
+ fetch: customFetch,
1887
+ onEvent
1888
+ });
1889
+ const baseSdk = {
1890
+ // Registry for CLI
1891
+ __registry: functionRegistry,
1892
+ // Function implementations with API config injection
1893
+ listApps: (options2 = {}) => listApps({ ...options2, api }),
1894
+ getApp: (options2) => getApp({ ...options2, api }),
1895
+ listActions: (options2 = {}) => listActions({ ...options2, api }),
1896
+ getAction: (options2) => getAction({ ...options2, api }),
1897
+ runAction: (options2) => runAction({ ...options2, api }),
1898
+ listAuthentications: (options2 = {}) => listAuthentications({ ...options2, api }),
1899
+ getAuthentication: (options2) => getAuthentication({ ...options2, api }),
1900
+ findFirstAuthentication: (options2 = {}) => findFirstAuthentication({ ...options2, api }),
1901
+ findUniqueAuthentication: (options2 = {}) => findUniqueAuthentication({ ...options2, api }),
1902
+ listFields: (options2) => listFields({ ...options2, api }),
1903
+ generateTypes: (options2) => generateTypes({ ...options2, api }),
1904
+ bundleCode: (options2) => bundleCode(options2),
1905
+ // No API config needed
1906
+ request: (options2) => request({ ...options2, api })
1907
+ };
1908
+ const fullSdk = baseSdk;
1909
+ fullSdk.apps = createAppsPlugin({ sdk: fullSdk });
1910
+ fullSdk.fetch = createFetchPlugin({ sdk: fullSdk });
1911
+ return fullSdk;
1912
+ }
1913
+
1914
+ export { ActionKeyPropertySchema, ActionTypePropertySchema, AppKeyPropertySchema, AppNotFoundError, AuthenticationIdPropertySchema, DebugPropertySchema, InputsPropertySchema, LimitPropertySchema, OffsetPropertySchema, OutputPropertySchema, ParamsPropertySchema, RelayFetchSchema, RelayRequestSchema, ZapierSdkError, actionKeyResolver, actionTypeResolver, appKeyResolver, authenticationIdResolver, bundleCode, createAppsPlugin, createFetchPlugin, createZapierSdk, findFirstAuthentication, findUniqueAuthentication, generateTypes, getAction, getApp, getAuthentication, getResolutionOrder, getResolutionOrderForParams, getResolvableParams, getResolver, getResolversForMissingParams, getTokenFromCliLogin, getTokenFromEnv, getTokenFromEnvOrConfig, hasResolver, inputsResolver, isPositional, listActions, listApps, listAuthentications, listFields, relayFetch, request, resolverRegistry, runAction };