@zapier/zapier-sdk-cli 0.8.4 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +35 -51
  3. package/dist/cli.cjs +950 -433
  4. package/dist/cli.mjs +951 -434
  5. package/dist/index.cjs +729 -336
  6. package/dist/index.mjs +730 -337
  7. package/dist/package.json +1 -1
  8. package/dist/src/plugins/add/ast-generator.d.ts +37 -0
  9. package/dist/src/plugins/add/ast-generator.js +403 -0
  10. package/dist/src/plugins/add/index.d.ts +13 -0
  11. package/dist/src/plugins/add/index.js +120 -0
  12. package/dist/src/plugins/add/schemas.d.ts +18 -0
  13. package/dist/src/plugins/add/schemas.js +19 -0
  14. package/dist/src/plugins/getLoginConfigPath/index.d.ts +15 -0
  15. package/dist/src/plugins/getLoginConfigPath/index.js +19 -0
  16. package/dist/src/plugins/getLoginConfigPath/schemas.d.ts +3 -0
  17. package/dist/src/plugins/getLoginConfigPath/schemas.js +5 -0
  18. package/dist/src/plugins/index.d.ts +2 -2
  19. package/dist/src/plugins/index.js +2 -2
  20. package/dist/src/sdk.js +3 -3
  21. package/dist/src/utils/cli-generator-utils.d.ts +2 -1
  22. package/dist/src/utils/cli-generator-utils.js +11 -5
  23. package/dist/src/utils/cli-generator.js +65 -65
  24. package/dist/src/utils/parameter-resolver.d.ts +4 -1
  25. package/dist/src/utils/parameter-resolver.js +92 -15
  26. package/dist/src/utils/schema-formatter.d.ts +5 -1
  27. package/dist/src/utils/schema-formatter.js +48 -18
  28. package/dist/tsconfig.tsbuildinfo +1 -1
  29. package/package.json +4 -4
  30. package/src/plugins/add/ast-generator.ts +777 -0
  31. package/src/plugins/add/index.test.ts +58 -0
  32. package/src/plugins/add/index.ts +187 -0
  33. package/src/plugins/add/schemas.ts +26 -0
  34. package/src/plugins/getLoginConfigPath/index.ts +45 -0
  35. package/src/plugins/getLoginConfigPath/schemas.ts +10 -0
  36. package/src/plugins/index.ts +2 -2
  37. package/src/sdk.ts +4 -4
  38. package/src/utils/cli-generator-utils.ts +17 -5
  39. package/src/utils/cli-generator.ts +90 -79
  40. package/src/utils/parameter-resolver.ts +155 -21
  41. package/src/utils/schema-formatter.ts +68 -33
  42. package/tsup.config.ts +1 -1
  43. package/dist/src/plugins/generateTypes/index.d.ts +0 -21
  44. package/dist/src/plugins/generateTypes/index.js +0 -312
  45. package/dist/src/plugins/generateTypes/schemas.d.ts +0 -18
  46. package/dist/src/plugins/generateTypes/schemas.js +0 -14
  47. package/dist/src/plugins/getConfigPath/index.d.ts +0 -15
  48. package/dist/src/plugins/getConfigPath/index.js +0 -19
  49. package/dist/src/plugins/getConfigPath/schemas.d.ts +0 -3
  50. package/dist/src/plugins/getConfigPath/schemas.js +0 -5
  51. package/src/plugins/generateTypes/index.ts +0 -444
  52. package/src/plugins/generateTypes/schemas.ts +0 -23
  53. package/src/plugins/getConfigPath/index.ts +0 -42
  54. package/src/plugins/getConfigPath/schemas.ts +0 -8
package/dist/cli.cjs CHANGED
@@ -14,9 +14,11 @@ var pkceChallenge = require('pkce-challenge');
14
14
  var ora = require('ora');
15
15
  var zapierSdkCliLogin = require('@zapier/zapier-sdk-cli-login');
16
16
  var zapierSdkMcp = require('@zapier/zapier-sdk-mcp');
17
+ var esbuild = require('esbuild');
17
18
  var fs = require('fs');
18
19
  var path = require('path');
19
- var esbuild = require('esbuild');
20
+ var ts = require('typescript');
21
+ var promises = require('fs/promises');
20
22
 
21
23
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
22
24
 
@@ -48,13 +50,47 @@ var pkceChallenge__default = /*#__PURE__*/_interopDefault(pkceChallenge);
48
50
  var ora__default = /*#__PURE__*/_interopDefault(ora);
49
51
  var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
50
52
  var path__namespace = /*#__PURE__*/_interopNamespace(path);
53
+ var ts__namespace = /*#__PURE__*/_interopNamespace(ts);
51
54
 
55
+ function getLocalResolutionOrder(paramName, resolvers, resolved = /* @__PURE__ */ new Set()) {
56
+ const resolver = resolvers[paramName];
57
+ if (!resolver || resolver.type === "static") {
58
+ return [paramName];
59
+ }
60
+ const order = [];
61
+ if ("depends" in resolver && resolver.depends) {
62
+ for (const dependency of resolver.depends) {
63
+ if (!resolved.has(dependency)) {
64
+ order.push(...getLocalResolutionOrder(dependency, resolvers, resolved));
65
+ resolved.add(dependency);
66
+ }
67
+ }
68
+ }
69
+ if (!resolved.has(paramName)) {
70
+ order.push(paramName);
71
+ resolved.add(paramName);
72
+ }
73
+ return order;
74
+ }
75
+ function getLocalResolutionOrderForParams(paramNames, resolvers) {
76
+ const resolved = /* @__PURE__ */ new Set();
77
+ const order = [];
78
+ for (const paramName of paramNames) {
79
+ const paramOrder = getLocalResolutionOrder(paramName, resolvers, resolved);
80
+ for (const param of paramOrder) {
81
+ if (!order.includes(param)) {
82
+ order.push(param);
83
+ }
84
+ }
85
+ }
86
+ return order;
87
+ }
52
88
  var SchemaParameterResolver = class {
53
- async resolveParameters(schema, providedParams, sdk2) {
89
+ async resolveParameters(schema, providedParams, sdk2, functionName) {
54
90
  const parseResult = schema.safeParse(providedParams);
55
91
  const allParams = this.extractParametersFromSchema(schema);
56
92
  const resolvableParams = allParams.filter(
57
- (param) => zapierSdk.hasResolver(param.name)
93
+ (param) => this.hasResolver(param.name, sdk2, functionName)
58
94
  );
59
95
  const missingResolvable = resolvableParams.filter((param) => {
60
96
  const hasValue = this.getNestedValue(providedParams, param.path) !== void 0;
@@ -90,11 +126,16 @@ var SchemaParameterResolver = class {
90
126
  const context = {
91
127
  sdk: sdk2,
92
128
  currentParams: providedParams,
93
- resolvedParams
129
+ resolvedParams,
130
+ functionName
94
131
  };
132
+ const localResolvers = this.getLocalResolvers(sdk2, functionName);
95
133
  if (functionallyRequired.length > 0) {
96
134
  const requiredParamNames = functionallyRequired.map((p) => p.name);
97
- const requiredResolutionOrder = zapierSdk.getResolutionOrderForParams(requiredParamNames);
135
+ const requiredResolutionOrder = getLocalResolutionOrderForParams(
136
+ requiredParamNames,
137
+ localResolvers
138
+ );
98
139
  const orderedRequiredParams = requiredResolutionOrder.map((paramName) => {
99
140
  let param = functionallyRequired.find((p) => p.name === paramName);
100
141
  if (!param) {
@@ -107,7 +148,11 @@ var SchemaParameterResolver = class {
107
148
  }).filter((param) => param !== void 0);
108
149
  for (const param of orderedRequiredParams) {
109
150
  try {
110
- const value = await this.resolveParameter(param, context);
151
+ const value = await this.resolveParameter(
152
+ param,
153
+ context,
154
+ functionName
155
+ );
111
156
  this.setNestedValue(resolvedParams, param.path, value);
112
157
  context.resolvedParams = resolvedParams;
113
158
  } catch (error) {
@@ -134,11 +179,18 @@ var SchemaParameterResolver = class {
134
179
  }
135
180
  if (alwaysPrompt.length > 0) {
136
181
  const alwaysPromptNames = alwaysPrompt.map((p) => p.name);
137
- const alwaysPromptResolutionOrder = zapierSdk.getResolutionOrderForParams(alwaysPromptNames);
182
+ const alwaysPromptResolutionOrder = getLocalResolutionOrderForParams(
183
+ alwaysPromptNames,
184
+ localResolvers
185
+ );
138
186
  const orderedAlwaysPromptParams = alwaysPromptResolutionOrder.map((paramName) => alwaysPrompt.find((p) => p.name === paramName)).filter((param) => param !== void 0);
139
187
  for (const param of orderedAlwaysPromptParams) {
140
188
  try {
141
- const value = await this.resolveParameter(param, context);
189
+ const value = await this.resolveParameter(
190
+ param,
191
+ context,
192
+ functionName
193
+ );
142
194
  this.setNestedValue(resolvedParams, param.path, value);
143
195
  context.resolvedParams = resolvedParams;
144
196
  } catch (error) {
@@ -162,11 +214,18 @@ var SchemaParameterResolver = class {
162
214
  ]);
163
215
  if (shouldResolveOptional.resolveOptional) {
164
216
  const optionalParamNames = trulyOptional.map((p) => p.name);
165
- const optionalResolutionOrder = zapierSdk.getResolutionOrderForParams(optionalParamNames);
217
+ const optionalResolutionOrder = getLocalResolutionOrderForParams(
218
+ optionalParamNames,
219
+ localResolvers
220
+ );
166
221
  const orderedOptionalParams = optionalResolutionOrder.map((paramName) => trulyOptional.find((p) => p.name === paramName)).filter((param) => param !== void 0);
167
222
  for (const param of orderedOptionalParams) {
168
223
  try {
169
- const value = await this.resolveParameter(param, context);
224
+ const value = await this.resolveParameter(
225
+ param,
226
+ context,
227
+ functionName
228
+ );
170
229
  this.setNestedValue(resolvedParams, param.path, value);
171
230
  context.resolvedParams = resolvedParams;
172
231
  } catch (error) {
@@ -214,19 +273,19 @@ var SchemaParameterResolver = class {
214
273
  }
215
274
  return this.createResolvableParameter([fieldName], baseSchema, isRequired);
216
275
  }
217
- createResolvableParameter(path3, schema, isRequired) {
218
- if (path3.length === 0) return null;
219
- const name = path3[path3.length - 1];
276
+ createResolvableParameter(path2, schema, isRequired) {
277
+ if (path2.length === 0) return null;
278
+ const name = path2[path2.length - 1];
220
279
  return {
221
280
  name,
222
- path: path3,
281
+ path: path2,
223
282
  schema,
224
283
  description: schema.description,
225
284
  isRequired
226
285
  };
227
286
  }
228
- async resolveParameter(param, context) {
229
- const resolver = zapierSdk.getResolver(param.name);
287
+ async resolveParameter(param, context, functionName) {
288
+ const resolver = this.getResolver(param.name, context.sdk, functionName);
230
289
  if (!resolver) {
231
290
  throw new Error(`No resolver found for parameter: ${param.name}`);
232
291
  }
@@ -311,10 +370,10 @@ var SchemaParameterResolver = class {
311
370
  break;
312
371
  }
313
372
  const newRequiredFields = newFields.filter(
314
- (field) => field.required
373
+ (field) => field.is_required
315
374
  );
316
375
  const newOptionalFields = newFields.filter(
317
- (field) => !field.required
376
+ (field) => !field.is_required
318
377
  );
319
378
  if (newRequiredFields.length > 0) {
320
379
  console.log(
@@ -379,15 +438,15 @@ Optional fields:`));
379
438
  }
380
439
  return inputs;
381
440
  }
382
- getNestedValue(obj, path3) {
383
- return path3.reduce(
441
+ getNestedValue(obj, path2) {
442
+ return path2.reduce(
384
443
  (current, key) => current?.[key],
385
444
  obj
386
445
  );
387
446
  }
388
- setNestedValue(obj, path3, value) {
389
- const lastKey = path3[path3.length - 1];
390
- const parent = path3.slice(0, -1).reduce((current, key) => {
447
+ setNestedValue(obj, path2, value) {
448
+ const lastKey = path2[path2.length - 1];
449
+ const parent = path2.slice(0, -1).reduce((current, key) => {
391
450
  const currentObj = current;
392
451
  if (!(key in currentObj)) {
393
452
  currentObj[key] = {};
@@ -401,7 +460,7 @@ Optional fields:`));
401
460
  const fieldPrompt = {
402
461
  type: fieldObj.type === "boolean" ? "confirm" : "input",
403
462
  name: fieldObj.key,
404
- message: `${fieldObj.label || fieldObj.key}${fieldObj.required ? " (required)" : " (optional)"}:`
463
+ message: `${fieldObj.label || fieldObj.key}${fieldObj.is_required ? " (required)" : " (optional)"}:`
405
464
  };
406
465
  if (fieldObj.helpText) {
407
466
  fieldPrompt.prefix = chalk3__default.default.gray(`\u2139 ${fieldObj.helpText}
@@ -426,7 +485,7 @@ Optional fields:`));
426
485
  const answer = await inquirer__default.default.prompt([fieldPrompt]);
427
486
  if (answer[fieldObj.key] !== void 0 && answer[fieldObj.key] !== "") {
428
487
  inputs[fieldObj.key] = answer[fieldObj.key];
429
- } else if (fieldObj.required) {
488
+ } else if (fieldObj.is_required) {
430
489
  throw new Error(`Required field ${fieldObj.key} cannot be empty`);
431
490
  }
432
491
  } catch (error) {
@@ -441,6 +500,40 @@ Optional fields:`));
441
500
  const errorObj = error;
442
501
  return errorObj?.name === "ExitPromptError" || errorObj?.message?.includes("User force closed") || errorObj?.isTTYError === true;
443
502
  }
503
+ hasResolver(paramName, sdk2, functionName) {
504
+ if (functionName && typeof sdk2.getRegistry === "function") {
505
+ const registry = sdk2.getRegistry();
506
+ const functionInfo = registry.functions.find(
507
+ (f) => f.name === functionName
508
+ );
509
+ if (functionInfo && functionInfo.resolvers?.[paramName]) {
510
+ return true;
511
+ }
512
+ }
513
+ return false;
514
+ }
515
+ getResolver(paramName, sdk2, functionName) {
516
+ if (functionName && typeof sdk2.getRegistry === "function") {
517
+ const registry = sdk2.getRegistry();
518
+ const functionInfo = registry.functions.find(
519
+ (f) => f.name === functionName
520
+ );
521
+ if (functionInfo && functionInfo.resolvers?.[paramName]) {
522
+ return functionInfo.resolvers[paramName];
523
+ }
524
+ }
525
+ return null;
526
+ }
527
+ getLocalResolvers(sdk2, functionName) {
528
+ if (!functionName || typeof sdk2.getRegistry !== "function") {
529
+ return {};
530
+ }
531
+ const registry = sdk2.getRegistry();
532
+ const functionInfo = registry.functions.find(
533
+ (f) => f.name === functionName
534
+ );
535
+ return functionInfo?.resolvers || {};
536
+ }
444
537
  };
445
538
  function getFormatMetadata(schema) {
446
539
  return schema?._def?.formatMeta;
@@ -448,8 +541,16 @@ function getFormatMetadata(schema) {
448
541
  function getOutputSchema(schema) {
449
542
  return schema?._def?.outputSchema;
450
543
  }
451
- function formatItemsFromSchema(inputSchema, items, startingNumber = 0) {
452
- const outputSchema = getOutputSchema(inputSchema);
544
+ function formatJsonOutput(data) {
545
+ if (data === void 0) {
546
+ return;
547
+ }
548
+ console.log(
549
+ util__default.default.inspect(data, { colors: true, depth: null, breakLength: 80 })
550
+ );
551
+ }
552
+ function formatItemsFromSchema(functionInfo, items, startingNumber = 0) {
553
+ const outputSchema = functionInfo.outputSchema || getOutputSchema(functionInfo.inputSchema);
453
554
  if (!outputSchema) {
454
555
  formatItemsGeneric(items, startingNumber);
455
556
  return;
@@ -460,16 +561,26 @@ function formatItemsFromSchema(inputSchema, items, startingNumber = 0) {
460
561
  return;
461
562
  }
462
563
  items.forEach((item, index) => {
463
- formatSingleItem(item, startingNumber + index, formatMeta);
564
+ const formatted = formatMeta.format(item);
565
+ formatSingleItem(formatted, startingNumber + index);
464
566
  });
465
567
  }
466
- function formatSingleItem(item, itemNumber, formatMeta) {
467
- const formatted = formatMeta.format(item);
568
+ function formatSingleItem(formatted, itemNumber) {
468
569
  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)}`;
570
+ if (formatted.id) {
571
+ titleLine += ` ${chalk3__default.default.gray(`(ID: ${formatted.id})`)}`;
572
+ } else if (formatted.key) {
573
+ titleLine += ` ${chalk3__default.default.gray(`(${formatted.key})`)}`;
471
574
  }
472
575
  console.log(titleLine);
576
+ if (formatted.description) {
577
+ console.log(` ${chalk3__default.default.dim(formatted.description)}`);
578
+ }
579
+ if (formatted.data !== void 0) {
580
+ formatJsonOutput(formatted.data);
581
+ console.log();
582
+ return;
583
+ }
473
584
  for (const detail of formatted.details) {
474
585
  const styledText = applyStyle(detail.text, detail.style);
475
586
  console.log(` ${styledText}`);
@@ -491,40 +602,36 @@ function applyStyle(value, style) {
491
602
  return chalk3__default.default.blue(value);
492
603
  }
493
604
  }
605
+ function convertGenericItemToFormattedItem(item) {
606
+ const itemObj = item;
607
+ return {
608
+ title: itemObj.title || itemObj.name || itemObj.key || itemObj.id || "Item",
609
+ id: itemObj.id,
610
+ key: itemObj.key,
611
+ description: itemObj.description,
612
+ details: []
613
+ };
614
+ }
494
615
  function formatItemsGeneric(items, startingNumber = 0) {
495
616
  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();
617
+ const formatted = convertGenericItemToFormattedItem(item);
618
+ formatSingleItem(formatted, startingNumber + index);
505
619
  });
506
620
  }
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) {
621
+ function analyzeZodSchema(schema, functionInfo) {
519
622
  const parameters = [];
520
623
  if (schema._def && schema._def.typeName === "ZodEffects") {
521
624
  const innerSchema = schema._def.schema;
522
- return analyzeZodSchema(innerSchema);
625
+ return analyzeZodSchema(innerSchema, functionInfo);
523
626
  }
524
627
  if (schema instanceof zod.z.ZodObject) {
525
628
  const shape = schema.shape;
526
629
  for (const [key, fieldSchema] of Object.entries(shape)) {
527
- const param = analyzeZodField(key, fieldSchema);
630
+ const param = analyzeZodField(
631
+ key,
632
+ fieldSchema,
633
+ functionInfo
634
+ );
528
635
  if (param) {
529
636
  parameters.push(param);
530
637
  }
@@ -532,7 +639,7 @@ function analyzeZodSchema(schema) {
532
639
  }
533
640
  return parameters;
534
641
  }
535
- function analyzeZodField(name, schema) {
642
+ function analyzeZodField(name, schema, functionInfo) {
536
643
  let baseSchema = schema;
537
644
  let required = true;
538
645
  let defaultValue = void 0;
@@ -566,6 +673,10 @@ function analyzeZodField(name, schema) {
566
673
  } else if (baseSchema instanceof zod.z.ZodRecord) {
567
674
  paramType = "string";
568
675
  }
676
+ let paramHasResolver = false;
677
+ if (functionInfo?.resolvers?.[name]) {
678
+ paramHasResolver = true;
679
+ }
569
680
  return {
570
681
  name,
571
682
  type: paramType,
@@ -573,7 +684,7 @@ function analyzeZodField(name, schema) {
573
684
  description: schema.description,
574
685
  default: defaultValue,
575
686
  choices,
576
- hasResolver: zapierSdk.hasResolver(name),
687
+ hasResolver: paramHasResolver,
577
688
  isPositional: zapierSdk.isPositional(schema)
578
689
  };
579
690
  }
@@ -595,12 +706,7 @@ function generateCliCommands(program2, sdk2) {
595
706
  return;
596
707
  }
597
708
  const cliCommandName = methodNameToCliCommand(fnInfo.name);
598
- const config = createCommandConfig(
599
- cliCommandName,
600
- fnInfo.name,
601
- fnInfo.inputSchema,
602
- sdk2
603
- );
709
+ const config = createCommandConfig(cliCommandName, fnInfo, sdk2);
604
710
  addCommand(program2, cliCommandName, config);
605
711
  });
606
712
  program2.configureHelp({
@@ -664,14 +770,15 @@ function generateCliCommands(program2, sdk2) {
664
770
  }
665
771
  });
666
772
  }
667
- function createCommandConfig(cliCommandName, sdkMethodName, schema, sdk2) {
668
- const parameters = analyzeZodSchema(schema);
773
+ function createCommandConfig(cliCommandName, functionInfo, sdk2) {
774
+ const schema = functionInfo.inputSchema;
775
+ const parameters = analyzeZodSchema(schema, functionInfo);
669
776
  const description = schema.description || `${cliCommandName} command`;
670
777
  const handler = async (...args) => {
671
778
  try {
672
779
  const commandObj = args[args.length - 1];
673
780
  const options = commandObj.opts();
674
- const isListCommand = cliCommandName.startsWith("list-");
781
+ const isListCommand = functionInfo.type === "list";
675
782
  const hasPaginationParams = parameters.some(
676
783
  (p) => p.name === "maxItems" || p.name === "pageSize"
677
784
  );
@@ -686,21 +793,22 @@ function createCommandConfig(cliCommandName, sdkMethodName, schema, sdk2) {
686
793
  const resolvedParams = await resolver.resolveParameters(
687
794
  schema,
688
795
  rawParams,
689
- sdk2
796
+ sdk2,
797
+ functionInfo.name
690
798
  );
691
799
  if (isListCommand && hasPaginationParams && !shouldUseJson && !hasUserSpecifiedMaxItems) {
692
800
  const sdkObj = sdk2;
693
- const sdkIterator = sdkObj[sdkMethodName](resolvedParams);
801
+ const sdkIterator = sdkObj[functionInfo.name](resolvedParams);
694
802
  await handlePaginatedListWithAsyncIteration(
695
- sdkMethodName,
803
+ functionInfo.name,
696
804
  sdkIterator,
697
- schema
805
+ functionInfo
698
806
  );
699
807
  } else {
700
808
  const hasOutputFile = resolvedParams.output;
701
809
  if (hasOutputFile) {
702
810
  const sdkObj2 = sdk2;
703
- await sdkObj2[sdkMethodName](resolvedParams);
811
+ await sdkObj2[functionInfo.name](resolvedParams);
704
812
  console.log(
705
813
  chalk3__default.default.green(`\u2705 ${cliCommandName} completed successfully!`)
706
814
  );
@@ -708,7 +816,7 @@ function createCommandConfig(cliCommandName, sdkMethodName, schema, sdk2) {
708
816
  return;
709
817
  }
710
818
  const sdkObj = sdk2;
711
- const result = await sdkObj[sdkMethodName](resolvedParams);
819
+ const result = await sdkObj[functionInfo.name](resolvedParams);
712
820
  const items = result?.data ? result.data : result;
713
821
  if (shouldUseJson) {
714
822
  console.log(JSON.stringify(items, null, 2));
@@ -718,8 +826,7 @@ function createCommandConfig(cliCommandName, sdkMethodName, schema, sdk2) {
718
826
  resolvedParams.maxItems,
719
827
  hasUserSpecifiedMaxItems,
720
828
  shouldUseJson,
721
- schema,
722
- sdkMethodName
829
+ functionInfo
723
830
  );
724
831
  } else {
725
832
  formatJsonOutput(items);
@@ -763,6 +870,7 @@ function createCommandConfig(cliCommandName, sdkMethodName, schema, sdk2) {
763
870
  }
764
871
  function addCommand(program2, commandName, config) {
765
872
  const command = program2.command(commandName).description(config.description);
873
+ let hasPositionalArray = false;
766
874
  config.parameters.forEach((param) => {
767
875
  const kebabName = param.name.replace(/([A-Z])/g, "-$1").toLowerCase();
768
876
  if (param.hasResolver && param.required) {
@@ -770,6 +878,19 @@ function addCommand(program2, commandName, config) {
770
878
  `[${kebabName}]`,
771
879
  param.description || `${kebabName} parameter`
772
880
  );
881
+ } else if (param.required && param.type === "array" && !hasPositionalArray) {
882
+ hasPositionalArray = true;
883
+ command.argument(
884
+ `<${kebabName}...>`,
885
+ param.description || `${kebabName} parameter`
886
+ );
887
+ } else if (param.required && param.type === "array") {
888
+ const flags = [`--${kebabName}`];
889
+ const flagSignature = flags.join(", ") + ` <values...>`;
890
+ command.requiredOption(
891
+ flagSignature,
892
+ param.description || `${kebabName} parameter (required)`
893
+ );
773
894
  } else if (param.required) {
774
895
  command.argument(
775
896
  `<${kebabName}>`,
@@ -826,6 +947,9 @@ function convertCliArgsToSdkParams(parameters, positionalArgs, options) {
826
947
  return sdkParams;
827
948
  }
828
949
  function convertValue(value, type) {
950
+ if (value === void 0) {
951
+ return void 0;
952
+ }
829
953
  switch (type) {
830
954
  case "number":
831
955
  return Number(value);
@@ -845,12 +969,14 @@ function convertValue(value, type) {
845
969
  return value;
846
970
  }
847
971
  }
848
- async function handlePaginatedListWithAsyncIteration(sdkMethodName, sdkResult, schema) {
849
- const itemName = getItemNameFromMethod(sdkMethodName);
972
+ async function handlePaginatedListWithAsyncIteration(sdkMethodName, sdkResult, functionInfo) {
973
+ const itemName = getItemNameFromMethod(functionInfo);
850
974
  let totalShown = 0;
851
975
  let pageCount = 0;
852
- console.log(chalk3__default.default.blue(`\u{1F4CB} ${getListTitleFromMethod(sdkMethodName)}
853
- `));
976
+ console.log(
977
+ chalk3__default.default.blue(`\u{1F4CB} ${getListTitleFromMethod(sdkMethodName, functionInfo)}
978
+ `)
979
+ );
854
980
  try {
855
981
  for await (const page of sdkResult) {
856
982
  const items = page.data || page;
@@ -869,12 +995,14 @@ async function handlePaginatedListWithAsyncIteration(sdkMethodName, sdkResult, s
869
995
  if (pageCount > 1) {
870
996
  console.clear();
871
997
  console.log(
872
- chalk3__default.default.blue(`\u{1F4CB} ${getListTitleFromMethod(sdkMethodName)}
873
- `)
998
+ chalk3__default.default.blue(
999
+ `\u{1F4CB} ${getListTitleFromMethod(sdkMethodName, functionInfo)}
1000
+ `
1001
+ )
874
1002
  );
875
1003
  }
876
- if (schema) {
877
- formatItemsFromSchema(schema, items, totalShown);
1004
+ if (functionInfo) {
1005
+ formatItemsFromSchema(functionInfo, items, totalShown);
878
1006
  } else {
879
1007
  formatItemsGeneric2(items, totalShown);
880
1008
  }
@@ -910,8 +1038,8 @@ async function handlePaginatedListWithAsyncIteration(sdkMethodName, sdkResult, s
910
1038
  console.log(chalk3__default.default.yellow(`No ${itemName} found.`));
911
1039
  return;
912
1040
  }
913
- if (schema) {
914
- formatItemsFromSchema(schema, items, 0);
1041
+ if (functionInfo) {
1042
+ formatItemsFromSchema(functionInfo, items, 0);
915
1043
  } else {
916
1044
  formatItemsGeneric2(items, 0);
917
1045
  }
@@ -922,7 +1050,7 @@ async function handlePaginatedListWithAsyncIteration(sdkMethodName, sdkResult, s
922
1050
  }
923
1051
  }
924
1052
  }
925
- function formatNonPaginatedResults(result, requestedMaxItems, userSpecifiedMaxItems, useRawJson, schema, methodName) {
1053
+ function formatNonPaginatedResults(result, requestedMaxItems, userSpecifiedMaxItems, useRawJson, functionInfo) {
926
1054
  if (!Array.isArray(result)) {
927
1055
  if (useRawJson) {
928
1056
  console.log(JSON.stringify(result, null, 2));
@@ -935,7 +1063,7 @@ function formatNonPaginatedResults(result, requestedMaxItems, userSpecifiedMaxIt
935
1063
  console.log(JSON.stringify(result, null, 2));
936
1064
  return;
937
1065
  }
938
- const itemName = methodName ? getItemNameFromMethod(methodName) : "items";
1066
+ const itemName = functionInfo ? getItemNameFromMethod(functionInfo) : "items";
939
1067
  if (result.length === 0) {
940
1068
  console.log(chalk3__default.default.yellow(`No ${itemName} found.`));
941
1069
  return;
@@ -943,8 +1071,8 @@ function formatNonPaginatedResults(result, requestedMaxItems, userSpecifiedMaxIt
943
1071
  console.log(chalk3__default.default.green(`
944
1072
  \u2705 Found ${result.length} ${itemName}:
945
1073
  `));
946
- if (schema) {
947
- formatItemsFromSchema(schema, result);
1074
+ if (functionInfo) {
1075
+ formatItemsFromSchema(functionInfo, result);
948
1076
  } else {
949
1077
  formatItemsGeneric2(result);
950
1078
  }
@@ -973,18 +1101,17 @@ function formatItemsGeneric2(items, startingNumber = 0) {
973
1101
  console.log();
974
1102
  });
975
1103
  }
976
- function getItemNameFromMethod(methodName) {
977
- const listMatch = methodName.match(/^list(.+)$/);
978
- if (listMatch) {
979
- return listMatch[1].toLowerCase();
1104
+ function getItemNameFromMethod(functionInfo) {
1105
+ if (functionInfo.itemType) {
1106
+ return `${functionInfo.itemType} items`;
980
1107
  }
981
1108
  return "items";
982
1109
  }
983
- function getListTitleFromMethod(methodName) {
984
- const itemName = getItemNameFromMethod(methodName);
985
- if (itemName === "items") return "Available Items";
986
- const capitalized = itemName.charAt(0).toUpperCase() + itemName.slice(1);
987
- return `Available ${capitalized}`;
1110
+ function getListTitleFromMethod(methodName, functionInfo) {
1111
+ if (functionInfo.itemType) {
1112
+ return `Available ${functionInfo.itemType} items`;
1113
+ }
1114
+ return `${methodName} items`;
988
1115
  }
989
1116
 
990
1117
  // src/utils/constants.ts
@@ -1051,28 +1178,28 @@ var client_default = api;
1051
1178
 
1052
1179
  // src/utils/getCallablePromise.ts
1053
1180
  var getCallablePromise = () => {
1054
- let resolve2 = () => {
1181
+ let resolve3 = () => {
1055
1182
  };
1056
1183
  let reject = () => {
1057
1184
  };
1058
1185
  const promise = new Promise((_resolve, _reject) => {
1059
- resolve2 = _resolve;
1186
+ resolve3 = _resolve;
1060
1187
  reject = _reject;
1061
1188
  });
1062
1189
  return {
1063
1190
  promise,
1064
- resolve: resolve2,
1191
+ resolve: resolve3,
1065
1192
  reject
1066
1193
  };
1067
1194
  };
1068
1195
  var getCallablePromise_default = getCallablePromise;
1069
1196
  var findAvailablePort = () => {
1070
- return new Promise((resolve2, reject) => {
1197
+ return new Promise((resolve3, reject) => {
1071
1198
  let portIndex = 0;
1072
1199
  const tryPort = (port) => {
1073
1200
  const server = express__default.default().listen(port, () => {
1074
1201
  server.close();
1075
- resolve2(port);
1202
+ resolve3(port);
1076
1203
  });
1077
1204
  server.on("error", (err) => {
1078
1205
  if (err.code === "EADDRINUSE") {
@@ -1162,15 +1289,15 @@ var login = async (timeoutMs = LOGIN_TIMEOUT_MS) => {
1162
1289
  } finally {
1163
1290
  process.off("SIGINT", cleanup);
1164
1291
  process.off("SIGTERM", cleanup);
1165
- await new Promise((resolve2) => {
1292
+ await new Promise((resolve3) => {
1166
1293
  const timeout = setTimeout(() => {
1167
1294
  log_default.info("Server close timed out, forcing connection shutdown...");
1168
1295
  connections.forEach((conn) => conn.destroy());
1169
- resolve2();
1296
+ resolve3();
1170
1297
  }, 1e3);
1171
1298
  server.close(() => {
1172
1299
  clearTimeout(timeout);
1173
- resolve2();
1300
+ resolve3();
1174
1301
  });
1175
1302
  });
1176
1303
  }
@@ -1265,323 +1392,6 @@ var mcpPlugin = ({ context }) => {
1265
1392
  }
1266
1393
  };
1267
1394
  };
1268
- var GenerateTypesSchema = zod.z.object({
1269
- appKey: zapierSdk.AppKeyPropertySchema.describe("App key to generate SDK code for"),
1270
- authenticationId: zapierSdk.AuthenticationIdPropertySchema.optional(),
1271
- output: zapierSdk.OutputPropertySchema.optional().describe(
1272
- "Output file path (defaults to generated/<appKey>.ts)"
1273
- ),
1274
- lockFilePath: zod.z.string().optional().describe("Path to the .zapierrc lock file (defaults to .zapierrc)")
1275
- }).describe("Generate TypeScript SDK code for a specific app");
1276
- var generateTypesPlugin = ({ sdk: sdk2 }) => {
1277
- const generateTypesWithSdk = zapierSdk.createFunction(
1278
- async function generateTypesWithSdk2(options) {
1279
- return await generateTypes({ ...options, sdk: sdk2 });
1280
- },
1281
- GenerateTypesSchema
1282
- );
1283
- return {
1284
- generateTypes: generateTypesWithSdk,
1285
- context: {
1286
- meta: {
1287
- generateTypes: {
1288
- categories: ["utility"],
1289
- inputSchema: GenerateTypesSchema
1290
- }
1291
- }
1292
- }
1293
- };
1294
- };
1295
- function generateFetchMethodSignature() {
1296
- return ` /** Make authenticated HTTP requests through Zapier's Relay service */
1297
- fetch: (options: Omit<z.infer<typeof RelayFetchSchema>, 'authenticationId'>) => Promise<Response>`;
1298
- }
1299
- async function generateTypes(options) {
1300
- const {
1301
- appKey,
1302
- authenticationId,
1303
- output = `./types/${appKey}.d.ts`,
1304
- sdk: sdk2
1305
- } = options;
1306
- const { app, version } = parseAppIdentifier(appKey);
1307
- const actionsResult = await sdk2.listActions({
1308
- appKey: app
1309
- });
1310
- const actions = actionsResult.data;
1311
- if (actions.length === 0) {
1312
- const typeDefinitions2 = generateEmptyTypesFile(app, version);
1313
- if (output) {
1314
- fs__namespace.mkdirSync(path__namespace.dirname(output), { recursive: true });
1315
- fs__namespace.writeFileSync(output, typeDefinitions2, "utf8");
1316
- }
1317
- return typeDefinitions2;
1318
- }
1319
- const actionsWithFields = [];
1320
- if (authenticationId) {
1321
- for (const action of actions) {
1322
- try {
1323
- const manifestEntry = sdk2.getContext().getManifestEntry(appKey);
1324
- const fieldsResult = await sdk2.listInputFields({
1325
- // 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
1326
- appKey: manifestEntry ? appKey : action.app_key,
1327
- actionKey: action.key,
1328
- actionType: action.action_type,
1329
- authenticationId
1330
- });
1331
- const fields = fieldsResult.data.map((field) => {
1332
- const fieldObj = field;
1333
- return {
1334
- ...fieldObj,
1335
- required: fieldObj.is_required || fieldObj.required || false
1336
- };
1337
- });
1338
- actionsWithFields.push({
1339
- ...action,
1340
- inputFields: fields,
1341
- name: action.title || action.key
1342
- });
1343
- } catch {
1344
- actionsWithFields.push({
1345
- ...action,
1346
- inputFields: [],
1347
- name: action.title || action.key
1348
- });
1349
- }
1350
- }
1351
- } else {
1352
- actions.forEach((action) => {
1353
- actionsWithFields.push({
1354
- ...action,
1355
- inputFields: [],
1356
- name: action.title || action.key
1357
- });
1358
- });
1359
- }
1360
- const typeDefinitions = generateTypeDefinitions(
1361
- app,
1362
- actionsWithFields,
1363
- version
1364
- );
1365
- if (output) {
1366
- fs__namespace.mkdirSync(path__namespace.dirname(output), { recursive: true });
1367
- fs__namespace.writeFileSync(output, typeDefinitions, "utf8");
1368
- }
1369
- return typeDefinitions;
1370
- }
1371
- function parseAppIdentifier(identifier) {
1372
- const parts = identifier.split("@");
1373
- return {
1374
- app: parts[0],
1375
- version: parts[1]
1376
- };
1377
- }
1378
- function generateTypeDefinitions(appKey, actions, version) {
1379
- if (actions.length === 0) {
1380
- return generateEmptyTypesFile(appKey, version);
1381
- }
1382
- const actionsByType = actions.reduce(
1383
- (acc, action) => {
1384
- if (!acc[action.action_type]) {
1385
- acc[action.action_type] = [];
1386
- }
1387
- acc[action.action_type].push(action);
1388
- return acc;
1389
- },
1390
- {}
1391
- );
1392
- const appName = capitalize(appKey);
1393
- const versionComment = version ? ` * Generated for ${appKey}@${version}` : ` * Generated for ${appKey}`;
1394
- let output = `/* eslint-disable @typescript-eslint/naming-convention */
1395
- /**
1396
- * Auto-generated TypeScript types for Zapier ${appKey} actions
1397
- ${versionComment}
1398
- * Generated on: ${(/* @__PURE__ */ new Date()).toISOString()}
1399
- *
1400
- * Usage:
1401
- * import type { ${appName}Sdk } from './path/to/this/file'
1402
- * const sdk = createZapierSdk() as unknown as ${appName}Sdk
1403
- *
1404
- * // Direct usage (per-call auth):
1405
- * await sdk.apps.${appKey}.search.user_by_email({ authenticationId: 123, inputs: { email } })
1406
- *
1407
- * // Factory usage (pinned auth):
1408
- * const my${appName} = sdk.apps.${appKey}({ authenticationId: 123 })
1409
- * await my${appName}.search.user_by_email({ inputs: { email } })
1410
- */
1411
-
1412
- import type { ActionExecutionOptions, ActionExecutionResult } from '@zapier/zapier-sdk'
1413
- import { z } from 'zod'
1414
- import { RelayFetchSchema } from '@zapier/zapier-sdk'
1415
-
1416
- `;
1417
- actions.forEach((action) => {
1418
- if (action.inputFields.length > 0) {
1419
- const inputTypeName = `${appName}${capitalize(action.action_type)}${capitalize(
1420
- sanitizeActionName(action.key)
1421
- )}Inputs`;
1422
- output += `interface ${inputTypeName} {
1423
- `;
1424
- action.inputFields.forEach((field) => {
1425
- const isOptional = !field.required;
1426
- const fieldType = mapFieldTypeToTypeScript(field);
1427
- const description = field.helpText ? ` /** ${escapeComment(field.helpText)} */
1428
- ` : "";
1429
- output += `${description} ${sanitizeFieldName(field.key)}${isOptional ? "?" : ""}: ${fieldType}
1430
- `;
1431
- });
1432
- output += `}
1433
-
1434
- `;
1435
- }
1436
- });
1437
- Object.entries(actionsByType).forEach(([actionType, typeActions]) => {
1438
- const typeName = `${appName}${capitalize(actionType)}Actions`;
1439
- output += `interface ${typeName} {
1440
- `;
1441
- typeActions.forEach((action) => {
1442
- const actionName = sanitizeActionName(action.key);
1443
- const description = action.description ? ` /** ${escapeComment(action.description)} */
1444
- ` : "";
1445
- if (action.inputFields.length > 0) {
1446
- const inputTypeName = `${appName}${capitalize(action.action_type)}${capitalize(
1447
- sanitizeActionName(action.key)
1448
- )}Inputs`;
1449
- output += `${description} ${actionName}: (options: { inputs: ${inputTypeName} } & Omit<ActionExecutionOptions, 'inputs'>) => Promise<ActionExecutionResult>
1450
- `;
1451
- } else {
1452
- output += `${description} ${actionName}: (options?: { inputs?: Record<string, any> } & ActionExecutionOptions) => Promise<ActionExecutionResult>
1453
- `;
1454
- }
1455
- });
1456
- output += `}
1457
-
1458
- `;
1459
- });
1460
- output += `interface ${appName}AppProxy {
1461
- `;
1462
- Object.keys(actionsByType).forEach((actionType) => {
1463
- const typeName = `${appName}${capitalize(actionType)}Actions`;
1464
- output += ` ${actionType}: ${typeName}
1465
- `;
1466
- });
1467
- output += generateFetchMethodSignature() + "\n";
1468
- output += `}
1469
-
1470
- `;
1471
- output += `interface ${appName}AppFactory {
1472
- `;
1473
- output += ` (options: { authenticationId: number }): ${appName}AppProxy
1474
- `;
1475
- output += `}
1476
-
1477
- `;
1478
- output += `type ${appName}AppWithFactory = ${appName}AppFactory & ${appName}AppProxy
1479
-
1480
- `;
1481
- output += `export interface ${appName}Sdk {
1482
- `;
1483
- output += ` apps: {
1484
- `;
1485
- output += ` ${appKey}: ${appName}AppWithFactory
1486
- `;
1487
- output += ` }
1488
- `;
1489
- output += `}
1490
- `;
1491
- return output;
1492
- }
1493
- function generateEmptyTypesFile(appKey, version) {
1494
- const appName = capitalize(appKey);
1495
- const versionComment = version ? ` * Generated for ${appKey}@${version}` : ` * Generated for ${appKey}`;
1496
- return `/* eslint-disable @typescript-eslint/naming-convention */
1497
- /**
1498
- * Auto-generated TypeScript types for Zapier ${appKey} actions
1499
- ${versionComment}
1500
- * Generated on: ${(/* @__PURE__ */ new Date()).toISOString()}
1501
- *
1502
- * No actions found for this app.
1503
- */
1504
-
1505
- import type { ActionExecutionOptions, ActionExecutionResult } from '@zapier/zapier-sdk'
1506
- import { z } from 'zod'
1507
- import { RelayFetchSchema } from '@zapier/zapier-sdk'
1508
-
1509
- interface ${appName}AppProxy {
1510
- // No actions available
1511
- ${generateFetchMethodSignature()}
1512
- }
1513
-
1514
- interface ${appName}AppFactory {
1515
- (options: { authenticationId: number }): ${appName}AppProxy
1516
- }
1517
-
1518
- type ${appName}AppWithFactory = ${appName}AppFactory & ${appName}AppProxy
1519
-
1520
- export interface ${appName}Sdk {
1521
- apps: {
1522
- ${appKey}: ${appName}AppWithFactory
1523
- }
1524
- }
1525
- `;
1526
- }
1527
- function capitalize(str) {
1528
- return str.charAt(0).toUpperCase() + str.slice(1).replace(/[-_]/g, "");
1529
- }
1530
- function sanitizeActionName(actionKey) {
1531
- let sanitized = actionKey.replace(/[^a-zA-Z0-9_$]/g, "_");
1532
- if (/^[0-9]/.test(sanitized)) {
1533
- sanitized = "_" + sanitized;
1534
- }
1535
- return sanitized;
1536
- }
1537
- function sanitizeFieldName(fieldKey) {
1538
- let sanitized = fieldKey.replace(/[^a-zA-Z0-9_$]/g, "_");
1539
- if (/^[0-9]/.test(sanitized)) {
1540
- sanitized = "_" + sanitized;
1541
- }
1542
- return sanitized;
1543
- }
1544
- function escapeComment(comment) {
1545
- return comment.replace(/\*\//g, "*\\/").replace(/\r?\n/g, " ");
1546
- }
1547
- function mapFieldTypeToTypeScript(field) {
1548
- if (field.choices && field.choices.length > 0) {
1549
- const choiceValues = field.choices.filter(
1550
- (choice) => choice.value !== void 0 && choice.value !== null && choice.value !== ""
1551
- ).map(
1552
- (choice) => typeof choice.value === "string" ? `"${choice.value}"` : choice.value
1553
- );
1554
- if (choiceValues.length > 0) {
1555
- return choiceValues.join(" | ");
1556
- }
1557
- }
1558
- switch (field.type?.toLowerCase()) {
1559
- case "string":
1560
- case "text":
1561
- case "email":
1562
- case "url":
1563
- case "password":
1564
- return "string";
1565
- case "integer":
1566
- case "number":
1567
- return "number";
1568
- case "boolean":
1569
- return "boolean";
1570
- case "datetime":
1571
- case "date":
1572
- return "string";
1573
- // ISO date strings
1574
- case "file":
1575
- return "string";
1576
- // File URL or content
1577
- case "array":
1578
- return "any[]";
1579
- case "object":
1580
- return "Record<string, any>";
1581
- default:
1582
- return "string | number | boolean";
1583
- }
1584
- }
1585
1395
  var BundleCodeSchema = zod.z.object({
1586
1396
  input: zod.z.string().min(1).describe("Input TypeScript file path to bundle"),
1587
1397
  output: zapierSdk.OutputPropertySchema.optional().describe(
@@ -1673,21 +1483,728 @@ async function bundleCode(options) {
1673
1483
  );
1674
1484
  }
1675
1485
  }
1676
- var GetConfigPathSchema = zod.z.object({}).describe("Show the path to the configuration file");
1677
- var getConfigPathPlugin = () => {
1678
- const getConfigPathWithSdk = zapierSdk.createFunction(
1679
- async function getConfigPathWithSdk2(_options) {
1486
+ var GetLoginConfigPathSchema = zod.z.object({}).describe("Show the path to the login configuration file");
1487
+ var getLoginConfigPathPlugin = () => {
1488
+ const getLoginConfigPathWithSdk = zapierSdk.createFunction(
1489
+ async function getLoginConfigPathWithSdk2(_options) {
1680
1490
  return zapierSdkCliLogin.getConfigPath();
1681
1491
  },
1682
- GetConfigPathSchema
1492
+ GetLoginConfigPathSchema
1683
1493
  );
1684
1494
  return {
1685
- getConfigPath: getConfigPathWithSdk,
1495
+ getLoginConfigPath: getLoginConfigPathWithSdk,
1496
+ context: {
1497
+ meta: {
1498
+ getLoginConfigPath: {
1499
+ categories: ["utility"],
1500
+ inputSchema: GetLoginConfigPathSchema
1501
+ }
1502
+ }
1503
+ }
1504
+ };
1505
+ };
1506
+ var AddSchema = zod.z.object({
1507
+ appKeys: zod.z.array(zod.z.string().min(1, "App key cannot be empty")).min(1, "At least one app key is required"),
1508
+ authenticationIds: zod.z.array(zod.z.string()).optional().describe("Authentication IDs to use for type generation"),
1509
+ configPath: zod.z.string().optional().describe(
1510
+ `Path to Zapier config file (defaults to '${zapierSdk.DEFAULT_CONFIG_PATH}')`
1511
+ ),
1512
+ typesOutput: zod.z.string().optional().describe(
1513
+ "Directory for TypeScript type files (defaults to (src|lib|.)/zapier/apps/)"
1514
+ )
1515
+ });
1516
+ var AstTypeGenerator = class {
1517
+ constructor() {
1518
+ this.factory = ts__namespace.factory;
1519
+ this.printer = ts__namespace.createPrinter({
1520
+ newLine: ts__namespace.NewLineKind.LineFeed,
1521
+ removeComments: false,
1522
+ omitTrailingSemicolon: false
1523
+ });
1524
+ }
1525
+ /**
1526
+ * Generate TypeScript types using AST for a specific app
1527
+ */
1528
+ async generateTypes(options) {
1529
+ const { appKey, authenticationId, sdk: sdk2 } = options;
1530
+ const { app, version } = this.parseAppIdentifier(appKey);
1531
+ const actionsResult = await sdk2.listActions({
1532
+ appKey: app
1533
+ });
1534
+ const actions = actionsResult.data;
1535
+ if (actions.length === 0) {
1536
+ return this.generateEmptyTypesFile(app, version);
1537
+ }
1538
+ const actionsWithFields = [];
1539
+ if (authenticationId) {
1540
+ for (const action of actions) {
1541
+ try {
1542
+ const fieldsResult = await sdk2.listInputFields({
1543
+ appKey,
1544
+ actionKey: action.key,
1545
+ actionType: action.action_type,
1546
+ authenticationId
1547
+ });
1548
+ const fields = fieldsResult.data.map(
1549
+ (field) => {
1550
+ const fieldObj = field;
1551
+ return {
1552
+ ...fieldObj,
1553
+ required: fieldObj.is_required || fieldObj.required || false
1554
+ };
1555
+ }
1556
+ );
1557
+ actionsWithFields.push({
1558
+ ...action,
1559
+ inputFields: fields,
1560
+ name: action.title || action.key
1561
+ });
1562
+ } catch {
1563
+ actionsWithFields.push({
1564
+ ...action,
1565
+ inputFields: [],
1566
+ name: action.title || action.key
1567
+ });
1568
+ }
1569
+ }
1570
+ } else {
1571
+ actions.forEach(
1572
+ (action) => {
1573
+ actionsWithFields.push({
1574
+ ...action,
1575
+ inputFields: [],
1576
+ name: action.title || action.key,
1577
+ app_key: action.app_key || appKey,
1578
+ action_type: action.action_type || "write",
1579
+ title: action.title || action.key,
1580
+ type: "action",
1581
+ description: action.description || ""
1582
+ });
1583
+ }
1584
+ );
1585
+ }
1586
+ const sourceFile = this.createSourceFile(app, actionsWithFields, version);
1587
+ return this.printer.printFile(sourceFile);
1588
+ }
1589
+ parseAppIdentifier(identifier) {
1590
+ const parts = identifier.split("@");
1591
+ return {
1592
+ app: parts[0],
1593
+ version: parts[1]
1594
+ };
1595
+ }
1596
+ createSourceFile(appKey, actions, version) {
1597
+ const appName = this.capitalize(appKey);
1598
+ const versionComment = version ? ` * Generated for ${appKey}@${version}` : ` * Generated for ${appKey}`;
1599
+ const headerComment = `Auto-generated TypeScript types for Zapier ${appKey} actions
1600
+ ${versionComment.slice(3)}
1601
+ Generated on: ${(/* @__PURE__ */ new Date()).toISOString()}
1602
+
1603
+ This file automatically augments the base SDK types when present.
1604
+ No manual imports or type casting required.
1605
+
1606
+ Usage:
1607
+ import { createZapierSdk } from "@zapier/zapier-sdk";
1608
+
1609
+ const zapier = createZapierSdk();
1610
+ // Types are automatically available:
1611
+ await zapier.apps.${appKey}.search.user_by_email({ authenticationId: 123, inputs: { email } })
1612
+
1613
+ // Factory usage (pinned auth):
1614
+ const my${appName} = zapier.apps.${appKey}({ authenticationId: 123 })
1615
+ await my${appName}.search.user_by_email({ inputs: { email } })`;
1616
+ const statements = [
1617
+ // Import the SDK to activate module augmentation
1618
+ this.createImportStatement(["@zapier/zapier-sdk"]),
1619
+ // Import types we'll use
1620
+ this.createTypeImportStatement(
1621
+ [
1622
+ "ActionExecutionOptions",
1623
+ "ActionExecutionResult",
1624
+ "ZapierFetchInitOptions"
1625
+ ],
1626
+ "@zapier/zapier-sdk"
1627
+ )
1628
+ ];
1629
+ const actionsByType = this.groupActionsByType(actions);
1630
+ actions.forEach((action) => {
1631
+ if (action.inputFields.length > 0) {
1632
+ const inputInterface = this.createInputInterface(appName, action);
1633
+ statements.push(inputInterface);
1634
+ }
1635
+ });
1636
+ Object.entries(actionsByType).forEach(([actionType, typeActions]) => {
1637
+ const actionInterface = this.createActionInterface(
1638
+ appName,
1639
+ actionType,
1640
+ typeActions
1641
+ );
1642
+ statements.push(actionInterface);
1643
+ });
1644
+ const appProxyInterface = this.createAppProxyInterface(
1645
+ appName,
1646
+ actionsByType
1647
+ );
1648
+ statements.push(appProxyInterface);
1649
+ const appFactoryInterface = this.createAppFactoryInterface(appName);
1650
+ statements.push(appFactoryInterface);
1651
+ const appWithFactoryType = this.createAppWithFactoryType(appName);
1652
+ statements.push(appWithFactoryType);
1653
+ const moduleAugmentation = this.createModuleAugmentation(appKey, appName);
1654
+ statements.push(moduleAugmentation);
1655
+ statements.push(
1656
+ this.factory.createExportDeclaration(
1657
+ void 0,
1658
+ false,
1659
+ this.factory.createNamedExports([])
1660
+ )
1661
+ );
1662
+ const sourceFile = ts__namespace.createSourceFile(
1663
+ "generated.d.ts",
1664
+ "",
1665
+ ts__namespace.ScriptTarget.Latest,
1666
+ false,
1667
+ ts__namespace.ScriptKind.TS
1668
+ );
1669
+ if (statements.length > 0) {
1670
+ ts__namespace.addSyntheticLeadingComment(
1671
+ statements[0],
1672
+ ts__namespace.SyntaxKind.MultiLineCommentTrivia,
1673
+ " eslint-disable @typescript-eslint/naming-convention, @typescript-eslint/no-explicit-any ",
1674
+ true
1675
+ );
1676
+ ts__namespace.addSyntheticLeadingComment(
1677
+ statements[0],
1678
+ ts__namespace.SyntaxKind.MultiLineCommentTrivia,
1679
+ headerComment,
1680
+ true
1681
+ );
1682
+ }
1683
+ return this.factory.updateSourceFile(sourceFile, statements);
1684
+ }
1685
+ createImportStatement(imports, from) {
1686
+ if (imports.length === 1 && !from && imports[0].startsWith("@")) {
1687
+ return this.factory.createImportDeclaration(
1688
+ void 0,
1689
+ void 0,
1690
+ this.factory.createStringLiteral(imports[0]),
1691
+ void 0
1692
+ );
1693
+ }
1694
+ const fromModule = from || imports[0];
1695
+ const importNames = from ? imports : [];
1696
+ return this.factory.createImportDeclaration(
1697
+ void 0,
1698
+ importNames.length > 0 ? this.factory.createImportClause(
1699
+ false,
1700
+ void 0,
1701
+ this.factory.createNamedImports(
1702
+ importNames.map(
1703
+ (name) => this.factory.createImportSpecifier(
1704
+ false,
1705
+ void 0,
1706
+ this.factory.createIdentifier(name)
1707
+ )
1708
+ )
1709
+ )
1710
+ ) : void 0,
1711
+ this.factory.createStringLiteral(fromModule),
1712
+ void 0
1713
+ );
1714
+ }
1715
+ createTypeImportStatement(imports, from) {
1716
+ return this.factory.createImportDeclaration(
1717
+ void 0,
1718
+ this.factory.createImportClause(
1719
+ true,
1720
+ // typeOnly: true
1721
+ void 0,
1722
+ this.factory.createNamedImports(
1723
+ imports.map(
1724
+ (name) => this.factory.createImportSpecifier(
1725
+ false,
1726
+ void 0,
1727
+ this.factory.createIdentifier(name)
1728
+ )
1729
+ )
1730
+ )
1731
+ ),
1732
+ this.factory.createStringLiteral(from),
1733
+ void 0
1734
+ );
1735
+ }
1736
+ groupActionsByType(actions) {
1737
+ return actions.reduce(
1738
+ (acc, action) => {
1739
+ if (!acc[action.action_type]) {
1740
+ acc[action.action_type] = [];
1741
+ }
1742
+ acc[action.action_type].push(action);
1743
+ return acc;
1744
+ },
1745
+ {}
1746
+ );
1747
+ }
1748
+ createInputInterface(appName, action) {
1749
+ const inputTypeName = `${appName}${this.capitalize(action.action_type)}${this.capitalize(
1750
+ this.sanitizeActionName(action.key)
1751
+ )}Inputs`;
1752
+ const properties = action.inputFields.map((field) => {
1753
+ const fieldType = this.mapFieldTypeToTypeNode(field);
1754
+ const isOptional = !field.required;
1755
+ let property = this.factory.createPropertySignature(
1756
+ void 0,
1757
+ this.sanitizeFieldName(field.key),
1758
+ isOptional ? this.factory.createToken(ts__namespace.SyntaxKind.QuestionToken) : void 0,
1759
+ fieldType
1760
+ );
1761
+ if (field.helpText) {
1762
+ property = ts__namespace.addSyntheticLeadingComment(
1763
+ property,
1764
+ ts__namespace.SyntaxKind.MultiLineCommentTrivia,
1765
+ `* ${this.escapeComment(field.helpText)} `,
1766
+ true
1767
+ );
1768
+ }
1769
+ return property;
1770
+ });
1771
+ return this.factory.createInterfaceDeclaration(
1772
+ void 0,
1773
+ inputTypeName,
1774
+ void 0,
1775
+ void 0,
1776
+ properties
1777
+ );
1778
+ }
1779
+ createActionInterface(appName, actionType, typeActions) {
1780
+ const typeName = `${appName}${this.capitalize(actionType)}Actions`;
1781
+ const methods = typeActions.map((action) => {
1782
+ const actionName = this.sanitizeActionName(action.key);
1783
+ let methodSignature;
1784
+ if (action.inputFields.length > 0) {
1785
+ const inputTypeName = `${appName}${this.capitalize(action.action_type)}${this.capitalize(
1786
+ this.sanitizeActionName(action.key)
1787
+ )}Inputs`;
1788
+ const inputsType = this.factory.createTypeLiteralNode([
1789
+ this.factory.createPropertySignature(
1790
+ void 0,
1791
+ "inputs",
1792
+ void 0,
1793
+ this.factory.createTypeReferenceNode(inputTypeName)
1794
+ )
1795
+ ]);
1796
+ const omitType = this.factory.createTypeReferenceNode("Omit", [
1797
+ this.factory.createTypeReferenceNode("ActionExecutionOptions"),
1798
+ this.factory.createLiteralTypeNode(
1799
+ this.factory.createStringLiteral("inputs")
1800
+ )
1801
+ ]);
1802
+ const optionsType = this.factory.createIntersectionTypeNode([
1803
+ inputsType,
1804
+ omitType
1805
+ ]);
1806
+ methodSignature = this.factory.createMethodSignature(
1807
+ void 0,
1808
+ actionName,
1809
+ void 0,
1810
+ void 0,
1811
+ [
1812
+ this.factory.createParameterDeclaration(
1813
+ void 0,
1814
+ void 0,
1815
+ "options",
1816
+ void 0,
1817
+ optionsType
1818
+ )
1819
+ ],
1820
+ this.factory.createTypeReferenceNode("Promise", [
1821
+ this.factory.createTypeReferenceNode("ActionExecutionResult")
1822
+ ])
1823
+ );
1824
+ } else {
1825
+ const genericInputsType = this.factory.createTypeLiteralNode([
1826
+ this.factory.createPropertySignature(
1827
+ void 0,
1828
+ "inputs",
1829
+ this.factory.createToken(ts__namespace.SyntaxKind.QuestionToken),
1830
+ this.factory.createTypeReferenceNode("Record", [
1831
+ this.factory.createKeywordTypeNode(ts__namespace.SyntaxKind.StringKeyword),
1832
+ this.factory.createKeywordTypeNode(ts__namespace.SyntaxKind.AnyKeyword)
1833
+ ])
1834
+ )
1835
+ ]);
1836
+ const intersectionType = this.factory.createIntersectionTypeNode([
1837
+ genericInputsType,
1838
+ this.factory.createTypeReferenceNode("ActionExecutionOptions")
1839
+ ]);
1840
+ methodSignature = this.factory.createMethodSignature(
1841
+ void 0,
1842
+ actionName,
1843
+ void 0,
1844
+ void 0,
1845
+ [
1846
+ this.factory.createParameterDeclaration(
1847
+ void 0,
1848
+ void 0,
1849
+ "options",
1850
+ this.factory.createToken(ts__namespace.SyntaxKind.QuestionToken),
1851
+ intersectionType
1852
+ )
1853
+ ],
1854
+ this.factory.createTypeReferenceNode("Promise", [
1855
+ this.factory.createTypeReferenceNode("ActionExecutionResult")
1856
+ ])
1857
+ );
1858
+ }
1859
+ if (action.description) {
1860
+ methodSignature = ts__namespace.addSyntheticLeadingComment(
1861
+ methodSignature,
1862
+ ts__namespace.SyntaxKind.MultiLineCommentTrivia,
1863
+ `* ${this.escapeComment(action.description)} `,
1864
+ true
1865
+ );
1866
+ }
1867
+ return methodSignature;
1868
+ });
1869
+ return this.factory.createInterfaceDeclaration(
1870
+ void 0,
1871
+ typeName,
1872
+ void 0,
1873
+ void 0,
1874
+ methods
1875
+ );
1876
+ }
1877
+ createAppProxyInterface(appName, actionsByType) {
1878
+ const properties = [
1879
+ ...Object.keys(actionsByType).map(
1880
+ (actionType) => this.factory.createPropertySignature(
1881
+ void 0,
1882
+ actionType,
1883
+ void 0,
1884
+ this.factory.createTypeReferenceNode(
1885
+ `${appName}${this.capitalize(actionType)}Actions`
1886
+ )
1887
+ )
1888
+ ),
1889
+ // Always include fetch method for authenticated HTTP requests
1890
+ this.createFetchMethodProperty()
1891
+ ];
1892
+ return this.factory.createInterfaceDeclaration(
1893
+ void 0,
1894
+ `${appName}AppProxy`,
1895
+ void 0,
1896
+ void 0,
1897
+ properties
1898
+ );
1899
+ }
1900
+ createFetchMethodProperty() {
1901
+ let property = this.factory.createPropertySignature(
1902
+ void 0,
1903
+ "fetch",
1904
+ void 0,
1905
+ this.factory.createFunctionTypeNode(
1906
+ void 0,
1907
+ [
1908
+ this.factory.createParameterDeclaration(
1909
+ void 0,
1910
+ void 0,
1911
+ "url",
1912
+ void 0,
1913
+ this.factory.createUnionTypeNode([
1914
+ this.factory.createTypeReferenceNode("string"),
1915
+ this.factory.createTypeReferenceNode("URL")
1916
+ ])
1917
+ ),
1918
+ this.factory.createParameterDeclaration(
1919
+ void 0,
1920
+ void 0,
1921
+ "init",
1922
+ this.factory.createToken(ts__namespace.SyntaxKind.QuestionToken),
1923
+ this.factory.createTypeReferenceNode("ZapierFetchInitOptions")
1924
+ )
1925
+ ],
1926
+ this.factory.createTypeReferenceNode("Promise", [
1927
+ this.factory.createTypeReferenceNode("Response")
1928
+ ])
1929
+ )
1930
+ );
1931
+ property = ts__namespace.addSyntheticLeadingComment(
1932
+ property,
1933
+ ts__namespace.SyntaxKind.MultiLineCommentTrivia,
1934
+ "* Make authenticated HTTP requests through Zapier's Relay service ",
1935
+ true
1936
+ );
1937
+ return property;
1938
+ }
1939
+ createAppFactoryInterface(appName) {
1940
+ const callSignature = this.factory.createCallSignature(
1941
+ void 0,
1942
+ [
1943
+ this.factory.createParameterDeclaration(
1944
+ void 0,
1945
+ void 0,
1946
+ "options",
1947
+ void 0,
1948
+ this.factory.createTypeLiteralNode([
1949
+ this.factory.createPropertySignature(
1950
+ void 0,
1951
+ "authenticationId",
1952
+ void 0,
1953
+ this.factory.createKeywordTypeNode(ts__namespace.SyntaxKind.NumberKeyword)
1954
+ )
1955
+ ])
1956
+ )
1957
+ ],
1958
+ this.factory.createTypeReferenceNode(`${appName}AppProxy`)
1959
+ );
1960
+ return this.factory.createInterfaceDeclaration(
1961
+ void 0,
1962
+ `${appName}AppFactory`,
1963
+ void 0,
1964
+ void 0,
1965
+ [callSignature]
1966
+ );
1967
+ }
1968
+ createAppWithFactoryType(appName) {
1969
+ return this.factory.createTypeAliasDeclaration(
1970
+ void 0,
1971
+ `${appName}AppWithFactory`,
1972
+ void 0,
1973
+ this.factory.createIntersectionTypeNode([
1974
+ this.factory.createTypeReferenceNode(`${appName}AppFactory`),
1975
+ this.factory.createTypeReferenceNode(`${appName}AppProxy`)
1976
+ ])
1977
+ );
1978
+ }
1979
+ createModuleAugmentation(appKey, appName) {
1980
+ return this.factory.createModuleDeclaration(
1981
+ [this.factory.createToken(ts__namespace.SyntaxKind.DeclareKeyword)],
1982
+ this.factory.createStringLiteral("@zapier/zapier-sdk"),
1983
+ this.factory.createModuleBlock([
1984
+ this.factory.createInterfaceDeclaration(
1985
+ void 0,
1986
+ "ZapierSdkApps",
1987
+ void 0,
1988
+ void 0,
1989
+ [
1990
+ this.factory.createPropertySignature(
1991
+ void 0,
1992
+ appKey,
1993
+ void 0,
1994
+ this.factory.createTypeReferenceNode(`${appName}AppWithFactory`)
1995
+ )
1996
+ ]
1997
+ )
1998
+ ])
1999
+ );
2000
+ }
2001
+ mapFieldTypeToTypeNode(field) {
2002
+ if (field.choices && field.choices.length > 0) {
2003
+ const choiceValues = field.choices.filter(
2004
+ (choice) => choice.value !== void 0 && choice.value !== null && choice.value !== ""
2005
+ ).map(
2006
+ (choice) => typeof choice.value === "string" ? this.factory.createLiteralTypeNode(
2007
+ this.factory.createStringLiteral(choice.value)
2008
+ ) : this.factory.createLiteralTypeNode(
2009
+ this.factory.createNumericLiteral(String(choice.value))
2010
+ )
2011
+ );
2012
+ if (choiceValues.length > 0) {
2013
+ return this.factory.createUnionTypeNode(choiceValues);
2014
+ }
2015
+ }
2016
+ switch (field.type?.toLowerCase()) {
2017
+ case "string":
2018
+ case "text":
2019
+ case "email":
2020
+ case "url":
2021
+ case "password":
2022
+ case "datetime":
2023
+ case "date":
2024
+ case "file":
2025
+ return this.factory.createKeywordTypeNode(ts__namespace.SyntaxKind.StringKeyword);
2026
+ case "integer":
2027
+ case "number":
2028
+ return this.factory.createKeywordTypeNode(ts__namespace.SyntaxKind.NumberKeyword);
2029
+ case "boolean":
2030
+ return this.factory.createKeywordTypeNode(ts__namespace.SyntaxKind.BooleanKeyword);
2031
+ case "array":
2032
+ return this.factory.createArrayTypeNode(
2033
+ this.factory.createKeywordTypeNode(ts__namespace.SyntaxKind.AnyKeyword)
2034
+ );
2035
+ case "object":
2036
+ return this.factory.createTypeReferenceNode("Record", [
2037
+ this.factory.createKeywordTypeNode(ts__namespace.SyntaxKind.StringKeyword),
2038
+ this.factory.createKeywordTypeNode(ts__namespace.SyntaxKind.AnyKeyword)
2039
+ ]);
2040
+ default:
2041
+ return this.factory.createUnionTypeNode([
2042
+ this.factory.createKeywordTypeNode(ts__namespace.SyntaxKind.StringKeyword),
2043
+ this.factory.createKeywordTypeNode(ts__namespace.SyntaxKind.NumberKeyword),
2044
+ this.factory.createKeywordTypeNode(ts__namespace.SyntaxKind.BooleanKeyword)
2045
+ ]);
2046
+ }
2047
+ }
2048
+ generateEmptyTypesFile(appKey, version) {
2049
+ const appName = this.capitalize(appKey);
2050
+ const versionComment = version ? ` * Generated for ${appKey}@${version}` : ` * Generated for ${appKey}`;
2051
+ return `/* eslint-disable @typescript-eslint/naming-convention, @typescript-eslint/no-explicit-any */
2052
+ /**
2053
+ * Auto-generated TypeScript types for Zapier ${appKey} actions
2054
+ ${versionComment}
2055
+ * Generated on: ${(/* @__PURE__ */ new Date()).toISOString()}
2056
+ *
2057
+ * No actions found for this app.
2058
+ */
2059
+
2060
+ import type { ActionExecutionOptions, ActionExecutionResult, ZapierFetchInitOptions } from '@zapier/zapier-sdk'
2061
+
2062
+ interface ${appName}AppProxy {
2063
+ /** Make authenticated HTTP requests through Zapier's Relay service */
2064
+ fetch: (url: string | URL, init?: ZapierFetchInitOptions) => Promise<Response>
2065
+ }
2066
+
2067
+ interface ${appName}AppFactory {
2068
+ (options: { authenticationId: number }): ${appName}AppProxy
2069
+ }
2070
+
2071
+ type ${appName}AppWithFactory = ${appName}AppFactory & ${appName}AppProxy
2072
+
2073
+ declare module "@zapier/zapier-sdk" {
2074
+ interface ZapierSdkApps {
2075
+ ${appKey}: ${appName}AppWithFactory
2076
+ }
2077
+ }
2078
+ `;
2079
+ }
2080
+ capitalize(str) {
2081
+ return str.charAt(0).toUpperCase() + str.slice(1).replace(/[-_]/g, "");
2082
+ }
2083
+ sanitizeActionName(actionKey) {
2084
+ let sanitized = actionKey.replace(/[^a-zA-Z0-9_$]/g, "_");
2085
+ if (/^[0-9]/.test(sanitized)) {
2086
+ sanitized = "_" + sanitized;
2087
+ }
2088
+ return sanitized;
2089
+ }
2090
+ sanitizeFieldName(fieldKey) {
2091
+ let sanitized = fieldKey.replace(/[^a-zA-Z0-9_$]/g, "_");
2092
+ if (/^[0-9]/.test(sanitized)) {
2093
+ sanitized = "_" + sanitized;
2094
+ }
2095
+ return sanitized;
2096
+ }
2097
+ escapeComment(comment) {
2098
+ return comment.replace(/\*\//g, "*\\/").replace(/\r?\n/g, " ");
2099
+ }
2100
+ };
2101
+ async function detectTypesOutputDirectory() {
2102
+ const candidates = ["src", "lib"];
2103
+ for (const candidate of candidates) {
2104
+ try {
2105
+ await promises.access(candidate);
2106
+ return path.join(candidate, "zapier", "apps");
2107
+ } catch {
2108
+ }
2109
+ }
2110
+ return "./zapier/apps/";
2111
+ }
2112
+ var addPlugin = ({ sdk: sdk2, context }) => {
2113
+ const add = zapierSdk.createFunction(async function add2(options) {
2114
+ const {
2115
+ appKeys,
2116
+ authenticationIds,
2117
+ configPath,
2118
+ typesOutput = await detectTypesOutputDirectory()
2119
+ } = options;
2120
+ const resolvedTypesOutput = path.resolve(typesOutput);
2121
+ await promises.mkdir(resolvedTypesOutput, { recursive: true });
2122
+ console.log(`\u{1F4E6} Looking up ${appKeys.length} app(s)...`);
2123
+ const appsIterator = sdk2.listApps({ appKeys }).items();
2124
+ const apps = [];
2125
+ for await (const app of appsIterator) {
2126
+ apps.push(app);
2127
+ }
2128
+ if (apps.length === 0) {
2129
+ console.warn("\u26A0\uFE0F No apps found");
2130
+ return;
2131
+ }
2132
+ let authentications = [];
2133
+ if (authenticationIds && authenticationIds.length > 0) {
2134
+ console.log(
2135
+ `\u{1F510} Looking up ${authenticationIds.length} authentication(s)...`
2136
+ );
2137
+ const authsIterator = sdk2.listAuthentications({ authenticationIds }).items();
2138
+ for await (const auth of authsIterator) {
2139
+ authentications.push(auth);
2140
+ }
2141
+ console.log(`\u{1F510} Found ${authentications.length} authentication(s)`);
2142
+ }
2143
+ for (const app of apps) {
2144
+ const appSlugAndKey = app.slug ? `${app.slug} (${app.key})` : app.key;
2145
+ console.log(`\u{1F4E6} Adding ${appSlugAndKey}...`);
2146
+ try {
2147
+ if (!app.version) {
2148
+ console.warn(
2149
+ `\u26A0\uFE0F Invalid implementation ID format for '${appSlugAndKey}': ${app.implementation_id}. Expected format: <implementationName>@<version>. Skipping...`
2150
+ );
2151
+ continue;
2152
+ }
2153
+ const [manifestKey] = await context.updateManifestEntry(
2154
+ app.key,
2155
+ {
2156
+ implementationName: app.key,
2157
+ version: app.version
2158
+ },
2159
+ configPath
2160
+ );
2161
+ console.log(
2162
+ `\u{1F4DD} Locked ${appSlugAndKey} to ${app.key}@${app.version} using key '${manifestKey}'`
2163
+ );
2164
+ let authenticationId;
2165
+ if (authentications.length > 0) {
2166
+ const matchingAuth = authentications.find((auth) => {
2167
+ return auth.app_key === app.key;
2168
+ });
2169
+ if (matchingAuth) {
2170
+ authenticationId = matchingAuth.id;
2171
+ console.log(
2172
+ `\u{1F510} Using authentication ${authenticationId} (${matchingAuth.title}) for ${appSlugAndKey}`
2173
+ );
2174
+ } else {
2175
+ console.warn(
2176
+ `\u26A0\uFE0F No matching authentication found for ${appSlugAndKey}`
2177
+ );
2178
+ }
2179
+ }
2180
+ const typesPath = path.join(resolvedTypesOutput, `${manifestKey}.d.ts`);
2181
+ try {
2182
+ const generator = new AstTypeGenerator();
2183
+ const typeDefinitions = await generator.generateTypes({
2184
+ appKey: manifestKey,
2185
+ authenticationId,
2186
+ sdk: sdk2
2187
+ });
2188
+ await promises.writeFile(typesPath, typeDefinitions, "utf8");
2189
+ console.log(`\u{1F527} Generated types for ${manifestKey} at ${typesPath}`);
2190
+ } catch (error) {
2191
+ console.warn(
2192
+ `\u26A0\uFE0F Failed to generate types for ${appSlugAndKey}: ${error}`
2193
+ );
2194
+ }
2195
+ } catch (error) {
2196
+ console.warn(`\u26A0\uFE0F Failed to process ${appSlugAndKey}: ${error}`);
2197
+ }
2198
+ }
2199
+ console.log(`\u2705 Added ${apps.length} app(s) to manifest`);
2200
+ }, AddSchema);
2201
+ return {
2202
+ add,
1686
2203
  context: {
1687
2204
  meta: {
1688
- getConfigPath: {
2205
+ add: {
1689
2206
  categories: ["utility"],
1690
- inputSchema: GetConfigPathSchema
2207
+ inputSchema: AddSchema
1691
2208
  }
1692
2209
  }
1693
2210
  }
@@ -1699,9 +2216,9 @@ function createZapierCliSdk(options = {}) {
1699
2216
  let sdk2 = zapierSdk.createZapierSdkWithoutRegistry({
1700
2217
  debug: options.debug
1701
2218
  });
1702
- sdk2 = sdk2.addPlugin(generateTypesPlugin);
1703
2219
  sdk2 = sdk2.addPlugin(bundleCodePlugin);
1704
- sdk2 = sdk2.addPlugin(getConfigPathPlugin);
2220
+ sdk2 = sdk2.addPlugin(getLoginConfigPathPlugin);
2221
+ sdk2 = sdk2.addPlugin(addPlugin);
1705
2222
  sdk2 = sdk2.addPlugin(mcpPlugin);
1706
2223
  sdk2 = sdk2.addPlugin(loginPlugin);
1707
2224
  sdk2 = sdk2.addPlugin(logoutPlugin);
@@ -1711,7 +2228,7 @@ function createZapierCliSdk(options = {}) {
1711
2228
 
1712
2229
  // package.json
1713
2230
  var package_default = {
1714
- version: "0.8.4"};
2231
+ version: "0.10.0"};
1715
2232
 
1716
2233
  // src/cli.ts
1717
2234
  var program = new commander.Command();