@zapier/zapier-sdk-cli 0.6.3 → 0.6.5

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 (95) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +115 -12
  3. package/bin/{zapier-sdk.js → zapier-sdk.mjs} +1 -1
  4. package/dist/cli.cjs +1715 -0
  5. package/dist/cli.d.mts +1 -0
  6. package/dist/cli.d.ts +1 -0
  7. package/dist/{cli.js → cli.mjs} +221 -469
  8. package/dist/index.cjs +770 -0
  9. package/dist/index.d.mts +12 -0
  10. package/dist/index.d.ts +12 -0
  11. package/dist/index.mjs +739 -0
  12. package/dist/package.json +67 -0
  13. package/dist/src/cli.js +8 -14
  14. package/dist/src/index.d.ts +1 -0
  15. package/dist/src/index.js +1 -1
  16. package/dist/src/plugins/bundleCode/index.d.ts +15 -0
  17. package/dist/src/{commands/bundle-code → plugins/bundleCode}/index.js +19 -1
  18. package/dist/src/{commands/bundle-code → plugins/bundleCode}/schemas.d.ts +8 -8
  19. package/dist/src/{commands/bundle-code → plugins/bundleCode}/schemas.js +4 -4
  20. package/dist/src/plugins/generateTypes/index.d.ts +21 -0
  21. package/dist/src/{commands/generate-types → plugins/generateTypes}/index.js +18 -0
  22. package/dist/src/{commands/generate-types → plugins/generateTypes}/schemas.d.ts +0 -3
  23. package/dist/src/{commands/generate-types → plugins/generateTypes}/schemas.js +1 -2
  24. package/dist/src/plugins/getConfigPath/index.d.ts +15 -0
  25. package/dist/src/plugins/getConfigPath/index.js +19 -0
  26. package/dist/src/plugins/getConfigPath/schemas.d.ts +3 -0
  27. package/dist/src/plugins/getConfigPath/schemas.js +5 -0
  28. package/dist/src/plugins/index.d.ts +6 -0
  29. package/dist/src/plugins/index.js +6 -0
  30. package/dist/src/plugins/login/index.d.ts +15 -0
  31. package/dist/src/plugins/login/index.js +26 -0
  32. package/dist/src/plugins/login/schemas.d.ts +9 -0
  33. package/dist/src/plugins/login/schemas.js +10 -0
  34. package/dist/src/plugins/logout/index.d.ts +15 -0
  35. package/dist/src/plugins/logout/index.js +18 -0
  36. package/dist/src/plugins/logout/schemas.d.ts +3 -0
  37. package/dist/src/plugins/logout/schemas.js +5 -0
  38. package/dist/src/plugins/mcp/index.d.ts +15 -0
  39. package/dist/src/plugins/mcp/index.js +24 -0
  40. package/dist/src/plugins/mcp/schemas.d.ts +9 -0
  41. package/dist/src/plugins/mcp/schemas.js +10 -0
  42. package/dist/src/sdk.d.ts +9 -0
  43. package/dist/src/sdk.js +22 -0
  44. package/dist/src/utils/cli-generator.js +12 -8
  45. package/dist/src/utils/schema-formatter.d.ts +1 -1
  46. package/dist/src/utils/schema-formatter.js +8 -8
  47. package/dist/tsconfig.tsbuildinfo +1 -1
  48. package/package.json +19 -8
  49. package/src/cli.ts +8 -21
  50. package/src/index.ts +2 -0
  51. package/src/{commands/bundle-code → plugins/bundleCode}/index.ts +39 -2
  52. package/src/{commands/bundle-code → plugins/bundleCode}/schemas.ts +4 -4
  53. package/src/{commands/generate-types → plugins/generateTypes}/index.ts +56 -3
  54. package/src/{commands/generate-types → plugins/generateTypes}/schemas.ts +0 -4
  55. package/src/plugins/getConfigPath/index.ts +42 -0
  56. package/src/plugins/getConfigPath/schemas.ts +8 -0
  57. package/src/plugins/index.ts +6 -0
  58. package/src/plugins/login/index.ts +48 -0
  59. package/src/plugins/login/schemas.ts +13 -0
  60. package/src/plugins/logout/index.ts +37 -0
  61. package/src/plugins/logout/schemas.ts +8 -0
  62. package/src/plugins/mcp/index.ts +43 -0
  63. package/src/plugins/mcp/schemas.ts +13 -0
  64. package/src/sdk.ts +43 -0
  65. package/src/utils/cli-generator.test.ts +93 -0
  66. package/src/utils/cli-generator.ts +19 -9
  67. package/src/utils/schema-formatter.ts +13 -7
  68. package/tsconfig.build.json +15 -3
  69. package/tsconfig.json +2 -2
  70. package/tsup.config.ts +10 -4
  71. package/bin/zsdk.js +0 -4
  72. package/dist/index.js +0 -0
  73. package/dist/src/commands/bundle-code/cli.d.ts +0 -2
  74. package/dist/src/commands/bundle-code/cli.js +0 -77
  75. package/dist/src/commands/bundle-code/index.d.ts +0 -5
  76. package/dist/src/commands/configPath.d.ts +0 -2
  77. package/dist/src/commands/configPath.js +0 -9
  78. package/dist/src/commands/generate-types/cli.d.ts +0 -2
  79. package/dist/src/commands/generate-types/cli.js +0 -84
  80. package/dist/src/commands/generate-types/index.d.ts +0 -8
  81. package/dist/src/commands/index.d.ts +0 -6
  82. package/dist/src/commands/index.js +0 -6
  83. package/dist/src/commands/login.d.ts +0 -2
  84. package/dist/src/commands/login.js +0 -25
  85. package/dist/src/commands/logout.d.ts +0 -2
  86. package/dist/src/commands/logout.js +0 -16
  87. package/dist/src/commands/mcp.d.ts +0 -2
  88. package/dist/src/commands/mcp.js +0 -11
  89. package/src/commands/bundle-code/cli.ts +0 -118
  90. package/src/commands/configPath.ts +0 -10
  91. package/src/commands/generate-types/cli.ts +0 -126
  92. package/src/commands/index.ts +0 -6
  93. package/src/commands/login.ts +0 -34
  94. package/src/commands/logout.ts +0 -19
  95. package/src/commands/mcp.ts +0 -14
package/dist/cli.cjs ADDED
@@ -0,0 +1,1715 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ var commander = require('commander');
5
+ var zod = require('zod');
6
+ var zapierSdk = require('@zapier/zapier-sdk');
7
+ var inquirer = require('inquirer');
8
+ var chalk3 = require('chalk');
9
+ var util = require('util');
10
+ var open = require('open');
11
+ var crypto = require('crypto');
12
+ var express = require('express');
13
+ var pkceChallenge = require('pkce-challenge');
14
+ var ora = require('ora');
15
+ var zapierSdkCliLogin = require('@zapier/zapier-sdk-cli-login');
16
+ var zapierSdkMcp = require('@zapier/zapier-sdk-mcp');
17
+ var fs = require('fs');
18
+ var path = require('path');
19
+ var esbuild = require('esbuild');
20
+
21
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
22
+
23
+ function _interopNamespace(e) {
24
+ if (e && e.__esModule) return e;
25
+ var n = Object.create(null);
26
+ if (e) {
27
+ Object.keys(e).forEach(function (k) {
28
+ if (k !== 'default') {
29
+ var d = Object.getOwnPropertyDescriptor(e, k);
30
+ Object.defineProperty(n, k, d.get ? d : {
31
+ enumerable: true,
32
+ get: function () { return e[k]; }
33
+ });
34
+ }
35
+ });
36
+ }
37
+ n.default = e;
38
+ return Object.freeze(n);
39
+ }
40
+
41
+ var inquirer__default = /*#__PURE__*/_interopDefault(inquirer);
42
+ var chalk3__default = /*#__PURE__*/_interopDefault(chalk3);
43
+ var util__default = /*#__PURE__*/_interopDefault(util);
44
+ var open__default = /*#__PURE__*/_interopDefault(open);
45
+ var crypto__default = /*#__PURE__*/_interopDefault(crypto);
46
+ var express__default = /*#__PURE__*/_interopDefault(express);
47
+ var pkceChallenge__default = /*#__PURE__*/_interopDefault(pkceChallenge);
48
+ var ora__default = /*#__PURE__*/_interopDefault(ora);
49
+ var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
50
+ var path__namespace = /*#__PURE__*/_interopNamespace(path);
51
+
52
+ var SchemaParameterResolver = class {
53
+ async resolveParameters(schema, providedParams, sdk2) {
54
+ const parseResult = schema.safeParse(providedParams);
55
+ const allParams = this.extractParametersFromSchema(schema);
56
+ const resolvableParams = allParams.filter(
57
+ (param) => zapierSdk.hasResolver(param.name)
58
+ );
59
+ const missingResolvable = resolvableParams.filter((param) => {
60
+ const hasValue = this.getNestedValue(providedParams, param.path) !== void 0;
61
+ return !hasValue;
62
+ });
63
+ const functionallyRequired = missingResolvable.filter((param) => {
64
+ if (param.isRequired) return true;
65
+ if (param.name === "inputs") {
66
+ return true;
67
+ }
68
+ return false;
69
+ });
70
+ const alwaysPrompt = missingResolvable.filter((param) => {
71
+ if (functionallyRequired.includes(param)) return false;
72
+ if (param.name === "authenticationId") {
73
+ return true;
74
+ }
75
+ return false;
76
+ });
77
+ const trulyOptional = missingResolvable.filter(
78
+ (param) => !functionallyRequired.includes(param) && !alwaysPrompt.includes(param)
79
+ );
80
+ if (parseResult.success && functionallyRequired.length === 0 && alwaysPrompt.length === 0) {
81
+ return parseResult.data;
82
+ }
83
+ if (functionallyRequired.length === 0 && alwaysPrompt.length === 0) {
84
+ if (!parseResult.success) {
85
+ throw parseResult.error;
86
+ }
87
+ return parseResult.data;
88
+ }
89
+ const resolvedParams = { ...providedParams };
90
+ const context = {
91
+ sdk: sdk2,
92
+ currentParams: providedParams,
93
+ resolvedParams
94
+ };
95
+ if (functionallyRequired.length > 0) {
96
+ const requiredParamNames = functionallyRequired.map((p) => p.name);
97
+ const requiredResolutionOrder = zapierSdk.getResolutionOrderForParams(requiredParamNames);
98
+ const orderedRequiredParams = requiredResolutionOrder.map((paramName) => {
99
+ let param = functionallyRequired.find((p) => p.name === paramName);
100
+ if (!param) {
101
+ param = alwaysPrompt.find((p) => p.name === paramName);
102
+ }
103
+ if (!param) {
104
+ param = trulyOptional.find((p) => p.name === paramName);
105
+ }
106
+ return param;
107
+ }).filter((param) => param !== void 0);
108
+ for (const param of orderedRequiredParams) {
109
+ try {
110
+ const value = await this.resolveParameter(param, context);
111
+ this.setNestedValue(resolvedParams, param.path, value);
112
+ context.resolvedParams = resolvedParams;
113
+ } catch (error) {
114
+ if (this.isUserCancellation(error)) {
115
+ console.log(chalk3__default.default.yellow("\n\nOperation cancelled by user"));
116
+ process.exit(0);
117
+ }
118
+ throw error;
119
+ }
120
+ }
121
+ const resolvedParamNames = new Set(
122
+ orderedRequiredParams.map((p) => p.name)
123
+ );
124
+ alwaysPrompt.splice(
125
+ 0,
126
+ alwaysPrompt.length,
127
+ ...alwaysPrompt.filter((p) => !resolvedParamNames.has(p.name))
128
+ );
129
+ trulyOptional.splice(
130
+ 0,
131
+ trulyOptional.length,
132
+ ...trulyOptional.filter((p) => !resolvedParamNames.has(p.name))
133
+ );
134
+ }
135
+ if (alwaysPrompt.length > 0) {
136
+ const alwaysPromptNames = alwaysPrompt.map((p) => p.name);
137
+ const alwaysPromptResolutionOrder = zapierSdk.getResolutionOrderForParams(alwaysPromptNames);
138
+ const orderedAlwaysPromptParams = alwaysPromptResolutionOrder.map((paramName) => alwaysPrompt.find((p) => p.name === paramName)).filter((param) => param !== void 0);
139
+ for (const param of orderedAlwaysPromptParams) {
140
+ try {
141
+ const value = await this.resolveParameter(param, context);
142
+ this.setNestedValue(resolvedParams, param.path, value);
143
+ context.resolvedParams = resolvedParams;
144
+ } catch (error) {
145
+ if (this.isUserCancellation(error)) {
146
+ console.log(chalk3__default.default.yellow("\n\nOperation cancelled by user"));
147
+ process.exit(0);
148
+ }
149
+ throw error;
150
+ }
151
+ }
152
+ }
153
+ if (trulyOptional.length > 0) {
154
+ const optionalNames = trulyOptional.map((p) => p.name).join(", ");
155
+ const shouldResolveOptional = await inquirer__default.default.prompt([
156
+ {
157
+ type: "confirm",
158
+ name: "resolveOptional",
159
+ message: `Would you like to be prompted for optional parameters (${optionalNames})?`,
160
+ default: false
161
+ }
162
+ ]);
163
+ if (shouldResolveOptional.resolveOptional) {
164
+ const optionalParamNames = trulyOptional.map((p) => p.name);
165
+ const optionalResolutionOrder = zapierSdk.getResolutionOrderForParams(optionalParamNames);
166
+ const orderedOptionalParams = optionalResolutionOrder.map((paramName) => trulyOptional.find((p) => p.name === paramName)).filter((param) => param !== void 0);
167
+ for (const param of orderedOptionalParams) {
168
+ try {
169
+ const value = await this.resolveParameter(param, context);
170
+ this.setNestedValue(resolvedParams, param.path, value);
171
+ context.resolvedParams = resolvedParams;
172
+ } catch (error) {
173
+ if (this.isUserCancellation(error)) {
174
+ console.log(chalk3__default.default.yellow("\n\nOperation cancelled by user"));
175
+ process.exit(0);
176
+ }
177
+ throw error;
178
+ }
179
+ }
180
+ }
181
+ }
182
+ const finalResult = schema.safeParse(resolvedParams);
183
+ if (!finalResult.success) {
184
+ console.error(
185
+ chalk3__default.default.red("\u274C Parameter validation failed after resolution:")
186
+ );
187
+ throw finalResult.error;
188
+ }
189
+ return finalResult.data;
190
+ }
191
+ extractParametersFromSchema(schema) {
192
+ const parameters = [];
193
+ if (schema instanceof zod.z.ZodObject) {
194
+ const shape = schema.shape;
195
+ for (const [key, fieldSchema] of Object.entries(shape)) {
196
+ const param = this.analyzeFieldSchema(key, fieldSchema);
197
+ if (param) {
198
+ parameters.push(param);
199
+ }
200
+ }
201
+ }
202
+ return parameters;
203
+ }
204
+ analyzeFieldSchema(fieldName, fieldSchema) {
205
+ let baseSchema = fieldSchema;
206
+ let isRequired = true;
207
+ if (baseSchema instanceof zod.z.ZodOptional) {
208
+ isRequired = false;
209
+ baseSchema = baseSchema._def.innerType;
210
+ }
211
+ if (baseSchema instanceof zod.z.ZodDefault) {
212
+ isRequired = false;
213
+ baseSchema = baseSchema._def.innerType;
214
+ }
215
+ return this.createResolvableParameter([fieldName], baseSchema, isRequired);
216
+ }
217
+ createResolvableParameter(path3, schema, isRequired) {
218
+ if (path3.length === 0) return null;
219
+ const name = path3[path3.length - 1];
220
+ return {
221
+ name,
222
+ path: path3,
223
+ schema,
224
+ description: schema.description,
225
+ isRequired
226
+ };
227
+ }
228
+ async resolveParameter(param, context) {
229
+ const resolver = zapierSdk.getResolver(param.name);
230
+ if (!resolver) {
231
+ throw new Error(`No resolver found for parameter: ${param.name}`);
232
+ }
233
+ console.log(chalk3__default.default.blue(`
234
+ \u{1F50D} Resolving ${param.name}...`));
235
+ const typedResolver = resolver;
236
+ if (typedResolver.type === "static") {
237
+ const promptConfig = {
238
+ type: typedResolver.inputType === "password" ? "password" : "input",
239
+ name: param.name,
240
+ message: `Enter ${param.name}:`,
241
+ ...typedResolver.placeholder && {
242
+ default: typedResolver.placeholder
243
+ }
244
+ };
245
+ const answers = await inquirer__default.default.prompt([promptConfig]);
246
+ return answers[param.name];
247
+ } else if (typedResolver.type === "dynamic") {
248
+ try {
249
+ if (param.isRequired && param.name !== "authenticationId") {
250
+ console.log(chalk3__default.default.gray(`Fetching options for ${param.name}...`));
251
+ }
252
+ const items = await typedResolver.fetch(
253
+ context.sdk,
254
+ context.resolvedParams
255
+ );
256
+ const safeItems = items || [];
257
+ const promptConfig = typedResolver.prompt(
258
+ safeItems,
259
+ context.resolvedParams
260
+ );
261
+ const answers = await inquirer__default.default.prompt([promptConfig]);
262
+ return answers[param.name];
263
+ } catch (error) {
264
+ throw error;
265
+ }
266
+ } else if (typedResolver.type === "fields") {
267
+ return await this.resolveFieldsRecursively(
268
+ resolver,
269
+ context,
270
+ param
271
+ );
272
+ }
273
+ throw new Error(`Unknown resolver type for ${param.name}`);
274
+ }
275
+ async resolveFieldsRecursively(resolver, context, param) {
276
+ const typedResolver = resolver;
277
+ const inputs = {};
278
+ let processedFieldKeys = /* @__PURE__ */ new Set();
279
+ let iteration = 0;
280
+ const maxIterations = 5;
281
+ while (iteration < maxIterations) {
282
+ iteration++;
283
+ const updatedContext = {
284
+ ...context,
285
+ resolvedParams: {
286
+ ...context.resolvedParams,
287
+ inputs
288
+ }
289
+ };
290
+ console.log(
291
+ chalk3__default.default.gray(
292
+ `Fetching input fields for ${param.name}${iteration > 1 ? ` (iteration ${iteration})` : ""}...`
293
+ )
294
+ );
295
+ const fields = await typedResolver.fetch(
296
+ updatedContext.sdk,
297
+ updatedContext.resolvedParams
298
+ );
299
+ if (!fields || fields.length === 0) {
300
+ if (iteration === 1) {
301
+ console.log(
302
+ chalk3__default.default.yellow(`No input fields required for this action.`)
303
+ );
304
+ }
305
+ break;
306
+ }
307
+ const newFields = fields.filter(
308
+ (field) => !(field.key && processedFieldKeys.has(field.key))
309
+ );
310
+ if (newFields.length === 0) {
311
+ break;
312
+ }
313
+ const newRequiredFields = newFields.filter(
314
+ (field) => field.required
315
+ );
316
+ const newOptionalFields = newFields.filter(
317
+ (field) => !field.required
318
+ );
319
+ if (newRequiredFields.length > 0) {
320
+ console.log(
321
+ chalk3__default.default.blue(
322
+ `
323
+ \u{1F4DD} Please provide values for the following ${iteration === 1 ? "" : "additional "}input fields:`
324
+ )
325
+ );
326
+ for (const field of newRequiredFields) {
327
+ await this.promptForField(field, inputs);
328
+ processedFieldKeys.add(field.key);
329
+ }
330
+ }
331
+ let shouldConfigureOptional = { configure: false };
332
+ if (newOptionalFields.length > 0) {
333
+ console.log(
334
+ chalk3__default.default.gray(
335
+ `
336
+ There are ${newOptionalFields.length} ${iteration === 1 ? "" : "additional "}optional field(s) available.`
337
+ )
338
+ );
339
+ try {
340
+ shouldConfigureOptional = await inquirer__default.default.prompt([
341
+ {
342
+ type: "confirm",
343
+ name: "configure",
344
+ message: `Would you like to configure ${iteration === 1 ? "" : "these additional "}optional fields?`,
345
+ default: false
346
+ }
347
+ ]);
348
+ } catch (error) {
349
+ if (this.isUserCancellation(error)) {
350
+ console.log(chalk3__default.default.yellow("\n\nOperation cancelled by user"));
351
+ process.exit(0);
352
+ }
353
+ throw error;
354
+ }
355
+ if (shouldConfigureOptional.configure) {
356
+ console.log(chalk3__default.default.cyan(`
357
+ Optional fields:`));
358
+ for (const field of newOptionalFields) {
359
+ await this.promptForField(field, inputs);
360
+ processedFieldKeys.add(field.key);
361
+ }
362
+ } else {
363
+ newOptionalFields.forEach(
364
+ (field) => processedFieldKeys.add(field.key)
365
+ );
366
+ }
367
+ }
368
+ if (newRequiredFields.length === 0 && (!newOptionalFields.length || !shouldConfigureOptional.configure)) {
369
+ break;
370
+ }
371
+ }
372
+ if (iteration >= maxIterations) {
373
+ console.log(
374
+ chalk3__default.default.yellow(
375
+ `
376
+ \u26A0\uFE0F Maximum field resolution iterations reached. Some dynamic fields may not have been discovered.`
377
+ )
378
+ );
379
+ }
380
+ return inputs;
381
+ }
382
+ getNestedValue(obj, path3) {
383
+ return path3.reduce(
384
+ (current, key) => current?.[key],
385
+ obj
386
+ );
387
+ }
388
+ setNestedValue(obj, path3, value) {
389
+ const lastKey = path3[path3.length - 1];
390
+ const parent = path3.slice(0, -1).reduce((current, key) => {
391
+ const currentObj = current;
392
+ if (!(key in currentObj)) {
393
+ currentObj[key] = {};
394
+ }
395
+ return currentObj[key];
396
+ }, obj);
397
+ parent[lastKey] = value;
398
+ }
399
+ async promptForField(field, inputs) {
400
+ const fieldObj = field;
401
+ const fieldPrompt = {
402
+ type: fieldObj.type === "boolean" ? "confirm" : "input",
403
+ name: fieldObj.key,
404
+ message: `${fieldObj.label || fieldObj.key}${fieldObj.required ? " (required)" : " (optional)"}:`
405
+ };
406
+ if (fieldObj.helpText) {
407
+ fieldPrompt.prefix = chalk3__default.default.gray(`\u2139 ${fieldObj.helpText}
408
+ `);
409
+ }
410
+ if (fieldObj.default !== void 0) {
411
+ fieldPrompt.default = fieldObj.default;
412
+ }
413
+ if (fieldObj.choices && fieldObj.choices.length > 0) {
414
+ fieldPrompt.type = "list";
415
+ fieldPrompt.choices = fieldObj.choices.map(
416
+ (choice) => {
417
+ const choiceObj = choice;
418
+ return {
419
+ name: choiceObj.label || choiceObj.value,
420
+ value: choiceObj.value
421
+ };
422
+ }
423
+ );
424
+ }
425
+ try {
426
+ const answer = await inquirer__default.default.prompt([fieldPrompt]);
427
+ if (answer[fieldObj.key] !== void 0 && answer[fieldObj.key] !== "") {
428
+ inputs[fieldObj.key] = answer[fieldObj.key];
429
+ } else if (fieldObj.required) {
430
+ throw new Error(`Required field ${fieldObj.key} cannot be empty`);
431
+ }
432
+ } catch (error) {
433
+ if (this.isUserCancellation(error)) {
434
+ console.log(chalk3__default.default.yellow("\n\nOperation cancelled by user"));
435
+ process.exit(0);
436
+ }
437
+ throw error;
438
+ }
439
+ }
440
+ isUserCancellation(error) {
441
+ const errorObj = error;
442
+ return errorObj?.name === "ExitPromptError" || errorObj?.message?.includes("User force closed") || errorObj?.isTTYError === true;
443
+ }
444
+ };
445
+ function getFormatMetadata(schema) {
446
+ return schema?._def?.formatMeta;
447
+ }
448
+ function getOutputSchema(schema) {
449
+ return schema?._def?.outputSchema;
450
+ }
451
+ function formatItemsFromSchema(inputSchema, items, startingNumber = 0) {
452
+ const outputSchema = getOutputSchema(inputSchema);
453
+ if (!outputSchema) {
454
+ formatItemsGeneric(items, startingNumber);
455
+ return;
456
+ }
457
+ const formatMeta = getFormatMetadata(outputSchema);
458
+ if (!formatMeta) {
459
+ formatItemsGeneric(items, startingNumber);
460
+ return;
461
+ }
462
+ items.forEach((item, index) => {
463
+ formatSingleItem(item, startingNumber + index, formatMeta);
464
+ });
465
+ }
466
+ function formatSingleItem(item, itemNumber, formatMeta) {
467
+ const formatted = formatMeta.format(item);
468
+ let titleLine = `${chalk3__default.default.gray(`${itemNumber + 1}.`)} ${chalk3__default.default.cyan(formatted.title)}`;
469
+ if (formatted.subtitle) {
470
+ titleLine += ` ${chalk3__default.default.gray(formatted.subtitle)}`;
471
+ }
472
+ console.log(titleLine);
473
+ for (const detail of formatted.details) {
474
+ const styledText = applyStyle(detail.text, detail.style);
475
+ console.log(` ${styledText}`);
476
+ }
477
+ console.log();
478
+ }
479
+ function applyStyle(value, style) {
480
+ switch (style) {
481
+ case "dim":
482
+ return chalk3__default.default.dim(value);
483
+ case "accent":
484
+ return chalk3__default.default.magenta(value);
485
+ case "warning":
486
+ return chalk3__default.default.red(value);
487
+ case "success":
488
+ return chalk3__default.default.green(value);
489
+ case "normal":
490
+ default:
491
+ return chalk3__default.default.blue(value);
492
+ }
493
+ }
494
+ function formatItemsGeneric(items, startingNumber = 0) {
495
+ items.forEach((item, index) => {
496
+ const itemObj = item;
497
+ const name = itemObj.title || itemObj.name || itemObj.key || itemObj.id || "Item";
498
+ console.log(
499
+ `${chalk3__default.default.gray(`${startingNumber + index + 1}.`)} ${chalk3__default.default.cyan(name)}`
500
+ );
501
+ if (itemObj.description) {
502
+ console.log(` ${chalk3__default.default.dim(itemObj.description)}`);
503
+ }
504
+ console.log();
505
+ });
506
+ }
507
+ function formatJsonOutput(data) {
508
+ if (data === void 0) {
509
+ return;
510
+ }
511
+ if (data && typeof data === "object" && !Array.isArray(data) && (data.success !== void 0 || data.id || data.status)) {
512
+ console.log(chalk3__default.default.green("\u2705 Action completed successfully!\n"));
513
+ }
514
+ console.log(
515
+ util__default.default.inspect(data, { colors: true, depth: null, breakLength: 80 })
516
+ );
517
+ }
518
+ function analyzeZodSchema(schema) {
519
+ const parameters = [];
520
+ if (schema instanceof zod.z.ZodObject) {
521
+ const shape = schema.shape;
522
+ for (const [key, fieldSchema] of Object.entries(shape)) {
523
+ const param = analyzeZodField(key, fieldSchema);
524
+ if (param) {
525
+ parameters.push(param);
526
+ }
527
+ }
528
+ }
529
+ return parameters;
530
+ }
531
+ function analyzeZodField(name, schema) {
532
+ let baseSchema = schema;
533
+ let required = true;
534
+ let defaultValue = void 0;
535
+ if (baseSchema instanceof zod.z.ZodOptional) {
536
+ required = false;
537
+ baseSchema = baseSchema._def.innerType;
538
+ }
539
+ if (baseSchema instanceof zod.z.ZodDefault) {
540
+ required = false;
541
+ defaultValue = baseSchema._def.defaultValue();
542
+ baseSchema = baseSchema._def.innerType;
543
+ }
544
+ let paramType = "string";
545
+ let choices;
546
+ if (baseSchema instanceof zod.z.ZodString) {
547
+ paramType = "string";
548
+ } else if (baseSchema instanceof zod.z.ZodNumber) {
549
+ paramType = "number";
550
+ } else if (baseSchema instanceof zod.z.ZodBoolean) {
551
+ paramType = "boolean";
552
+ } else if (baseSchema instanceof zod.z.ZodArray) {
553
+ paramType = "array";
554
+ } else if (baseSchema instanceof zod.z.ZodEnum) {
555
+ paramType = "string";
556
+ choices = baseSchema._def.values;
557
+ } else if (baseSchema instanceof zod.z.ZodRecord) {
558
+ paramType = "string";
559
+ }
560
+ return {
561
+ name,
562
+ type: paramType,
563
+ required,
564
+ description: schema.description,
565
+ default: defaultValue,
566
+ choices,
567
+ hasResolver: zapierSdk.hasResolver(name),
568
+ isPositional: zapierSdk.isPositional(schema)
569
+ };
570
+ }
571
+ function toKebabCase(str) {
572
+ return str.replace(/([A-Z])/g, "-$1").toLowerCase();
573
+ }
574
+ function methodNameToCliCommand(methodName) {
575
+ return toKebabCase(methodName);
576
+ }
577
+ function generateCliCommands(program2, sdk2) {
578
+ if (typeof sdk2.getRegistry !== "function") {
579
+ console.error("SDK registry not available");
580
+ return;
581
+ }
582
+ const registry = sdk2.getRegistry();
583
+ registry.functions.forEach((fnInfo) => {
584
+ if (!fnInfo.inputSchema) {
585
+ console.warn(`Schema not found for ${fnInfo.name}`);
586
+ return;
587
+ }
588
+ const cliCommandName = methodNameToCliCommand(fnInfo.name);
589
+ const config = createCommandConfig(
590
+ cliCommandName,
591
+ fnInfo.name,
592
+ fnInfo.inputSchema,
593
+ sdk2
594
+ );
595
+ addCommand(program2, cliCommandName, config);
596
+ });
597
+ program2.configureHelp({
598
+ formatHelp: (cmd, helper) => {
599
+ const helpWidth = helper.helpWidth || 80;
600
+ let output = helper.commandUsage(cmd) + "\n";
601
+ if (cmd.description()) {
602
+ output += helper.wrap(cmd.description(), helpWidth, 0) + "\n";
603
+ }
604
+ const options = helper.visibleOptions(cmd);
605
+ if (options.length > 0) {
606
+ output += "\nOptions:\n";
607
+ const longestOptionLength = Math.max(
608
+ ...options.map((opt) => helper.optionTerm(opt).length)
609
+ );
610
+ options.forEach((option) => {
611
+ const term = helper.optionTerm(option);
612
+ const padding = " ".repeat(
613
+ Math.max(2, longestOptionLength - term.length + 4)
614
+ );
615
+ output += ` ${term}${padding}${helper.optionDescription(option)}
616
+ `;
617
+ });
618
+ }
619
+ const commands = helper.visibleCommands(cmd);
620
+ if (commands.length > 0) {
621
+ output += "\nCommands:\n";
622
+ const categorizedCommands = /* @__PURE__ */ new Set();
623
+ registry.categories.forEach((category) => {
624
+ const categoryCommands = commands.filter(
625
+ (command) => category.functions.some((functionName) => {
626
+ const cliCommandName = methodNameToCliCommand(functionName);
627
+ return command.name() === cliCommandName;
628
+ })
629
+ );
630
+ if (categoryCommands.length > 0) {
631
+ output += `
632
+ ${category.titlePlural}:
633
+ `;
634
+ categoryCommands.forEach((command) => {
635
+ output += ` ${helper.subcommandTerm(command)}
636
+ `;
637
+ categorizedCommands.add(command.name());
638
+ });
639
+ }
640
+ });
641
+ const otherCommands = commands.filter(
642
+ (command) => !categorizedCommands.has(command.name())
643
+ );
644
+ if (otherCommands.length > 0) {
645
+ output += `
646
+ Other:
647
+ `;
648
+ otherCommands.forEach((command) => {
649
+ output += ` ${helper.subcommandTerm(command)}
650
+ `;
651
+ });
652
+ }
653
+ }
654
+ return output;
655
+ }
656
+ });
657
+ }
658
+ function createCommandConfig(cliCommandName, sdkMethodName, schema, sdk2) {
659
+ const parameters = analyzeZodSchema(schema);
660
+ const description = schema.description || `${cliCommandName} command`;
661
+ const handler = async (...args) => {
662
+ try {
663
+ const commandObj = args[args.length - 1];
664
+ const options = commandObj.opts();
665
+ const isListCommand = cliCommandName.startsWith("list-");
666
+ const hasPaginationParams = parameters.some(
667
+ (p) => p.name === "maxItems" || p.name === "pageSize"
668
+ );
669
+ const hasUserSpecifiedMaxItems = "maxItems" in options && options.maxItems !== void 0;
670
+ const shouldUseJson = options.json;
671
+ const rawParams = convertCliArgsToSdkParams(
672
+ parameters,
673
+ args.slice(0, -1),
674
+ options
675
+ );
676
+ const resolver = new SchemaParameterResolver();
677
+ const resolvedParams = await resolver.resolveParameters(
678
+ schema,
679
+ rawParams,
680
+ sdk2
681
+ );
682
+ if (isListCommand && hasPaginationParams && !shouldUseJson && !hasUserSpecifiedMaxItems) {
683
+ const sdkObj = sdk2;
684
+ const sdkIterator = sdkObj[sdkMethodName](resolvedParams);
685
+ await handlePaginatedListWithAsyncIteration(
686
+ sdkMethodName,
687
+ sdkIterator,
688
+ schema
689
+ );
690
+ } else {
691
+ const hasOutputFile = resolvedParams.output;
692
+ if (hasOutputFile) {
693
+ const sdkObj2 = sdk2;
694
+ await sdkObj2[sdkMethodName](resolvedParams);
695
+ console.log(
696
+ chalk3__default.default.green(`\u2705 ${cliCommandName} completed successfully!`)
697
+ );
698
+ console.log(chalk3__default.default.gray(`Output written to: ${hasOutputFile}`));
699
+ return;
700
+ }
701
+ const sdkObj = sdk2;
702
+ const result = await sdkObj[sdkMethodName](resolvedParams);
703
+ const items = result?.data ? result.data : result;
704
+ if (shouldUseJson) {
705
+ console.log(JSON.stringify(items, null, 2));
706
+ } else if (isListCommand) {
707
+ formatNonPaginatedResults(
708
+ items,
709
+ resolvedParams.maxItems,
710
+ hasUserSpecifiedMaxItems,
711
+ shouldUseJson,
712
+ schema,
713
+ sdkMethodName
714
+ );
715
+ } else {
716
+ formatJsonOutput(items);
717
+ }
718
+ }
719
+ } catch (error) {
720
+ if (error instanceof Error && error.message.includes('"code"')) {
721
+ try {
722
+ const validationErrors = JSON.parse(error.message);
723
+ console.error(chalk3__default.default.red("\u274C Validation Error:"));
724
+ validationErrors.forEach((err) => {
725
+ const errorObj = err;
726
+ const field = errorObj?.path?.join(".") || "unknown";
727
+ console.error(
728
+ chalk3__default.default.yellow(
729
+ ` \u2022 ${field}: ${errorObj?.message || "Unknown error"}`
730
+ )
731
+ );
732
+ });
733
+ console.error(
734
+ "\n" + chalk3__default.default.dim(`Use --help to see available options`)
735
+ );
736
+ } catch {
737
+ console.error(chalk3__default.default.red("Error:"), error.message);
738
+ }
739
+ } else if (error instanceof zapierSdk.ZapierError) {
740
+ const formattedMessage = zapierSdk.formatErrorMessage(error);
741
+ console.error(chalk3__default.default.red("\u274C Error:"), formattedMessage);
742
+ } else {
743
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
744
+ console.error(chalk3__default.default.red("\u274C Error:"), errorMessage);
745
+ }
746
+ process.exit(1);
747
+ }
748
+ };
749
+ return {
750
+ description,
751
+ parameters,
752
+ handler
753
+ };
754
+ }
755
+ function addCommand(program2, commandName, config) {
756
+ const command = program2.command(commandName).description(config.description);
757
+ config.parameters.forEach((param) => {
758
+ const kebabName = param.name.replace(/([A-Z])/g, "-$1").toLowerCase();
759
+ if (param.hasResolver && param.required) {
760
+ command.argument(
761
+ `[${kebabName}]`,
762
+ param.description || `${kebabName} parameter`
763
+ );
764
+ } else if (param.required) {
765
+ command.argument(
766
+ `<${kebabName}>`,
767
+ param.description || `${kebabName} parameter`
768
+ );
769
+ } else if (param.isPositional) {
770
+ command.argument(
771
+ `[${kebabName}]`,
772
+ param.description || `${kebabName} parameter`
773
+ );
774
+ } else {
775
+ const flags = [`--${kebabName}`];
776
+ if (param.type === "boolean") {
777
+ command.option(flags.join(", "), param.description);
778
+ } else if (param.type === "array") {
779
+ const flagSignature = flags.join(", ") + ` <values...>`;
780
+ command.option(
781
+ flagSignature,
782
+ param.description,
783
+ param.default
784
+ );
785
+ } else {
786
+ const flagSignature = flags.join(", ") + ` <${param.type}>`;
787
+ command.option(
788
+ flagSignature,
789
+ param.description || "",
790
+ param.default
791
+ );
792
+ }
793
+ }
794
+ });
795
+ command.option("--json", "Output raw JSON instead of formatted results");
796
+ command.action(config.handler);
797
+ }
798
+ function convertCliArgsToSdkParams(parameters, positionalArgs, options) {
799
+ const sdkParams = {};
800
+ let argIndex = 0;
801
+ parameters.forEach((param) => {
802
+ if ((param.required || param.isPositional) && argIndex < positionalArgs.length) {
803
+ sdkParams[param.name] = convertValue(
804
+ positionalArgs[argIndex],
805
+ param.type
806
+ );
807
+ argIndex++;
808
+ }
809
+ });
810
+ Object.entries(options).forEach(([key, value]) => {
811
+ const camelKey = key.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
812
+ const param = parameters.find((p) => p.name === camelKey);
813
+ if (param && value !== void 0) {
814
+ sdkParams[camelKey] = convertValue(value, param.type);
815
+ }
816
+ });
817
+ return sdkParams;
818
+ }
819
+ function convertValue(value, type) {
820
+ switch (type) {
821
+ case "number":
822
+ return Number(value);
823
+ case "boolean":
824
+ return Boolean(value);
825
+ case "array":
826
+ return Array.isArray(value) ? value : [value];
827
+ case "string":
828
+ default:
829
+ if (typeof value === "string" && (value.startsWith("{") || value.startsWith("["))) {
830
+ try {
831
+ return JSON.parse(value);
832
+ } catch {
833
+ return value;
834
+ }
835
+ }
836
+ return value;
837
+ }
838
+ }
839
+ async function handlePaginatedListWithAsyncIteration(sdkMethodName, sdkResult, schema) {
840
+ const itemName = getItemNameFromMethod(sdkMethodName);
841
+ let totalShown = 0;
842
+ let pageCount = 0;
843
+ console.log(chalk3__default.default.blue(`\u{1F4CB} ${getListTitleFromMethod(sdkMethodName)}
844
+ `));
845
+ try {
846
+ for await (const page of sdkResult) {
847
+ const items = page.data || page;
848
+ pageCount++;
849
+ if (!Array.isArray(items)) {
850
+ console.log(chalk3__default.default.yellow(`No ${itemName} found.`));
851
+ return;
852
+ }
853
+ if (items.length === 0 && pageCount === 1) {
854
+ console.log(chalk3__default.default.yellow(`No ${itemName} found.`));
855
+ return;
856
+ }
857
+ if (items.length === 0) {
858
+ break;
859
+ }
860
+ if (pageCount > 1) {
861
+ console.clear();
862
+ console.log(
863
+ chalk3__default.default.blue(`\u{1F4CB} ${getListTitleFromMethod(sdkMethodName)}
864
+ `)
865
+ );
866
+ }
867
+ if (schema) {
868
+ formatItemsFromSchema(schema, items, totalShown);
869
+ } else {
870
+ formatItemsGeneric2(items, totalShown);
871
+ }
872
+ totalShown += items.length;
873
+ console.log(
874
+ chalk3__default.default.green(
875
+ `
876
+ \u2705 Showing ${totalShown} ${itemName} (page ${pageCount})`
877
+ )
878
+ );
879
+ if (page.nextCursor) {
880
+ const { continueReading } = await inquirer__default.default.prompt([
881
+ {
882
+ type: "confirm",
883
+ name: "continueReading",
884
+ message: `Load next page?`,
885
+ default: true
886
+ }
887
+ ]);
888
+ if (!continueReading) {
889
+ break;
890
+ }
891
+ } else {
892
+ break;
893
+ }
894
+ }
895
+ console.log(chalk3__default.default.gray(`
896
+ \u{1F4C4} Finished browsing ${itemName}`));
897
+ } catch (error) {
898
+ const items = sdkResult?.data || sdkResult;
899
+ if (Array.isArray(items)) {
900
+ if (items.length === 0) {
901
+ console.log(chalk3__default.default.yellow(`No ${itemName} found.`));
902
+ return;
903
+ }
904
+ if (schema) {
905
+ formatItemsFromSchema(schema, items, 0);
906
+ } else {
907
+ formatItemsGeneric2(items, 0);
908
+ }
909
+ console.log(chalk3__default.default.green(`
910
+ \u2705 Showing ${items.length} ${itemName}`));
911
+ } else {
912
+ throw error;
913
+ }
914
+ }
915
+ }
916
+ function formatNonPaginatedResults(result, requestedMaxItems, userSpecifiedMaxItems, useRawJson, schema, methodName) {
917
+ if (!Array.isArray(result)) {
918
+ if (useRawJson) {
919
+ console.log(JSON.stringify(result, null, 2));
920
+ } else {
921
+ formatJsonOutput(result);
922
+ }
923
+ return;
924
+ }
925
+ if (useRawJson) {
926
+ console.log(JSON.stringify(result, null, 2));
927
+ return;
928
+ }
929
+ const itemName = methodName ? getItemNameFromMethod(methodName) : "items";
930
+ if (result.length === 0) {
931
+ console.log(chalk3__default.default.yellow(`No ${itemName} found.`));
932
+ return;
933
+ }
934
+ console.log(chalk3__default.default.green(`
935
+ \u2705 Found ${result.length} ${itemName}:
936
+ `));
937
+ if (schema) {
938
+ formatItemsFromSchema(schema, result);
939
+ } else {
940
+ formatItemsGeneric2(result);
941
+ }
942
+ if (userSpecifiedMaxItems && requestedMaxItems) {
943
+ console.log(
944
+ chalk3__default.default.gray(
945
+ `
946
+ \u{1F4C4} Showing up to ${requestedMaxItems} ${itemName} (--max-items ${requestedMaxItems})`
947
+ )
948
+ );
949
+ } else {
950
+ console.log(chalk3__default.default.gray(`
951
+ \u{1F4C4} All available ${itemName} shown`));
952
+ }
953
+ }
954
+ function formatItemsGeneric2(items, startingNumber = 0) {
955
+ items.forEach((item, index) => {
956
+ const itemObj = item;
957
+ const name = itemObj?.name || itemObj?.key || itemObj?.id || "Item";
958
+ console.log(
959
+ `${chalk3__default.default.gray(`${startingNumber + index + 1}.`)} ${chalk3__default.default.cyan(String(name))}`
960
+ );
961
+ if (itemObj?.description) {
962
+ console.log(` ${chalk3__default.default.dim(String(itemObj.description))}`);
963
+ }
964
+ console.log();
965
+ });
966
+ }
967
+ function getItemNameFromMethod(methodName) {
968
+ const listMatch = methodName.match(/^list(.+)$/);
969
+ if (listMatch) {
970
+ return listMatch[1].toLowerCase();
971
+ }
972
+ return "items";
973
+ }
974
+ function getListTitleFromMethod(methodName) {
975
+ const itemName = getItemNameFromMethod(methodName);
976
+ if (itemName === "items") return "Available Items";
977
+ const capitalized = itemName.charAt(0).toUpperCase() + itemName.slice(1);
978
+ return `Available ${capitalized}`;
979
+ }
980
+
981
+ // src/utils/constants.ts
982
+ var ZAPIER_BASE = "https://zapier.com";
983
+ var LOGIN_CLIENT_ID = "K5eEnRE9TTmSFATdkkWhKF8NOKwoiOnYAyIqJjae";
984
+ var LOGIN_PORTS = [49505, 50575, 52804, 55981, 61010, 63851];
985
+ var LOGIN_TIMEOUT_MS = 3e5;
986
+ var AUTH_MODE_HEADER = "X-Auth";
987
+ var spinPromise = async (promise, text) => {
988
+ const spinner = ora__default.default(text).start();
989
+ try {
990
+ const result = await promise;
991
+ spinner.succeed();
992
+ return result;
993
+ } catch (error) {
994
+ spinner.fail();
995
+ throw error;
996
+ }
997
+ };
998
+ var log = {
999
+ info: (message, ...args) => {
1000
+ console.log(chalk3__default.default.blue("\u2139"), message, ...args);
1001
+ },
1002
+ error: (message, ...args) => {
1003
+ console.error(chalk3__default.default.red("\u2716"), message, ...args);
1004
+ },
1005
+ success: (message, ...args) => {
1006
+ console.log(chalk3__default.default.green("\u2713"), message, ...args);
1007
+ },
1008
+ warn: (message, ...args) => {
1009
+ console.log(chalk3__default.default.yellow("\u26A0"), message, ...args);
1010
+ }
1011
+ };
1012
+ var log_default = log;
1013
+
1014
+ // src/utils/api/client.ts
1015
+ var createApiClient = () => {
1016
+ const post = async (url, data, options = {}) => {
1017
+ const { headers = {} } = options;
1018
+ const response = await fetch(url, {
1019
+ method: "POST",
1020
+ headers: {
1021
+ "Content-Type": "application/x-www-form-urlencoded",
1022
+ Connection: "close",
1023
+ ...headers
1024
+ },
1025
+ body: new URLSearchParams(data)
1026
+ });
1027
+ if (!response.ok) {
1028
+ throw new Error(`${response.status} ${response.statusText}`);
1029
+ }
1030
+ const responseData = await response.json();
1031
+ return {
1032
+ data: responseData,
1033
+ status: response.status
1034
+ };
1035
+ };
1036
+ return {
1037
+ post
1038
+ };
1039
+ };
1040
+ var api = createApiClient();
1041
+ var client_default = api;
1042
+
1043
+ // src/utils/getCallablePromise.ts
1044
+ var getCallablePromise = () => {
1045
+ let resolve2 = () => {
1046
+ };
1047
+ let reject = () => {
1048
+ };
1049
+ const promise = new Promise((_resolve, _reject) => {
1050
+ resolve2 = _resolve;
1051
+ reject = _reject;
1052
+ });
1053
+ return {
1054
+ promise,
1055
+ resolve: resolve2,
1056
+ reject
1057
+ };
1058
+ };
1059
+ var getCallablePromise_default = getCallablePromise;
1060
+ var findAvailablePort = () => {
1061
+ return new Promise((resolve2, reject) => {
1062
+ let portIndex = 0;
1063
+ const tryPort = (port) => {
1064
+ const server = express__default.default().listen(port, () => {
1065
+ server.close();
1066
+ resolve2(port);
1067
+ });
1068
+ server.on("error", (err) => {
1069
+ if (err.code === "EADDRINUSE") {
1070
+ if (portIndex < LOGIN_PORTS.length) {
1071
+ tryPort(LOGIN_PORTS[portIndex++]);
1072
+ } else {
1073
+ reject(
1074
+ new Error(
1075
+ `All configured OAuth callback ports are busy: ${LOGIN_PORTS.join(", ")}. Please try again later or close applications using these ports.`
1076
+ )
1077
+ );
1078
+ }
1079
+ } else {
1080
+ reject(err);
1081
+ }
1082
+ });
1083
+ };
1084
+ if (LOGIN_PORTS.length > 0) {
1085
+ tryPort(LOGIN_PORTS[portIndex++]);
1086
+ } else {
1087
+ reject(new Error("No OAuth callback ports configured"));
1088
+ }
1089
+ });
1090
+ };
1091
+ var generateRandomString = () => {
1092
+ const array = new Uint32Array(28);
1093
+ crypto__default.default.getRandomValues(array);
1094
+ return Array.from(
1095
+ array,
1096
+ (dec) => ("0" + dec.toString(16)).substring(-2)
1097
+ ).join("");
1098
+ };
1099
+ var login = async (timeoutMs = LOGIN_TIMEOUT_MS) => {
1100
+ zapierSdkCliLogin.logout();
1101
+ const availablePort = await findAvailablePort();
1102
+ const redirectUri = `http://localhost:${availablePort}/oauth`;
1103
+ log_default.info(`Using port ${availablePort} for OAuth callback`);
1104
+ const { promise: promisedCode, resolve: setCode } = getCallablePromise_default();
1105
+ const app = express__default.default();
1106
+ app.get("/oauth", (req, res) => {
1107
+ setCode(String(req.query.code));
1108
+ res.setHeader("Connection", "close");
1109
+ res.end("You can now close this tab and return to the CLI.");
1110
+ });
1111
+ const server = app.listen(availablePort);
1112
+ const connections = /* @__PURE__ */ new Set();
1113
+ server.on("connection", (conn) => {
1114
+ connections.add(conn);
1115
+ conn.on("close", () => connections.delete(conn));
1116
+ });
1117
+ const cleanup = () => {
1118
+ server.close();
1119
+ log_default.info("\n\u274C Login cancelled by user");
1120
+ process.exit(0);
1121
+ };
1122
+ process.on("SIGINT", cleanup);
1123
+ process.on("SIGTERM", cleanup);
1124
+ const { code_verifier: codeVerifier, code_challenge: codeChallenge } = await pkceChallenge__default.default();
1125
+ const authUrl = `${ZAPIER_BASE}/oauth/authorize/?${new URLSearchParams({
1126
+ response_type: "code",
1127
+ client_id: LOGIN_CLIENT_ID,
1128
+ redirect_uri: redirectUri,
1129
+ scope: "internal offline_access",
1130
+ state: generateRandomString(),
1131
+ code_challenge: codeChallenge,
1132
+ code_challenge_method: "S256"
1133
+ }).toString()}`;
1134
+ log_default.info("Opening your browser to log in.");
1135
+ log_default.info("If it doesn't open, visit:", authUrl);
1136
+ open__default.default(authUrl);
1137
+ try {
1138
+ await spinPromise(
1139
+ Promise.race([
1140
+ promisedCode,
1141
+ new Promise(
1142
+ (_resolve, reject) => setTimeout(() => {
1143
+ reject(
1144
+ new Error(
1145
+ `Login timed out after ${Math.round(timeoutMs / 1e3)} seconds.`
1146
+ )
1147
+ );
1148
+ }, timeoutMs)
1149
+ )
1150
+ ]),
1151
+ "Waiting for you to login and authorize"
1152
+ );
1153
+ } finally {
1154
+ process.off("SIGINT", cleanup);
1155
+ process.off("SIGTERM", cleanup);
1156
+ await new Promise((resolve2) => {
1157
+ const timeout = setTimeout(() => {
1158
+ log_default.info("Server close timed out, forcing connection shutdown...");
1159
+ connections.forEach((conn) => conn.destroy());
1160
+ resolve2();
1161
+ }, 1e3);
1162
+ server.close(() => {
1163
+ clearTimeout(timeout);
1164
+ resolve2();
1165
+ });
1166
+ });
1167
+ }
1168
+ log_default.info("Exchanging authorization code for tokens...");
1169
+ const { data } = await client_default.post(
1170
+ `${ZAPIER_BASE}/oauth/token/`,
1171
+ {
1172
+ grant_type: "authorization_code",
1173
+ code: await promisedCode,
1174
+ redirect_uri: redirectUri,
1175
+ client_id: LOGIN_CLIENT_ID,
1176
+ code_verifier: codeVerifier
1177
+ },
1178
+ {
1179
+ headers: {
1180
+ [AUTH_MODE_HEADER]: "no",
1181
+ "Content-Type": "application/x-www-form-urlencoded"
1182
+ }
1183
+ }
1184
+ );
1185
+ zapierSdkCliLogin.updateLogin(data);
1186
+ log_default.info("Token exchange completed successfully");
1187
+ return data.access_token;
1188
+ };
1189
+ var login_default = login;
1190
+ var LoginSchema = zod.z.object({
1191
+ timeout: zod.z.string().optional().describe("Login timeout in seconds (default: 300)")
1192
+ }).describe("Log in to Zapier to access your account");
1193
+
1194
+ // src/plugins/login/index.ts
1195
+ var loginWithSdk = zapierSdk.createFunction(async function loginWithSdk2(options) {
1196
+ const timeoutSeconds = options.timeout ? parseInt(options.timeout, 10) : 300;
1197
+ if (isNaN(timeoutSeconds) || timeoutSeconds <= 0) {
1198
+ throw new Error("Timeout must be a positive number");
1199
+ }
1200
+ await login_default(timeoutSeconds * 1e3);
1201
+ const user = await zapierSdkCliLogin.getLoggedInUser();
1202
+ console.log(`\u2705 Successfully logged in as ${user.email}`);
1203
+ setTimeout(() => process.exit(0), 100);
1204
+ }, LoginSchema);
1205
+ var loginPlugin = () => ({
1206
+ login: loginWithSdk,
1207
+ context: {
1208
+ meta: {
1209
+ login: {
1210
+ categories: ["account"],
1211
+ inputSchema: LoginSchema
1212
+ }
1213
+ }
1214
+ }
1215
+ });
1216
+ var LogoutSchema = zod.z.object({}).describe("Log out of your Zapier account");
1217
+
1218
+ // src/plugins/logout/index.ts
1219
+ var logoutWithSdk = zapierSdk.createFunction(async function logoutWithSdk2(_options) {
1220
+ zapierSdkCliLogin.logout();
1221
+ console.log("\u2705 Successfully logged out");
1222
+ }, LogoutSchema);
1223
+ var logoutPlugin = () => ({
1224
+ logout: logoutWithSdk,
1225
+ context: {
1226
+ meta: {
1227
+ logout: {
1228
+ categories: ["account"],
1229
+ inputSchema: LogoutSchema
1230
+ }
1231
+ }
1232
+ }
1233
+ });
1234
+ var McpSchema = zod.z.object({
1235
+ port: zod.z.string().optional().describe("Port to listen on (for future HTTP transport)")
1236
+ }).describe("Start MCP server for Zapier SDK");
1237
+
1238
+ // src/plugins/mcp/index.ts
1239
+ var mcpPlugin = ({ context }) => {
1240
+ const mcpWithSdk = zapierSdk.createFunction(async function mcpWithSdk2(options) {
1241
+ const mcpOptions = {
1242
+ ...options,
1243
+ debug: context.options.debug
1244
+ };
1245
+ return await zapierSdkMcp.startMcpServerAsProcess(mcpOptions);
1246
+ }, McpSchema);
1247
+ return {
1248
+ mcp: mcpWithSdk,
1249
+ context: {
1250
+ meta: {
1251
+ mcp: {
1252
+ categories: ["utility"],
1253
+ inputSchema: McpSchema
1254
+ }
1255
+ }
1256
+ }
1257
+ };
1258
+ };
1259
+ var GenerateTypesSchema = zod.z.object({
1260
+ appKey: zapierSdk.AppKeyPropertySchema.describe("App key to generate SDK code for"),
1261
+ authenticationId: zapierSdk.AuthenticationIdPropertySchema.optional(),
1262
+ output: zapierSdk.OutputPropertySchema.optional().describe(
1263
+ "Output file path (defaults to generated/<appKey>.ts)"
1264
+ ),
1265
+ lockFilePath: zod.z.string().optional().describe("Path to the .zapierrc lock file (defaults to .zapierrc)")
1266
+ }).describe("Generate TypeScript SDK code for a specific app");
1267
+ var generateTypesPlugin = ({ sdk: sdk2 }) => {
1268
+ const generateTypesWithSdk = zapierSdk.createFunction(
1269
+ async function generateTypesWithSdk2(options) {
1270
+ return await generateTypes({ ...options, sdk: sdk2 });
1271
+ },
1272
+ GenerateTypesSchema
1273
+ );
1274
+ return {
1275
+ generateTypes: generateTypesWithSdk,
1276
+ context: {
1277
+ meta: {
1278
+ generateTypes: {
1279
+ categories: ["utility"],
1280
+ inputSchema: GenerateTypesSchema
1281
+ }
1282
+ }
1283
+ }
1284
+ };
1285
+ };
1286
+ function generateFetchMethodSignature() {
1287
+ return ` /** Make authenticated HTTP requests through Zapier's Relay service */
1288
+ fetch: (options: Omit<z.infer<typeof RelayFetchSchema>, 'authenticationId'>) => Promise<Response>`;
1289
+ }
1290
+ async function generateTypes(options) {
1291
+ const {
1292
+ appKey,
1293
+ authenticationId,
1294
+ output = `./types/${appKey}.d.ts`,
1295
+ sdk: sdk2
1296
+ } = options;
1297
+ const { app, version } = parseAppIdentifier(appKey);
1298
+ const actionsResult = await sdk2.listActions({
1299
+ appKey: app
1300
+ });
1301
+ const actions = actionsResult.data;
1302
+ if (actions.length === 0) {
1303
+ const typeDefinitions2 = generateEmptyTypesFile(app, version);
1304
+ if (output) {
1305
+ fs__namespace.mkdirSync(path__namespace.dirname(output), { recursive: true });
1306
+ fs__namespace.writeFileSync(output, typeDefinitions2, "utf8");
1307
+ }
1308
+ return typeDefinitions2;
1309
+ }
1310
+ const actionsWithFields = [];
1311
+ if (authenticationId) {
1312
+ for (const action of actions) {
1313
+ try {
1314
+ const manifestEntry = sdk2.getContext().getManifestEntry(appKey);
1315
+ const fieldsResult = await sdk2.listInputFields({
1316
+ // If the appKey is in the manifest, use the appKey so that the types are consistent with the manifest's version, otherwise use the action.app_key
1317
+ appKey: manifestEntry ? appKey : action.app_key,
1318
+ actionKey: action.key,
1319
+ actionType: action.action_type,
1320
+ authenticationId
1321
+ });
1322
+ const fields = fieldsResult.data.map((field) => {
1323
+ const fieldObj = field;
1324
+ return {
1325
+ ...fieldObj,
1326
+ required: fieldObj.is_required || fieldObj.required || false
1327
+ };
1328
+ });
1329
+ actionsWithFields.push({
1330
+ ...action,
1331
+ inputFields: fields,
1332
+ name: action.title || action.key
1333
+ });
1334
+ } catch {
1335
+ actionsWithFields.push({
1336
+ ...action,
1337
+ inputFields: [],
1338
+ name: action.title || action.key
1339
+ });
1340
+ }
1341
+ }
1342
+ } else {
1343
+ actions.forEach((action) => {
1344
+ actionsWithFields.push({
1345
+ ...action,
1346
+ inputFields: [],
1347
+ name: action.title || action.key
1348
+ });
1349
+ });
1350
+ }
1351
+ const typeDefinitions = generateTypeDefinitions(
1352
+ app,
1353
+ actionsWithFields,
1354
+ version
1355
+ );
1356
+ if (output) {
1357
+ fs__namespace.mkdirSync(path__namespace.dirname(output), { recursive: true });
1358
+ fs__namespace.writeFileSync(output, typeDefinitions, "utf8");
1359
+ }
1360
+ return typeDefinitions;
1361
+ }
1362
+ function parseAppIdentifier(identifier) {
1363
+ const parts = identifier.split("@");
1364
+ return {
1365
+ app: parts[0],
1366
+ version: parts[1]
1367
+ };
1368
+ }
1369
+ function generateTypeDefinitions(appKey, actions, version) {
1370
+ if (actions.length === 0) {
1371
+ return generateEmptyTypesFile(appKey, version);
1372
+ }
1373
+ const actionsByType = actions.reduce(
1374
+ (acc, action) => {
1375
+ if (!acc[action.action_type]) {
1376
+ acc[action.action_type] = [];
1377
+ }
1378
+ acc[action.action_type].push(action);
1379
+ return acc;
1380
+ },
1381
+ {}
1382
+ );
1383
+ const appName = capitalize(appKey);
1384
+ const versionComment = version ? ` * Generated for ${appKey}@${version}` : ` * Generated for ${appKey}`;
1385
+ let output = `/* eslint-disable @typescript-eslint/naming-convention */
1386
+ /**
1387
+ * Auto-generated TypeScript types for Zapier ${appKey} actions
1388
+ ${versionComment}
1389
+ * Generated on: ${(/* @__PURE__ */ new Date()).toISOString()}
1390
+ *
1391
+ * Usage:
1392
+ * import type { ${appName}Sdk } from './path/to/this/file'
1393
+ * const sdk = createZapierSdk() as unknown as ${appName}Sdk
1394
+ *
1395
+ * // Direct usage (per-call auth):
1396
+ * await sdk.apps.${appKey}.search.user_by_email({ authenticationId: 123, inputs: { email } })
1397
+ *
1398
+ * // Factory usage (pinned auth):
1399
+ * const my${appName} = sdk.apps.${appKey}({ authenticationId: 123 })
1400
+ * await my${appName}.search.user_by_email({ inputs: { email } })
1401
+ */
1402
+
1403
+ import type { ActionExecutionOptions, ActionExecutionResult } from '@zapier/zapier-sdk'
1404
+ import { z } from 'zod'
1405
+ import { RelayFetchSchema } from '@zapier/zapier-sdk'
1406
+
1407
+ `;
1408
+ actions.forEach((action) => {
1409
+ if (action.inputFields.length > 0) {
1410
+ const inputTypeName = `${appName}${capitalize(action.action_type)}${capitalize(
1411
+ sanitizeActionName(action.key)
1412
+ )}Inputs`;
1413
+ output += `interface ${inputTypeName} {
1414
+ `;
1415
+ action.inputFields.forEach((field) => {
1416
+ const isOptional = !field.required;
1417
+ const fieldType = mapFieldTypeToTypeScript(field);
1418
+ const description = field.helpText ? ` /** ${escapeComment(field.helpText)} */
1419
+ ` : "";
1420
+ output += `${description} ${sanitizeFieldName(field.key)}${isOptional ? "?" : ""}: ${fieldType}
1421
+ `;
1422
+ });
1423
+ output += `}
1424
+
1425
+ `;
1426
+ }
1427
+ });
1428
+ Object.entries(actionsByType).forEach(([actionType, typeActions]) => {
1429
+ const typeName = `${appName}${capitalize(actionType)}Actions`;
1430
+ output += `interface ${typeName} {
1431
+ `;
1432
+ typeActions.forEach((action) => {
1433
+ const actionName = sanitizeActionName(action.key);
1434
+ const description = action.description ? ` /** ${escapeComment(action.description)} */
1435
+ ` : "";
1436
+ if (action.inputFields.length > 0) {
1437
+ const inputTypeName = `${appName}${capitalize(action.action_type)}${capitalize(
1438
+ sanitizeActionName(action.key)
1439
+ )}Inputs`;
1440
+ output += `${description} ${actionName}: (options: { inputs: ${inputTypeName} } & Omit<ActionExecutionOptions, 'inputs'>) => Promise<ActionExecutionResult>
1441
+ `;
1442
+ } else {
1443
+ output += `${description} ${actionName}: (options?: { inputs?: Record<string, any> } & ActionExecutionOptions) => Promise<ActionExecutionResult>
1444
+ `;
1445
+ }
1446
+ });
1447
+ output += `}
1448
+
1449
+ `;
1450
+ });
1451
+ output += `interface ${appName}AppProxy {
1452
+ `;
1453
+ Object.keys(actionsByType).forEach((actionType) => {
1454
+ const typeName = `${appName}${capitalize(actionType)}Actions`;
1455
+ output += ` ${actionType}: ${typeName}
1456
+ `;
1457
+ });
1458
+ output += generateFetchMethodSignature() + "\n";
1459
+ output += `}
1460
+
1461
+ `;
1462
+ output += `interface ${appName}AppFactory {
1463
+ `;
1464
+ output += ` (options: { authenticationId: number }): ${appName}AppProxy
1465
+ `;
1466
+ output += `}
1467
+
1468
+ `;
1469
+ output += `type ${appName}AppWithFactory = ${appName}AppFactory & ${appName}AppProxy
1470
+
1471
+ `;
1472
+ output += `export interface ${appName}Sdk {
1473
+ `;
1474
+ output += ` apps: {
1475
+ `;
1476
+ output += ` ${appKey}: ${appName}AppWithFactory
1477
+ `;
1478
+ output += ` }
1479
+ `;
1480
+ output += `}
1481
+ `;
1482
+ return output;
1483
+ }
1484
+ function generateEmptyTypesFile(appKey, version) {
1485
+ const appName = capitalize(appKey);
1486
+ const versionComment = version ? ` * Generated for ${appKey}@${version}` : ` * Generated for ${appKey}`;
1487
+ return `/* eslint-disable @typescript-eslint/naming-convention */
1488
+ /**
1489
+ * Auto-generated TypeScript types for Zapier ${appKey} actions
1490
+ ${versionComment}
1491
+ * Generated on: ${(/* @__PURE__ */ new Date()).toISOString()}
1492
+ *
1493
+ * No actions found for this app.
1494
+ */
1495
+
1496
+ import type { ActionExecutionOptions, ActionExecutionResult } from '@zapier/zapier-sdk'
1497
+ import { z } from 'zod'
1498
+ import { RelayFetchSchema } from '@zapier/zapier-sdk'
1499
+
1500
+ interface ${appName}AppProxy {
1501
+ // No actions available
1502
+ ${generateFetchMethodSignature()}
1503
+ }
1504
+
1505
+ interface ${appName}AppFactory {
1506
+ (options: { authenticationId: number }): ${appName}AppProxy
1507
+ }
1508
+
1509
+ type ${appName}AppWithFactory = ${appName}AppFactory & ${appName}AppProxy
1510
+
1511
+ export interface ${appName}Sdk {
1512
+ apps: {
1513
+ ${appKey}: ${appName}AppWithFactory
1514
+ }
1515
+ }
1516
+ `;
1517
+ }
1518
+ function capitalize(str) {
1519
+ return str.charAt(0).toUpperCase() + str.slice(1).replace(/[-_]/g, "");
1520
+ }
1521
+ function sanitizeActionName(actionKey) {
1522
+ let sanitized = actionKey.replace(/[^a-zA-Z0-9_$]/g, "_");
1523
+ if (/^[0-9]/.test(sanitized)) {
1524
+ sanitized = "_" + sanitized;
1525
+ }
1526
+ return sanitized;
1527
+ }
1528
+ function sanitizeFieldName(fieldKey) {
1529
+ let sanitized = fieldKey.replace(/[^a-zA-Z0-9_$]/g, "_");
1530
+ if (/^[0-9]/.test(sanitized)) {
1531
+ sanitized = "_" + sanitized;
1532
+ }
1533
+ return sanitized;
1534
+ }
1535
+ function escapeComment(comment) {
1536
+ return comment.replace(/\*\//g, "*\\/").replace(/\r?\n/g, " ");
1537
+ }
1538
+ function mapFieldTypeToTypeScript(field) {
1539
+ if (field.choices && field.choices.length > 0) {
1540
+ const choiceValues = field.choices.filter(
1541
+ (choice) => choice.value !== void 0 && choice.value !== null && choice.value !== ""
1542
+ ).map(
1543
+ (choice) => typeof choice.value === "string" ? `"${choice.value}"` : choice.value
1544
+ );
1545
+ if (choiceValues.length > 0) {
1546
+ return choiceValues.join(" | ");
1547
+ }
1548
+ }
1549
+ switch (field.type?.toLowerCase()) {
1550
+ case "string":
1551
+ case "text":
1552
+ case "email":
1553
+ case "url":
1554
+ case "password":
1555
+ return "string";
1556
+ case "integer":
1557
+ case "number":
1558
+ return "number";
1559
+ case "boolean":
1560
+ return "boolean";
1561
+ case "datetime":
1562
+ case "date":
1563
+ return "string";
1564
+ // ISO date strings
1565
+ case "file":
1566
+ return "string";
1567
+ // File URL or content
1568
+ case "array":
1569
+ return "any[]";
1570
+ case "object":
1571
+ return "Record<string, any>";
1572
+ default:
1573
+ return "string | number | boolean";
1574
+ }
1575
+ }
1576
+ var BundleCodeSchema = zod.z.object({
1577
+ input: zod.z.string().min(1).describe("Input TypeScript file path to bundle"),
1578
+ output: zapierSdk.OutputPropertySchema.optional().describe(
1579
+ "Output file path (defaults to input with .js extension)"
1580
+ ),
1581
+ string: zod.z.boolean().optional().describe("Return bundled code as string instead of writing to file"),
1582
+ minify: zod.z.boolean().optional().describe("Minify the bundled output"),
1583
+ target: zod.z.string().optional().describe("ECMAScript target version"),
1584
+ cjs: zod.z.boolean().optional().describe("Output CommonJS format instead of ESM")
1585
+ }).describe("Bundle TypeScript code into executable JavaScript");
1586
+ var bundleCodePlugin = () => {
1587
+ const bundleCodeWithSdk = zapierSdk.createFunction(async function bundleCodeWithSdk2(options) {
1588
+ return await bundleCode(options);
1589
+ }, BundleCodeSchema);
1590
+ return {
1591
+ bundleCode: bundleCodeWithSdk,
1592
+ context: {
1593
+ meta: {
1594
+ bundleCode: {
1595
+ categories: ["utility"],
1596
+ inputSchema: BundleCodeSchema
1597
+ }
1598
+ }
1599
+ }
1600
+ };
1601
+ };
1602
+ var ZapierBundleError = class extends Error {
1603
+ constructor(message, details, originalError) {
1604
+ super(message);
1605
+ this.code = "ZAPIER_BUNDLE_ERROR";
1606
+ this.name = "ZapierBundleError";
1607
+ this.details = details;
1608
+ this.originalError = originalError;
1609
+ }
1610
+ };
1611
+ async function bundleCode(options) {
1612
+ const {
1613
+ input,
1614
+ output,
1615
+ target = "es2020",
1616
+ cjs = false,
1617
+ minify = false,
1618
+ string: returnString = false
1619
+ } = options;
1620
+ const resolvedInput = path__namespace.resolve(process.cwd(), input);
1621
+ try {
1622
+ const result = esbuild.buildSync({
1623
+ entryPoints: [resolvedInput],
1624
+ bundle: true,
1625
+ platform: "node",
1626
+ target,
1627
+ format: cjs ? "cjs" : "esm",
1628
+ minify,
1629
+ write: false,
1630
+ external: [],
1631
+ // Bundle everything
1632
+ banner: {
1633
+ js: "#!/usr/bin/env node"
1634
+ }
1635
+ });
1636
+ if (result.errors.length > 0) {
1637
+ const errorMessages = result.errors.map((e) => e.text);
1638
+ throw new ZapierBundleError(
1639
+ `Bundle failed: ${errorMessages.join(", ")}`,
1640
+ errorMessages
1641
+ );
1642
+ }
1643
+ const bundledCode = result.outputFiles?.[0]?.text;
1644
+ if (!bundledCode) {
1645
+ throw new ZapierBundleError("No output generated");
1646
+ }
1647
+ let finalOutput = bundledCode;
1648
+ if (returnString) {
1649
+ finalOutput = JSON.stringify(bundledCode);
1650
+ }
1651
+ if (output) {
1652
+ fs__namespace.mkdirSync(path__namespace.dirname(output), { recursive: true });
1653
+ fs__namespace.writeFileSync(output, finalOutput, "utf8");
1654
+ }
1655
+ return finalOutput;
1656
+ } catch (error) {
1657
+ if (error instanceof ZapierBundleError) {
1658
+ throw error;
1659
+ }
1660
+ throw new ZapierBundleError(
1661
+ `Bundle failed: ${error instanceof Error ? error.message : "Unknown error"}`,
1662
+ void 0,
1663
+ error instanceof Error ? error : void 0
1664
+ );
1665
+ }
1666
+ }
1667
+ var GetConfigPathSchema = zod.z.object({}).describe("Show the path to the configuration file");
1668
+ var getConfigPathPlugin = () => {
1669
+ const getConfigPathWithSdk = zapierSdk.createFunction(
1670
+ async function getConfigPathWithSdk2(_options) {
1671
+ return zapierSdkCliLogin.getConfigPath();
1672
+ },
1673
+ GetConfigPathSchema
1674
+ );
1675
+ return {
1676
+ getConfigPath: getConfigPathWithSdk,
1677
+ context: {
1678
+ meta: {
1679
+ getConfigPath: {
1680
+ categories: ["utility"],
1681
+ inputSchema: GetConfigPathSchema
1682
+ }
1683
+ }
1684
+ }
1685
+ };
1686
+ };
1687
+
1688
+ // src/sdk.ts
1689
+ function createZapierCliSdk(options = {}) {
1690
+ let sdk2 = zapierSdk.createZapierSdkWithoutRegistry({
1691
+ debug: options.debug
1692
+ });
1693
+ sdk2 = sdk2.addPlugin(generateTypesPlugin);
1694
+ sdk2 = sdk2.addPlugin(bundleCodePlugin);
1695
+ sdk2 = sdk2.addPlugin(getConfigPathPlugin);
1696
+ sdk2 = sdk2.addPlugin(mcpPlugin);
1697
+ sdk2 = sdk2.addPlugin(loginPlugin);
1698
+ sdk2 = sdk2.addPlugin(logoutPlugin);
1699
+ const finalSdk = sdk2.addPlugin(zapierSdk.registryPlugin);
1700
+ return finalSdk;
1701
+ }
1702
+
1703
+ // package.json
1704
+ var package_default = {
1705
+ version: "0.6.5"};
1706
+
1707
+ // src/cli.ts
1708
+ var program = new commander.Command();
1709
+ program.name("zapier-sdk").description("CLI for Zapier SDK").version(package_default.version, "-v, --version", "display version number").option("--debug", "Enable debug logging");
1710
+ var isDebugMode = process.env.DEBUG === "true" || process.argv.includes("--debug");
1711
+ var sdk = createZapierCliSdk({
1712
+ debug: isDebugMode
1713
+ });
1714
+ generateCliCommands(program, sdk);
1715
+ program.parse();