@zapier/zapier-sdk 0.3.0 → 0.4.0

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