@zapier/zapier-sdk 0.13.8 → 0.14.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.
package/dist/index.mjs CHANGED
@@ -1790,6 +1790,64 @@ var RootFieldItemSchema = z.union([
1790
1790
  FieldsetItemSchema
1791
1791
  ]);
1792
1792
 
1793
+ // src/services/implementations.ts
1794
+ async function fetchImplementationNeeds({
1795
+ api,
1796
+ selectedApi,
1797
+ action,
1798
+ actionType,
1799
+ authenticationId,
1800
+ inputs
1801
+ }) {
1802
+ const request = {
1803
+ selected_api: selectedApi,
1804
+ action,
1805
+ type_of: actionType,
1806
+ params: inputs || {}
1807
+ };
1808
+ if (authenticationId !== null) {
1809
+ request.authentication_id = authenticationId;
1810
+ }
1811
+ const response = await api.post(
1812
+ "/api/v4/implementations/needs/",
1813
+ request
1814
+ );
1815
+ if (!response.success) {
1816
+ throw new ZapierApiError(
1817
+ `Failed to get input fields: ${response.errors?.join(", ") || "Unknown error"}`
1818
+ );
1819
+ }
1820
+ return response;
1821
+ }
1822
+ async function fetchImplementationChoices({
1823
+ api,
1824
+ actionId,
1825
+ inputFieldId,
1826
+ authenticationId,
1827
+ inputs,
1828
+ page
1829
+ }) {
1830
+ const request = {
1831
+ action_id: actionId,
1832
+ input_field_id: inputFieldId,
1833
+ page,
1834
+ params: inputs || {}
1835
+ };
1836
+ if (authenticationId !== null) {
1837
+ request.authentication_id = authenticationId;
1838
+ }
1839
+ const response = await api.post(
1840
+ "/api/v4/implementations/choices/",
1841
+ request
1842
+ );
1843
+ if (!response.success) {
1844
+ throw new ZapierApiError(
1845
+ `Failed to get input field choices: ${response.errors?.join(", ") || "Unknown error"}`
1846
+ );
1847
+ }
1848
+ return response;
1849
+ }
1850
+
1793
1851
  // src/plugins/listInputFields/index.ts
1794
1852
  function getInputFieldTypeFromNeed(need) {
1795
1853
  if (need.list) {
@@ -1893,7 +1951,13 @@ var listInputFieldsPlugin = ({ sdk, context }) => {
1893
1951
  const listInputFields = createPaginatedFunction(
1894
1952
  async function listInputFieldsPage(options) {
1895
1953
  const { api, getVersionedImplementationId } = context;
1896
- const { appKey, actionKey, actionType, authenticationId, inputs } = options;
1954
+ const {
1955
+ appKey,
1956
+ actionKey,
1957
+ actionType,
1958
+ authenticationId = null,
1959
+ inputs
1960
+ } = options;
1897
1961
  const selectedApi = await getVersionedImplementationId(appKey);
1898
1962
  if (!selectedApi) {
1899
1963
  throw new ZapierConfigurationError(
@@ -1906,24 +1970,14 @@ var listInputFieldsPlugin = ({ sdk, context }) => {
1906
1970
  actionType,
1907
1971
  actionKey
1908
1972
  });
1909
- const needsRequest = {
1910
- selected_api: selectedApi,
1973
+ const needsData = await fetchImplementationNeeds({
1974
+ api,
1975
+ selectedApi,
1911
1976
  action: action.key,
1912
- type_of: actionType,
1913
- params: inputs || {}
1914
- };
1915
- if (authenticationId !== null) {
1916
- needsRequest.authentication_id = authenticationId;
1917
- }
1918
- const needsData = await api.post(
1919
- "/api/v4/implementations/needs/",
1920
- needsRequest
1921
- );
1922
- if (!needsData.success) {
1923
- throw new ZapierApiError(
1924
- `Failed to get action fields: ${needsData.errors?.join(", ") || "Unknown error"}`
1925
- );
1926
- }
1977
+ actionType,
1978
+ authenticationId,
1979
+ inputs
1980
+ });
1927
1981
  const rootFieldset = transformNeedsToFields(needsData.needs || []);
1928
1982
  return {
1929
1983
  data: rootFieldset,
@@ -3079,15 +3133,28 @@ function createDebugFetch(options) {
3079
3133
  }
3080
3134
  };
3081
3135
  }
3136
+
3137
+ // src/utils/retry-utils.ts
3138
+ var MAX_CONSECUTIVE_ERRORS = 3;
3139
+ var BASE_ERROR_BACKOFF_MS = 1e3;
3140
+ var JITTER_FACTOR = 0.5;
3141
+ function calculateWaitTime(baseInterval, errorCount) {
3142
+ const jitter = Math.random() * JITTER_FACTOR * baseInterval;
3143
+ const errorBackoff = Math.min(
3144
+ BASE_ERROR_BACKOFF_MS * (errorCount / 2),
3145
+ baseInterval * 2
3146
+ // Cap error backoff at 2x the base interval
3147
+ );
3148
+ return Math.floor(baseInterval + jitter + errorBackoff);
3149
+ }
3150
+
3151
+ // src/api/polling.ts
3082
3152
  var DEFAULT_TIMEOUT_MS = 18e4;
3083
3153
  var DEFAULT_SUCCESS_STATUS = 200;
3084
3154
  var DEFAULT_PENDING_STATUS = 202;
3085
3155
  var DEFAULT_INITIAL_DELAY_MS = 50;
3086
3156
  var DEFAULT_MAX_POLLING_INTERVAL_MS = 1e4;
3087
- var MAX_CONSECUTIVE_ERRORS = 3;
3088
3157
  var MAX_TIMEOUT_BUFFER_MS = 1e4;
3089
- var BASE_ERROR_BACKOFF_MS = 1e3;
3090
- var JITTER_FACTOR = 0.5;
3091
3158
  var DEFAULT_POLLING_STAGES = [
3092
3159
  [125, 125],
3093
3160
  // Up to 125ms: poll every 125ms
@@ -3102,15 +3169,6 @@ var DEFAULT_POLLING_STAGES = [
3102
3169
  [6e4, 5e3]
3103
3170
  // Up to 60s: poll every 5s
3104
3171
  ];
3105
- var calculateWaitTime = (baseInterval, errorCount) => {
3106
- const jitter = Math.random() * JITTER_FACTOR * baseInterval;
3107
- const errorBackoff = Math.min(
3108
- BASE_ERROR_BACKOFF_MS * (errorCount / 2),
3109
- baseInterval * 2
3110
- // Cap error backoff at 2x the base interval
3111
- );
3112
- return Math.floor(baseInterval + jitter + errorBackoff);
3113
- };
3114
3172
  var processResponse = async (response, successStatus, pendingStatus, resultExtractor, errorCount) => {
3115
3173
  if (!response.ok) {
3116
3174
  return {
@@ -3591,6 +3649,94 @@ var apiPlugin = (params) => {
3591
3649
  }
3592
3650
  };
3593
3651
  };
3652
+ var DEFAULT_CONCURRENCY = 10;
3653
+ var BATCH_START_DELAY_MS = 25;
3654
+ var DEFAULT_BATCH_TIMEOUT_MS = 18e4;
3655
+ async function batch(tasks, options = {}) {
3656
+ const {
3657
+ concurrency = DEFAULT_CONCURRENCY,
3658
+ retry = true,
3659
+ batchDelay = BATCH_START_DELAY_MS,
3660
+ timeoutMs = DEFAULT_BATCH_TIMEOUT_MS,
3661
+ taskTimeoutMs
3662
+ } = options;
3663
+ if (concurrency <= 0) {
3664
+ throw new Error("Concurrency must be greater than 0");
3665
+ }
3666
+ if (timeoutMs <= 0) {
3667
+ throw new Error("Timeout must be greater than 0");
3668
+ }
3669
+ if (taskTimeoutMs !== void 0 && taskTimeoutMs <= 0) {
3670
+ throw new Error("Task timeout must be greater than 0");
3671
+ }
3672
+ if (tasks.length === 0) {
3673
+ return [];
3674
+ }
3675
+ const startTime = Date.now();
3676
+ const results = new Array(tasks.length);
3677
+ const taskQueue = tasks.map((task, index) => ({
3678
+ index,
3679
+ task,
3680
+ errorCount: 0
3681
+ }));
3682
+ async function executeTask(taskState) {
3683
+ const { index, task, errorCount } = taskState;
3684
+ try {
3685
+ let result;
3686
+ if (taskTimeoutMs !== void 0) {
3687
+ const timeoutPromise = setTimeout$1(taskTimeoutMs).then(() => {
3688
+ throw new ZapierTimeoutError(
3689
+ `Task timed out after ${taskTimeoutMs}ms`
3690
+ );
3691
+ });
3692
+ result = await Promise.race([task(), timeoutPromise]);
3693
+ } else {
3694
+ result = await task();
3695
+ }
3696
+ results[index] = { status: "fulfilled", value: result };
3697
+ } catch (error) {
3698
+ const newErrorCount = errorCount + 1;
3699
+ const isTimeout = error instanceof ZapierTimeoutError;
3700
+ if (retry && !isTimeout && newErrorCount < MAX_CONSECUTIVE_ERRORS) {
3701
+ const waitTime = calculateWaitTime(1e3, newErrorCount);
3702
+ await setTimeout$1(waitTime);
3703
+ taskQueue.push({
3704
+ index,
3705
+ task,
3706
+ errorCount: newErrorCount
3707
+ });
3708
+ } else {
3709
+ results[index] = { status: "rejected", reason: error };
3710
+ }
3711
+ }
3712
+ }
3713
+ async function worker() {
3714
+ while (taskQueue.length > 0) {
3715
+ const elapsedTime = Date.now() - startTime;
3716
+ if (elapsedTime >= timeoutMs) {
3717
+ throw new ZapierTimeoutError(
3718
+ `Batch operation timed out after ${Math.floor(elapsedTime / 1e3)}s. ${taskQueue.length} task(s) not completed.`
3719
+ );
3720
+ }
3721
+ const taskState = taskQueue.shift();
3722
+ if (!taskState) break;
3723
+ await executeTask(taskState);
3724
+ if (taskQueue.length > 0 && batchDelay > 0) {
3725
+ await setTimeout$1(batchDelay);
3726
+ }
3727
+ }
3728
+ }
3729
+ const workerCount = Math.min(concurrency, tasks.length);
3730
+ const workers = [];
3731
+ for (let i = 0; i < workerCount; i++) {
3732
+ workers.push(worker());
3733
+ if (i < workerCount - 1 && batchDelay > 0) {
3734
+ await setTimeout$1(batchDelay / 10);
3735
+ }
3736
+ }
3737
+ await Promise.all(workers);
3738
+ return results;
3739
+ }
3594
3740
 
3595
3741
  // src/plugins/registry/index.ts
3596
3742
  var registryPlugin = ({ sdk, context }) => {
@@ -3741,43 +3887,62 @@ function transformNeedChoicesToInputFieldChoiceItem(choice) {
3741
3887
  }
3742
3888
  var listInputFieldChoicesPlugin = ({ context, sdk }) => {
3743
3889
  const listInputFieldChoices = createPaginatedFunction(async function listInputFieldChoicesPage(options) {
3744
- const { api } = context;
3890
+ const { api, getVersionedImplementationId } = context;
3745
3891
  const {
3746
3892
  appKey,
3747
3893
  actionType,
3748
3894
  actionKey,
3749
3895
  inputFieldKey,
3750
- authenticationId,
3896
+ authenticationId = null,
3751
3897
  inputs,
3752
3898
  page,
3753
3899
  cursor
3754
3900
  } = options;
3755
- const actionResult = await sdk.getAction({ appKey, actionType, actionKey });
3756
- const actionId = actionResult.data.id;
3757
- if (!actionId) {
3758
- throw new ZapierApiError(
3759
- `Action ${actionKey} does not have an ID - cannot retrieve input field choices`
3901
+ const selectedApi = await getVersionedImplementationId(appKey);
3902
+ if (!selectedApi) {
3903
+ throw new ZapierConfigurationError(
3904
+ "No current_implementation_id found for app",
3905
+ { configType: "current_implementation_id" }
3760
3906
  );
3761
3907
  }
3762
- const requestPage = cursor ? parseInt(cursor, 10) : page ?? 0;
3763
- const choicesRequest = {
3764
- action_id: actionId,
3765
- input_field_id: inputFieldKey,
3766
- page: requestPage,
3767
- params: inputs || {}
3768
- };
3769
- if (authenticationId !== null) {
3770
- choicesRequest.authentication_id = authenticationId;
3771
- }
3772
- const choicesData = await api.post(
3773
- "/api/v4/implementations/choices/",
3774
- choicesRequest
3908
+ const { data: action } = await sdk.getAction({
3909
+ appKey,
3910
+ actionType,
3911
+ actionKey
3912
+ });
3913
+ const needsData = await fetchImplementationNeeds({
3914
+ api,
3915
+ selectedApi,
3916
+ action: action.key,
3917
+ actionType,
3918
+ authenticationId,
3919
+ inputs
3920
+ });
3921
+ const targetNeed = needsData.needs?.find(
3922
+ (need) => need.key === inputFieldKey
3775
3923
  );
3776
- if (!choicesData.success) {
3924
+ if (targetNeed?.choices && targetNeed.choices.length > 0) {
3925
+ return {
3926
+ data: targetNeed.choices.map(
3927
+ transformNeedChoicesToInputFieldChoiceItem
3928
+ ),
3929
+ nextCursor: void 0
3930
+ };
3931
+ }
3932
+ if (!action.id) {
3777
3933
  throw new ZapierApiError(
3778
- `Failed to get input field choices: ${choicesData.errors?.join(", ") || "Unknown error"}`
3934
+ `Action ${actionKey} does not have an ID - cannot retrieve input field choices`
3779
3935
  );
3780
3936
  }
3937
+ const requestPage = cursor ? parseInt(cursor, 10) : page ?? 0;
3938
+ const choicesData = await fetchImplementationChoices({
3939
+ api,
3940
+ actionId: action.id,
3941
+ inputFieldId: inputFieldKey,
3942
+ authenticationId,
3943
+ inputs,
3944
+ page: requestPage
3945
+ });
3781
3946
  const choices = (choicesData.choices || []).map(
3782
3947
  transformNeedChoicesToInputFieldChoiceItem
3783
3948
  );
@@ -3975,7 +4140,7 @@ function getCpuTime() {
3975
4140
 
3976
4141
  // package.json
3977
4142
  var package_default = {
3978
- version: "0.13.8"};
4143
+ version: "0.14.0"};
3979
4144
 
3980
4145
  // src/plugins/eventEmission/builders.ts
3981
4146
  function createBaseEvent(context = {}) {
@@ -4343,4 +4508,4 @@ function createZapierSdk(options = {}) {
4343
4508
  return createZapierSdkWithoutRegistry(options).addPlugin(registryPlugin);
4344
4509
  }
4345
4510
 
4346
- export { ActionKeyPropertySchema, ActionTypePropertySchema, AppKeyPropertySchema, AuthenticationIdPropertySchema, DEFAULT_CONFIG_PATH, DebugPropertySchema, InputsPropertySchema, LimitPropertySchema, MAX_PAGE_LIMIT, OffsetPropertySchema, OutputPropertySchema, ParamsPropertySchema, RelayFetchSchema, RelayRequestSchema, ZAPIER_BASE_URL, ZapierActionError, ZapierApiError, ZapierAppNotFoundError, ZapierAuthenticationError, ZapierBundleError, ZapierConfigurationError, ZapierError, ZapierNotFoundError, ZapierResourceNotFoundError, ZapierTimeoutError, ZapierUnknownError, ZapierValidationError, actionKeyResolver, actionTypeResolver, apiPlugin, appKeyResolver, appsPlugin, authenticationIdGenericResolver, authenticationIdResolver, buildApplicationLifecycleEvent, buildErrorEvent, buildErrorEventWithContext, createBaseEvent, createFunction, createSdk, createZapierSdk, createZapierSdkWithoutRegistry, fetchPlugin, findFirstAuthenticationPlugin, findManifestEntry, findUniqueAuthenticationPlugin, formatErrorMessage, generateEventId, getActionPlugin, getAppPlugin, getAuthenticationPlugin, getCiPlatform, getCpuTime, getCurrentTimestamp, getMemoryUsage, getOsInfo, getPlatformVersions, getPreferredManifestEntryKey, getProfilePlugin, getReleaseId, getTokenFromCliLogin, getTokenFromEnv, getTokenFromEnvOrConfig, inputFieldKeyResolver, inputsAllOptionalResolver, inputsResolver, isCi, isPositional, listActionsPlugin, listAppsPlugin, listAuthenticationsPlugin, listInputFieldsPlugin, manifestPlugin, readManifestFromFile, registryPlugin, requestPlugin, runActionPlugin, toSnakeCase, toTitleCase };
4511
+ export { ActionKeyPropertySchema, ActionTypePropertySchema, AppKeyPropertySchema, AuthenticationIdPropertySchema, DEFAULT_CONFIG_PATH, DebugPropertySchema, InputsPropertySchema, LimitPropertySchema, MAX_PAGE_LIMIT, OffsetPropertySchema, OutputPropertySchema, ParamsPropertySchema, RelayFetchSchema, RelayRequestSchema, ZAPIER_BASE_URL, ZapierActionError, ZapierApiError, ZapierAppNotFoundError, ZapierAuthenticationError, ZapierBundleError, ZapierConfigurationError, ZapierError, ZapierNotFoundError, ZapierResourceNotFoundError, ZapierTimeoutError, ZapierUnknownError, ZapierValidationError, actionKeyResolver, actionTypeResolver, apiPlugin, appKeyResolver, appsPlugin, authenticationIdGenericResolver, authenticationIdResolver, batch, buildApplicationLifecycleEvent, buildErrorEvent, buildErrorEventWithContext, createBaseEvent, createFunction, createSdk, createZapierSdk, createZapierSdkWithoutRegistry, fetchPlugin, findFirstAuthenticationPlugin, findManifestEntry, findUniqueAuthenticationPlugin, formatErrorMessage, generateEventId, getActionPlugin, getAppPlugin, getAuthenticationPlugin, getCiPlatform, getCpuTime, getCurrentTimestamp, getMemoryUsage, getOsInfo, getPlatformVersions, getPreferredManifestEntryKey, getProfilePlugin, getReleaseId, getTokenFromCliLogin, getTokenFromEnv, getTokenFromEnvOrConfig, inputFieldKeyResolver, inputsAllOptionalResolver, inputsResolver, isCi, isPositional, listActionsPlugin, listAppsPlugin, listAuthenticationsPlugin, listInputFieldsPlugin, manifestPlugin, readManifestFromFile, registryPlugin, requestPlugin, runActionPlugin, toSnakeCase, toTitleCase };
@@ -3,6 +3,7 @@ import type { ApiClient } from "../../api";
3
3
  import type { InputFieldChoiceItem } from "./schemas";
4
4
  import { ListInputFieldChoicesSchema, type ListInputFieldChoicesOptions } from "./schemas";
5
5
  import type { GetActionPluginProvides } from "../getAction";
6
+ import type { GetVersionedImplementationId } from "../manifest/schemas";
6
7
  export interface ListInputFieldChoicesPluginProvides {
7
8
  listInputFieldChoices: (options: ListInputFieldChoicesOptions) => Promise<{
8
9
  data: InputFieldChoiceItem[];
@@ -24,6 +25,7 @@ export interface ListInputFieldChoicesPluginProvides {
24
25
  export declare const listInputFieldChoicesPlugin: Plugin<GetSdkType<GetActionPluginProvides>, // requires getAction in SDK
25
26
  {
26
27
  api: ApiClient;
27
- }, // requires api in context
28
+ getVersionedImplementationId: GetVersionedImplementationId;
29
+ }, // requires api and getVersionedImplementationId in context
28
30
  ListInputFieldChoicesPluginProvides>;
29
31
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/plugins/listInputFieldChoices/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAM3C,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAC;AACtD,OAAO,EACL,2BAA2B,EAC3B,KAAK,4BAA4B,EAGlC,MAAM,WAAW,CAAC;AAGnB,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAsB5D,MAAM,WAAW,mCAAmC;IAClD,qBAAqB,EAAE,CAAC,OAAO,EAAE,4BAA4B,KAAK,OAAO,CAAC;QACxE,IAAI,EAAE,oBAAoB,EAAE,CAAC;QAC7B,UAAU,CAAC,EAAE,MAAM,CAAC;KACrB,CAAC,GACA,aAAa,CAAC;QAAE,IAAI,EAAE,oBAAoB,EAAE,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,GAAG;QACrE,KAAK,IAAI,aAAa,CAAC,oBAAoB,CAAC,CAAC;KAC9C,CAAC;IACJ,OAAO,EAAE;QACP,IAAI,EAAE;YACJ,qBAAqB,EAAE;gBACrB,WAAW,EAAE,OAAO,2BAA2B,CAAC;aACjD,CAAC;SACH,CAAC;KACH,CAAC;CACH;AAED,eAAO,MAAM,2BAA2B,EAAE,MAAM,CAC9C,UAAU,CAAC,uBAAuB,CAAC,EAAE,4BAA4B;AACjE;IAAE,GAAG,EAAE,SAAS,CAAA;CAAE,EAAE,0BAA0B;AAC9C,mCAAmC,CAkHpC,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/plugins/listInputFieldChoices/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAE3C,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAC;AACtD,OAAO,EACL,2BAA2B,EAC3B,KAAK,4BAA4B,EAGlC,MAAM,WAAW,CAAC;AAGnB,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC;AA0BxE,MAAM,WAAW,mCAAmC;IAClD,qBAAqB,EAAE,CAAC,OAAO,EAAE,4BAA4B,KAAK,OAAO,CAAC;QACxE,IAAI,EAAE,oBAAoB,EAAE,CAAC;QAC7B,UAAU,CAAC,EAAE,MAAM,CAAC;KACrB,CAAC,GACA,aAAa,CAAC;QAAE,IAAI,EAAE,oBAAoB,EAAE,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,GAAG;QACrE,KAAK,IAAI,aAAa,CAAC,oBAAoB,CAAC,CAAC;KAC9C,CAAC;IACJ,OAAO,EAAE;QACP,IAAI,EAAE;YACJ,qBAAqB,EAAE;gBACrB,WAAW,EAAE,OAAO,2BAA2B,CAAC;aACjD,CAAC;SACH,CAAC;KACH,CAAC;CACH;AAED,eAAO,MAAM,2BAA2B,EAAE,MAAM,CAC9C,UAAU,CAAC,uBAAuB,CAAC,EAAE,4BAA4B;AACjE;IACE,GAAG,EAAE,SAAS,CAAC;IACf,4BAA4B,EAAE,4BAA4B,CAAC;CAC5D,EAAE,2DAA2D;AAC9D,mCAAmC,CAyIpC,CAAC"}
@@ -1,7 +1,8 @@
1
1
  import { ListInputFieldChoicesSchema, InputFieldChoiceItemSchema, } from "./schemas";
2
- import { ZapierApiError } from "../../types/errors";
2
+ import { ZapierApiError, ZapierConfigurationError } from "../../types/errors";
3
3
  import { createPaginatedFunction } from "../../utils/function-utils";
4
4
  import { appKeyResolver, actionTypeResolver, actionKeyResolver, authenticationIdResolver, inputFieldKeyResolver, inputsAllOptionalResolver, } from "../../resolvers";
5
+ import { fetchImplementationNeeds, fetchImplementationChoices, } from "../../services/implementations";
5
6
  // Transform NeedChoices to InputFieldChoiceItem
6
7
  function transformNeedChoicesToInputFieldChoiceItem(choice) {
7
8
  return {
@@ -13,32 +14,52 @@ function transformNeedChoicesToInputFieldChoiceItem(choice) {
13
14
  }
14
15
  export const listInputFieldChoicesPlugin = ({ context, sdk }) => {
15
16
  const listInputFieldChoices = createPaginatedFunction(async function listInputFieldChoicesPage(options) {
16
- const { api } = context;
17
+ const { api, getVersionedImplementationId } = context;
17
18
  // Extract parameters
18
- const { appKey, actionType, actionKey, inputFieldKey, authenticationId, inputs, page, cursor, } = options;
19
- // Use sdk.getAction to get the action ID
20
- const actionResult = await sdk.getAction({ appKey, actionType, actionKey });
21
- const actionId = actionResult.data.id;
22
- if (!actionId) {
19
+ const { appKey, actionType, actionKey, inputFieldKey, authenticationId = null, inputs, page, cursor, } = options;
20
+ // Get versioned implementation ID for the app
21
+ const selectedApi = await getVersionedImplementationId(appKey);
22
+ if (!selectedApi) {
23
+ throw new ZapierConfigurationError("No current_implementation_id found for app", { configType: "current_implementation_id" });
24
+ }
25
+ // Get action details
26
+ const { data: action } = await sdk.getAction({
27
+ appKey,
28
+ actionType,
29
+ actionKey,
30
+ });
31
+ // First, check for static choices by fetching implementation needs directly
32
+ const needsData = await fetchImplementationNeeds({
33
+ api,
34
+ selectedApi,
35
+ action: action.key,
36
+ actionType,
37
+ authenticationId,
38
+ inputs,
39
+ });
40
+ // Find the specific Need by key - search through raw needs array
41
+ const targetNeed = needsData.needs?.find((need) => need.key === inputFieldKey);
42
+ // If the need has static choices, return them
43
+ if (targetNeed?.choices && targetNeed.choices.length > 0) {
44
+ return {
45
+ data: targetNeed.choices.map(transformNeedChoicesToInputFieldChoiceItem),
46
+ nextCursor: undefined,
47
+ };
48
+ }
49
+ if (!action.id) {
23
50
  throw new ZapierApiError(`Action ${actionKey} does not have an ID - cannot retrieve input field choices`);
24
51
  }
25
- // Build choices request using action ID from getAction
26
52
  // Use cursor (from pagination) as page number if available, otherwise use explicit page or default to 0
27
53
  const requestPage = cursor ? parseInt(cursor, 10) : (page ?? 0);
28
- const choicesRequest = {
29
- action_id: actionId,
30
- input_field_id: inputFieldKey,
54
+ // Use service layer to fetch dynamic choices
55
+ const choicesData = await fetchImplementationChoices({
56
+ api,
57
+ actionId: action.id,
58
+ inputFieldId: inputFieldKey,
59
+ authenticationId,
60
+ inputs,
31
61
  page: requestPage,
32
- params: inputs || {},
33
- };
34
- // Only include authentication_id if it's not null (skip authentication when null)
35
- if (authenticationId !== null) {
36
- choicesRequest.authentication_id = authenticationId;
37
- }
38
- const choicesData = await api.post("/api/v4/implementations/choices/", choicesRequest);
39
- if (!choicesData.success) {
40
- throw new ZapierApiError(`Failed to get input field choices: ${choicesData.errors?.join(", ") || "Unknown error"}`);
41
- }
62
+ });
42
63
  // Transform NeedChoices objects to InputFieldChoiceItem objects
43
64
  const choices = (choicesData.choices || []).map(transformNeedChoicesToInputFieldChoiceItem);
44
65
  // Handle pagination