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