@zapier/zapier-sdk 0.94.1 → 0.96.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.
@@ -1,5 +1,5 @@
1
- import { defineMethod, DEFAULT_PAGE_SIZE, apiPluginRef, workflowIdResolver, openEnum, durableRunIdResolver, defineResolver, ZapierConflictError, extractErrorDetail, workflowVersionIdResolver, workflowDraftIdResolver, ZapierApiError, workflowRunIdResolver, definePlugin, zapierSdkPlugin, ZapierValidationError, createSdk, zapierCoreOptions, CORE_OPTIONS_ID, SDK_OPTIONS_ID } from './chunk-XETAS26U.mjs';
2
- export { ACTION_RUNS_PATH, API_ID, ActionKeyPropertySchema, ActionPropertySchema, ActionTimeoutMillisecondsPropertySchema, ActionTimeoutSecondsPropertySchema, ActionTypePropertySchema, AppKeyPropertySchema, AppPropertySchema, AppsPropertySchema, AuthMechanism, AuthenticationIdPropertySchema, BaseSdkOptionsSchema, CONNECTIONS_ID, CONTEXT, CONTEXT_CACHE_MAX_SIZE, CONTEXT_CACHE_TTL_MILLISECONDS, CORE_ERROR_SYMBOL, CORE_OPTIONS_ID, CORE_SIGNAL_SYMBOL, ClientCredentialsObjectSchema, ConnectionEntrySchema, ConnectionIdPropertySchema, ConnectionPropertySchema, ConnectionsMapSchema, ConnectionsPropertySchema, CoreCancelledSignal, CoreDisposeError, CoreErrorCode, CoreSignal, CredentialsFunctionSchema, CredentialsObjectSchema, CredentialsSchema, DEFAULT_ACTION_TIMEOUT_MILLISECONDS, DEFAULT_APPROVAL_TIMEOUT_MILLISECONDS, DEFAULT_CONFIG_PATH, DEFAULT_MAX_APPROVAL_RETRIES, DEFAULT_PAGE_SIZE, DEPRECATION_NOTICE_EVENT, DebugPropertySchema, DrainTriggerInboxSchema, EVENT_EMISSION_ID, FieldsPropertySchema, InputFieldPropertySchema, InputsPropertySchema, LeaseLimitPropertySchema, LeasePropertySchema, LeaseSecondsPropertySchema, LimitPropertySchema, MANIFEST_ID, MAX_CONCURRENCY_LIMIT, MAX_PAGE_LIMIT, OffsetPropertySchema, OutputPropertySchema, ParamsPropertySchema, PkceCredentialsObjectSchema, RESOLVE_CREDENTIALS_ID, RecordPropertySchema, RecordsPropertySchema, RelayFetchSchema, RelayRequestSchema, ResolvedCredentialsSchema, SDK_OPTIONS_ID, TablePropertySchema, TablesPropertySchema, TriggerInboxKeyPropertySchema, TriggerInboxNamePropertySchema, TriggerInboxPropertySchema, WatchTriggerInboxSchema, ZAPIER_BASE_URL, ZAPIER_MAX_CONCURRENT_REQUESTS, ZAPIER_MAX_NETWORK_RETRIES, ZAPIER_MAX_NETWORK_RETRY_DELAY_MILLISECONDS, ZapierAbortDrainSignal, ZapierActionError, ZapierApiError, ZapierAppNotFoundError, ZapierApprovalError, ZapierAuthenticationError, ZapierBundleError, ZapierConfigurationError, ZapierConflictError, ZapierError, ZapierNotFoundError, ZapierRateLimitError, ZapierRelayError, ZapierReleaseTriggerMessageSignal, ZapierResourceNotFoundError, ZapierSignal, ZapierTimeoutError, ZapierUnknownError, ZapierValidationError, actionKeyResolver, actionTypeResolver, addPlugin, apiPlugin, apiPluginRef, appKeyResolver, appsPlugin, batch, buildApplicationLifecycleEvent, buildCapabilityMessage, buildErrorEvent, buildErrorEventWithContext, buildMethodCalledEvent, cleanupEventListeners, clearTokenCache, clientCredentialsNameResolver, clientIdResolver, composePlugins, connectionIdGenericResolver, connectionIdResolver, connectionsPlugin, connectionsPluginRef, createActionRunPlugin, createBaseEvent, createClientCredentialsPlugin, createController, createCorePlugin, createFunction, createMemoryCache, createPaginatedFunction, createPaginatedPluginMethod, createPluginMethod, createPluginStack, createSdk, createTableFieldsPlugin, createTablePlugin, createTableRecordsPlugin, createZapierApi, createZapierSdkWithoutRegistry, declareMethod, declareOptionalProperty, declarePlugin, declareProperty, defineFormatter, defineLegacyMerge, defineMethod, defineMethodOverride, definePlugin, defineProperty, defineResolver, deleteClientCredentialsPlugin, deleteTableFieldsPlugin, deleteTablePlugin, deleteTableRecordsPlugin, disposeSdk, durableRunIdResolver, eventEmissionHookPlugin, eventEmissionPlugin, eventEmissionPluginRef, fetchPlugin, findFirstConnectionPlugin, findManifestEntry, findUniqueConnectionPlugin, formatErrorMessage, fromFunctionPlugin, generateEventId, getActionInputFieldsSchemaPlugin, getActionPlugin, getActionRunPlugin, getAgent, getAppPlugin, getBaseUrlFromCredentials, getCallerContext, getCiPlatform, getClientIdFromCredentials, getConnectionPlugin, getContext, getCoreErrorCause, getCoreErrorCode, getCpuTime, getCurrentTimestamp, getMemoryUsage, getNegatable, getOrCreateApiClient, getOsInfo, getPlatformVersions, getPreferredManifestEntryKey, getProfilePlugin, getRegistryPlugin, getReleaseId, getTablePlugin, getTableRecordPlugin, getTokenFromCliLogin, getTtyContext, getZapierApprovalMode, getZapierDefaultApprovalMode, getZapierOpenAutoModeApprovalsInBrowser, getZapierSdkService, injectCliLogin, inputFieldKeyResolver, inputsAllOptionalResolver, inputsResolver, invalidateCachedToken, invalidateCredentialsToken, isCi, isCliLoginAvailable, isClientCredentials, isCoreCancelledSignal, isCoreError, isCoreSignal, isCredentialsFunction, isCredentialsObject, isPermanentHttpError, isPkceCredentials, isPositional, isZapierAbortDrainSignal, isZapierActionError, isZapierAppNotFoundError, isZapierApprovalError, isZapierAuthenticationError, isZapierBundleError, isZapierConflictError, isZapierError, isZapierNotFoundError, isZapierRateLimitError, isZapierReleaseTriggerMessageSignal, isZapierResourceNotFoundError, isZapierSignal, isZapierTimeoutError, isZapierValidationError, listActionInputFieldChoicesPlugin, listActionInputFieldsPlugin, listActionsPlugin, listAppsPlugin, listClientCredentialsPlugin, listConnectionsPlugin, listTableFieldsPlugin, listTableRecordsPlugin, listTablesPlugin, logDeprecation, manifestPlugin, manifestPluginRef, omitExports, operationAnnotatorPlugin, parseConcurrencyEnvVar, readManifestFromFile, registryPlugin, requestPlugin, resetDeprecationWarnings, resolveAuth, resolveAuthToken, resolveCredentials, resolveCredentialsFromEnv, resolveCredentialsPlugin, resolveCredentialsPluginRef, resolvePlugin, runActionPlugin, runInMethodScope, runWithCallerContext, runWithTelemetryContext, sdkOptionsPluginRef, selectExports, tableFieldIdsResolver, tableFieldsResolver, tableFiltersResolver, tableIdResolver, tableNameResolver, tableRecordIdResolver, tableRecordIdsResolver, tableRecordsResolver, tableSortResolver, tableUpdateRecordsResolver, toSnakeCase, toTitleCase, triggerInboxResolver, triggerMessagesResolver, updateTableRecordsPlugin, workflowDraftIdResolver, workflowIdResolver, workflowRunIdResolver, workflowVersionIdResolver, zapierAdaptError, zapierCoreOptions, zapierSdkPlugin } from './chunk-XETAS26U.mjs';
1
+ import { defineMethod, DEFAULT_PAGE_SIZE, apiPluginRef, workflowIdResolver, openEnum, durableRunIdResolver, defineResolver, ZapierConflictError, extractErrorDetail, workflowVersionIdResolver, workflowDraftIdResolver, ZapierApiError, workflowRunIdResolver, definePlugin, zapierSdkPlugin, ZapierValidationError, ZapierConfigurationError, createSdk, zapierCoreOptions, CORE_OPTIONS_ID, SDK_OPTIONS_ID } from './chunk-MLSC6GO6.mjs';
2
+ export { ACTION_RUNS_PATH, API_ID, ActionKeyPropertySchema, ActionPropertySchema, ActionTimeoutMillisecondsPropertySchema, ActionTimeoutSecondsPropertySchema, ActionTypePropertySchema, AppKeyPropertySchema, AppPropertySchema, AppsPropertySchema, AuthMechanism, AuthenticationIdPropertySchema, BaseSdkOptionsSchema, CONNECTIONS_ID, CONTEXT, CONTEXT_CACHE_MAX_SIZE, CONTEXT_CACHE_TTL_MILLISECONDS, CORE_ERROR_SYMBOL, CORE_OPTIONS_ID, CORE_SIGNAL_SYMBOL, ClientCredentialsObjectSchema, ConnectionEntrySchema, ConnectionIdPropertySchema, ConnectionPropertySchema, ConnectionsMapSchema, ConnectionsPropertySchema, CoreCancelledSignal, CoreDisposeError, CoreErrorCode, CoreSignal, CredentialsFunctionSchema, CredentialsObjectSchema, CredentialsSchema, DEFAULT_ACTION_TIMEOUT_MILLISECONDS, DEFAULT_APPROVAL_TIMEOUT_MILLISECONDS, DEFAULT_CONFIG_PATH, DEFAULT_MAX_APPROVAL_RETRIES, DEFAULT_PAGE_SIZE, DEPRECATION_NOTICE_EVENT, DebugPropertySchema, DrainTriggerInboxSchema, EVENT_EMISSION_ID, FieldsPropertySchema, InputFieldPropertySchema, InputsPropertySchema, LeaseLimitPropertySchema, LeasePropertySchema, LeaseSecondsPropertySchema, LimitPropertySchema, MANIFEST_ID, MAX_CONCURRENCY_LIMIT, MAX_PAGE_LIMIT, OffsetPropertySchema, OutputPropertySchema, ParamsPropertySchema, PkceCredentialsObjectSchema, RESOLVE_CREDENTIALS_ID, RecordPropertySchema, RecordsPropertySchema, RelayFetchSchema, RelayRequestSchema, ResolvedCredentialsSchema, SDK_OPTIONS_ID, TablePropertySchema, TablesPropertySchema, TriggerInboxKeyPropertySchema, TriggerInboxNamePropertySchema, TriggerInboxPropertySchema, WatchTriggerInboxSchema, ZAPIER_BASE_URL, ZAPIER_MAX_CONCURRENT_REQUESTS, ZAPIER_MAX_NETWORK_RETRIES, ZAPIER_MAX_NETWORK_RETRY_DELAY_MILLISECONDS, ZapierAbortDrainSignal, ZapierActionError, ZapierApiError, ZapierAppNotFoundError, ZapierApprovalError, ZapierAuthenticationError, ZapierBundleError, ZapierConfigurationError, ZapierConflictError, ZapierError, ZapierNotFoundError, ZapierRateLimitError, ZapierRelayError, ZapierReleaseTriggerMessageSignal, ZapierResourceNotFoundError, ZapierSignal, ZapierTimeoutError, ZapierUnknownError, ZapierValidationError, actionKeyResolver, actionTypeResolver, addPlugin, apiPlugin, apiPluginRef, appKeyResolver, appsPlugin, batch, buildApplicationLifecycleEvent, buildCapabilityMessage, buildErrorEvent, buildErrorEventWithContext, buildMethodCalledEvent, cleanupEventListeners, clearTokenCache, clientCredentialsNameResolver, clientIdResolver, composePlugins, connectionIdGenericResolver, connectionIdResolver, connectionsPlugin, connectionsPluginRef, createActionRunPlugin, createBaseEvent, createClientCredentialsPlugin, createController, createCorePlugin, createFunction, createMemoryCache, createPaginatedFunction, createPaginatedPluginMethod, createPluginMethod, createPluginStack, createSdk, createTableFieldsPlugin, createTablePlugin, createTableRecordsPlugin, createZapierApi, createZapierSdkWithoutRegistry, declareMethod, declareOptionalProperty, declarePlugin, declareProperty, defineFormatter, defineLegacyMerge, defineMethod, defineMethodOverride, definePlugin, defineProperty, defineResolver, deleteClientCredentialsPlugin, deleteTableFieldsPlugin, deleteTablePlugin, deleteTableRecordsPlugin, disposeSdk, durableRunIdResolver, eventEmissionHookPlugin, eventEmissionPlugin, eventEmissionPluginRef, fetchPlugin, findFirstConnectionPlugin, findManifestEntry, findUniqueConnectionPlugin, formatErrorMessage, fromFunctionPlugin, generateEventId, getActionInputFieldsSchemaPlugin, getActionPlugin, getActionRunPlugin, getAgent, getAppPlugin, getBaseUrlFromCredentials, getCallerContext, getCiPlatform, getClientIdFromCredentials, getConnectionPlugin, getContext, getCoreErrorCause, getCoreErrorCode, getCpuTime, getCurrentTimestamp, getMemoryUsage, getNegatable, getOrCreateApiClient, getOsInfo, getPlatformVersions, getPreferredManifestEntryKey, getProfilePlugin, getRegistryPlugin, getReleaseId, getTablePlugin, getTableRecordPlugin, getTokenFromCliLogin, getTtyContext, getZapierApprovalMode, getZapierDefaultApprovalMode, getZapierOpenAutoModeApprovalsInBrowser, getZapierSdkService, injectCliLogin, inputFieldKeyResolver, inputsAllOptionalResolver, inputsResolver, invalidateCachedToken, invalidateCredentialsToken, isCi, isCliLoginAvailable, isClientCredentials, isCoreCancelledSignal, isCoreError, isCoreSignal, isCredentialsFunction, isCredentialsObject, isPermanentHttpError, isPkceCredentials, isPositional, isZapierAbortDrainSignal, isZapierActionError, isZapierAppNotFoundError, isZapierApprovalError, isZapierAuthenticationError, isZapierBundleError, isZapierConflictError, isZapierError, isZapierNotFoundError, isZapierRateLimitError, isZapierReleaseTriggerMessageSignal, isZapierResourceNotFoundError, isZapierSignal, isZapierTimeoutError, isZapierValidationError, listActionInputFieldChoicesPlugin, listActionInputFieldsPlugin, listActionsPlugin, listAppsPlugin, listClientCredentialsPlugin, listConnectionsPlugin, listTableFieldsPlugin, listTableRecordsPlugin, listTablesPlugin, logDeprecation, manifestPlugin, manifestPluginRef, omitExports, operationAnnotatorPlugin, parseConcurrencyEnvVar, readManifestFromFile, registryPlugin, requestPlugin, resetDeprecationWarnings, resolveAuth, resolveAuthToken, resolveCredentials, resolveCredentialsFromEnv, resolveCredentialsPlugin, resolveCredentialsPluginRef, resolvePlugin, runActionPlugin, runInMethodScope, runWithCallerContext, runWithTelemetryContext, sdkOptionsPluginRef, selectExports, tableFieldIdsResolver, tableFieldsResolver, tableFiltersResolver, tableIdResolver, tableNameResolver, tableRecordIdResolver, tableRecordIdsResolver, tableRecordsResolver, tableSortResolver, tableUpdateRecordsResolver, toSnakeCase, toTitleCase, triggerInboxResolver, triggerMessagesResolver, updateTableRecordsPlugin, workflowDraftIdResolver, workflowIdResolver, workflowRunIdResolver, workflowVersionIdResolver, zapierAdaptError, zapierCoreOptions, zapierSdkPlugin } from './chunk-MLSC6GO6.mjs';
3
3
  import './chunk-Y6FXYEAI.mjs';
4
4
  import { z } from 'zod';
5
5
 
@@ -953,14 +953,23 @@ var PublishWorkflowVersionBaseSchema = z.object({
953
953
  /** @deprecated Use `appVersions` instead. */
954
954
  app_versions: z.record(z.string(), AppVersionBindingSchema).nullish().meta({ deprecated: true }),
955
955
  trigger: TriggerConfigSchema.optional().describe(
956
- "Trigger configuration. When provided, the workflow subscribes to a Zapier trigger; omit for webhook-only workflows."
956
+ "Trigger configuration. When provided, the workflow subscribes to a Zapier trigger; for an on-demand, triggerless workflow, omit this and pass `manual: true` instead."
957
+ ),
958
+ manual: z.boolean().optional().describe(
959
+ "Declare this an on-demand, triggerless workflow version. Pass `manual: true` only when omitting `trigger`; passing both is a contradiction the API rejects with a 400."
957
960
  )
958
961
  });
959
962
  var WorkflowPropertySchema = z.string().uuid().describe("Durable workflow ID");
963
+ function hasNoTriggerManualConflict(data) {
964
+ return !(data.trigger !== void 0 && data.manual === true);
965
+ }
966
+ var TRIGGER_MANUAL_CONFLICT_MESSAGE = "Provide `trigger` or `manual: true`, not both \u2014 a trigger together with manual: true is a contradiction.";
960
967
  var PublishWorkflowVersionSchema = z.object({
961
968
  workflow: WorkflowPropertySchema,
962
969
  sourceFiles: SourceFilesSchema
963
- }).merge(PublishWorkflowVersionBaseSchema).describe(PublishWorkflowVersionDescription).meta({
970
+ }).merge(PublishWorkflowVersionBaseSchema).refine(hasNoTriggerManualConflict, {
971
+ message: TRIGGER_MANUAL_CONFLICT_MESSAGE
972
+ }).describe(PublishWorkflowVersionDescription).meta({
964
973
  aliases: {
965
974
  source_files: "sourceFiles",
966
975
  zapier_durable_version: "zapierDurableVersion",
@@ -970,7 +979,9 @@ var PublishWorkflowVersionSchema = z.object({
970
979
  var PublishWorkflowVersionSchemaDeprecated = z.object({
971
980
  workflow: WorkflowPropertySchema,
972
981
  source_files: SourceFilesSchema
973
- }).merge(PublishWorkflowVersionBaseSchema);
982
+ }).merge(PublishWorkflowVersionBaseSchema).refine(hasNoTriggerManualConflict, {
983
+ message: TRIGGER_MANUAL_CONFLICT_MESSAGE
984
+ });
974
985
  var PublishWorkflowVersionOptionsSchema = z.union([PublishWorkflowVersionSchema, PublishWorkflowVersionSchemaDeprecated]).describe(PublishWorkflowVersionDescription);
975
986
  var PublishWorkflowVersionResponseSchema = WorkflowVersionSchema;
976
987
 
@@ -1057,6 +1068,9 @@ var publishWorkflowVersionPlugin = defineMethod({
1057
1068
  if (input.trigger !== void 0) {
1058
1069
  body.trigger = toWireTrigger(input.trigger);
1059
1070
  }
1071
+ if (input.manual !== void 0) {
1072
+ body.manual = input.manual;
1073
+ }
1060
1074
  const raw = await api.post(
1061
1075
  `${CODE_SUBSTRATE_WORKFLOWS_API}/workflows/${encodeURIComponent(input.workflow)}/versions`,
1062
1076
  body,
@@ -1816,6 +1830,341 @@ var triggerWorkflowPlugin = defineMethod({
1816
1830
  }
1817
1831
  });
1818
1832
 
1833
+ // src/plugins/humanInput/shared.ts
1834
+ var humanInputDefaults = {
1835
+ categories: ["human-input"],
1836
+ experimental: true
1837
+ };
1838
+ var FORMS_API = "/forms/v0";
1839
+ var FORMS_ACCESS_DENIED_DETAIL = "This user does not yet have access to Forms.";
1840
+ function firstErrorDetail(data) {
1841
+ if (typeof data !== "object" || data === null || !("errors" in data) || !Array.isArray(data.errors)) {
1842
+ return void 0;
1843
+ }
1844
+ const first = data.errors[0];
1845
+ if (typeof first !== "object" || first === null || !("detail" in first)) {
1846
+ return void 0;
1847
+ }
1848
+ return typeof first.detail === "string" ? first.detail : void 0;
1849
+ }
1850
+ function handleFormsAccessError({
1851
+ status,
1852
+ data
1853
+ }) {
1854
+ if (status !== 403 || firstErrorDetail(data) !== FORMS_ACCESS_DENIED_DETAIL) {
1855
+ return void 0;
1856
+ }
1857
+ return new ZapierConfigurationError(
1858
+ `${FORMS_ACCESS_DENIED_DETAIL} Request access through Zapier support at https://zapier.com/app/get-help.`,
1859
+ { statusCode: status }
1860
+ );
1861
+ }
1862
+
1863
+ // src/plugins/humanInput/utils.ts
1864
+ var FORM_DOCUMENT_SCHEMA_VERSION = 4;
1865
+ function omitUndefined(body) {
1866
+ return Object.fromEntries(
1867
+ Object.entries(body).filter(([, value]) => value !== void 0)
1868
+ );
1869
+ }
1870
+ function labelToKey(label) {
1871
+ return label.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
1872
+ }
1873
+ function toWireDataSource(dataSource) {
1874
+ return omitUndefined({
1875
+ app: dataSource.app,
1876
+ action_type: dataSource.actionType,
1877
+ resource: dataSource.resource,
1878
+ value_key: dataSource.valueKey,
1879
+ label_key: dataSource.labelKey
1880
+ });
1881
+ }
1882
+ function toFieldAttrs(field, key) {
1883
+ const base = {
1884
+ key,
1885
+ label: field.label,
1886
+ required: field.required ?? false,
1887
+ field_type: field.type,
1888
+ disabled: field.disabled
1889
+ };
1890
+ switch (field.type) {
1891
+ case "yes_no":
1892
+ return omitUndefined({ ...base, variant: field.variant ?? "checkbox" });
1893
+ case "url":
1894
+ return omitUndefined({ ...base, multi_url: field.multiUrl ?? false });
1895
+ case "date":
1896
+ case "date_range":
1897
+ return omitUndefined({
1898
+ ...base,
1899
+ include_time: field.includeTime ?? false
1900
+ });
1901
+ case "currency":
1902
+ return omitUndefined({
1903
+ ...base,
1904
+ decimals: field.decimals ?? 2,
1905
+ currency_format: field.currencyFormat
1906
+ });
1907
+ case "phone_number":
1908
+ return omitUndefined({
1909
+ ...base,
1910
+ default_country: field.defaultCountry ?? "US",
1911
+ phone_number_format: field.phoneNumberFormat ?? "national",
1912
+ accepted_countries: field.acceptedCountries
1913
+ });
1914
+ case "dropdown":
1915
+ return omitUndefined({
1916
+ ...base,
1917
+ options: field.options,
1918
+ multi_select: field.multiSelect ?? false
1919
+ });
1920
+ case "integration_backed":
1921
+ return omitUndefined({
1922
+ ...base,
1923
+ data_source: field.dataSource === void 0 ? void 0 : toWireDataSource(field.dataSource)
1924
+ });
1925
+ default:
1926
+ return omitUndefined(base);
1927
+ }
1928
+ }
1929
+ function assertUniqueKeys(keys, fields) {
1930
+ const seen = /* @__PURE__ */ new Map();
1931
+ for (const [index, key] of keys.entries()) {
1932
+ const label = fields[index]?.label ?? "";
1933
+ const previous = seen.get(key);
1934
+ if (previous !== void 0) {
1935
+ throw new ZapierValidationError(
1936
+ `Fields "${previous}" and "${label}" both derive the submission key "${key}". Give them labels that differ by more than punctuation or casing.`,
1937
+ { details: { key, labels: [previous, label] } }
1938
+ );
1939
+ }
1940
+ seen.set(key, label);
1941
+ }
1942
+ }
1943
+ function toEndingActionNode(id, title, message) {
1944
+ const trimmedTitle = title?.trim();
1945
+ const trimmedMessage = message?.trim();
1946
+ if (!trimmedTitle && !trimmedMessage) return void 0;
1947
+ return {
1948
+ id,
1949
+ type: "ending_action",
1950
+ attrs: omitUndefined({
1951
+ variant: "success",
1952
+ title: trimmedTitle || void 0,
1953
+ message: trimmedMessage || void 0
1954
+ })
1955
+ };
1956
+ }
1957
+ function buildFormDocument(input) {
1958
+ const fields = input.fields ?? [];
1959
+ const keys = fields.map(
1960
+ (field, index) => labelToKey(field.label) || `field_${index + 1}`
1961
+ );
1962
+ assertUniqueKeys(keys, fields);
1963
+ const children = fields.map((field, index) => ({
1964
+ id: `@field_${index + 1}`,
1965
+ type: "field",
1966
+ attrs: toFieldAttrs(field, keys[index])
1967
+ }));
1968
+ const endingAction = toEndingActionNode(
1969
+ "@ending_action",
1970
+ input.confirmationTitle,
1971
+ input.confirmationMessage
1972
+ );
1973
+ if (endingAction) children.push(endingAction);
1974
+ return {
1975
+ id: "@root",
1976
+ type: "root",
1977
+ attrs: omitUndefined({
1978
+ schema_version: FORM_DOCUMENT_SCHEMA_VERSION,
1979
+ title: input.title,
1980
+ description: input.description
1981
+ }),
1982
+ children
1983
+ };
1984
+ }
1985
+ function toWireFormAttributes(input) {
1986
+ return omitUndefined({
1987
+ document: input.document ?? buildFormDocument(input),
1988
+ consumer_auth: input.consumerAuth,
1989
+ callback_url: input.callbackUrl,
1990
+ publish: input.draft === true ? false : void 0
1991
+ });
1992
+ }
1993
+ var FormFieldTypeSchema = z.enum([
1994
+ "short_text",
1995
+ "long_text",
1996
+ "email",
1997
+ "number",
1998
+ "yes_no",
1999
+ "url",
2000
+ "date",
2001
+ "date_range",
2002
+ "currency",
2003
+ "phone_number",
2004
+ "dropdown",
2005
+ "integration_backed"
2006
+ ]);
2007
+ var ConsumerAuthSchema = z.enum(["none", "zapier"]);
2008
+ var DropdownOptionSchema = z.object({
2009
+ value: z.string().min(1).describe("The value submitted when this option is selected."),
2010
+ label: z.string().min(1).describe("Human-readable label shown to the user.")
2011
+ });
2012
+ var FieldDataSourceSchema = z.object({
2013
+ app: z.string().min(1).describe(
2014
+ "Zapier app to pull options from. See `listApps` for the catalog."
2015
+ ),
2016
+ actionType: z.enum(["read", "read_bulk"]).describe(
2017
+ "Whether the data source returns a single record (`read`) or a collection (`read_bulk`)."
2018
+ ),
2019
+ resource: z.string().min(1).describe(
2020
+ "Resource name within the app \u2014 typically a trigger or search key from the app's definition."
2021
+ ),
2022
+ valueKey: z.string().min(1).optional().describe(
2023
+ "Property on each returned record to use as the submitted option value. Defaults to `id`."
2024
+ ),
2025
+ labelKey: z.string().min(1).optional().describe(
2026
+ "Property on each returned record to use as the displayed option label. Defaults to a sensible name field."
2027
+ )
2028
+ });
2029
+ var FormFieldBaseSchema = z.object({
2030
+ label: z.string().min(1).describe("Human-readable label shown above the input."),
2031
+ type: FormFieldTypeSchema.describe("The type of field."),
2032
+ required: z.boolean().optional().describe("Whether the field must be answered before the form can submit."),
2033
+ disabled: z.boolean().optional().describe(
2034
+ "When true, the field is rendered read-only \u2014 shown but not editable. A rendering hint only; it is not enforced during submission validation."
2035
+ ),
2036
+ variant: z.enum(["checkbox", "radio"]).optional().describe(
2037
+ "For `yes_no` fields: `checkbox` renders a single toggle, `radio` renders explicit yes/no buttons. Defaults to `checkbox`."
2038
+ ),
2039
+ multiUrl: z.boolean().optional().describe(
2040
+ "For `url` fields: when true the field accepts a list of URLs, otherwise a single URL. Defaults to false."
2041
+ ),
2042
+ includeTime: z.boolean().optional().describe(
2043
+ "For `date` and `date_range` fields: when true the picker also captures a time. Defaults to false."
2044
+ ),
2045
+ currencyFormat: z.string().regex(/^[A-Za-z]{3}$/).optional().describe(
2046
+ "For `currency` fields: ISO 4217 currency code (e.g. `usd`, `eur`). Controls the symbol shown in the form UI."
2047
+ ),
2048
+ decimals: z.union([z.literal(0), z.literal(2)]).optional().describe(
2049
+ "For `currency` fields: allowed decimal places. `0` for whole numbers, `2` for up to two decimal places. Defaults to `2`."
2050
+ ),
2051
+ defaultCountry: z.string().regex(/^[A-Z]{2}$/).optional().describe(
2052
+ "For `phone_number` fields: ISO 3166-1 alpha-2 code for the default selected country (e.g. `US`). Defaults to `US`."
2053
+ ),
2054
+ phoneNumberFormat: z.enum(["national", "international"]).optional().describe(
2055
+ "For `phone_number` fields: `national` omits the country-code prefix, `international` includes it. Defaults to `national`."
2056
+ ),
2057
+ acceptedCountries: z.array(z.string().regex(/^[A-Z]{2}$/)).optional().describe(
2058
+ "For `phone_number` fields: restrict input to specific ISO 3166-1 alpha-2 country codes. Omit to allow all countries."
2059
+ ),
2060
+ options: z.array(DropdownOptionSchema).min(1).optional().describe(
2061
+ "For `dropdown` fields: the selectable options. At least one is required."
2062
+ ),
2063
+ multiSelect: z.boolean().optional().describe(
2064
+ "For `dropdown` fields: when true the user may select multiple options. Defaults to false."
2065
+ ),
2066
+ dataSource: FieldDataSourceSchema.optional().describe(
2067
+ "For `integration_backed` fields: where to fetch the field's options from at render time."
2068
+ )
2069
+ });
2070
+ var FormFieldSchema = FormFieldBaseSchema.superRefine((field, ctx) => {
2071
+ if (field.type === "dropdown" && field.options === void 0) {
2072
+ ctx.addIssue({
2073
+ code: "custom",
2074
+ path: ["options"],
2075
+ message: "A dropdown field requires `options`."
2076
+ });
2077
+ }
2078
+ if (field.type === "integration_backed" && field.dataSource === void 0) {
2079
+ ctx.addIssue({
2080
+ code: "custom",
2081
+ path: ["dataSource"],
2082
+ message: "An integration_backed field requires `dataSource`."
2083
+ });
2084
+ }
2085
+ });
2086
+ var RawFormDocumentSchema = z.object({
2087
+ id: z.string().min(1),
2088
+ type: z.literal("root"),
2089
+ attrs: z.object({
2090
+ schema_version: z.number().int(),
2091
+ title: z.string().min(1)
2092
+ }).loose(),
2093
+ children: z.array(z.unknown()).optional()
2094
+ }).loose();
2095
+ var FormSchema = z.object({
2096
+ id: z.string(),
2097
+ title: z.string(),
2098
+ description: z.string().nullish(),
2099
+ hosted_url: z.string(),
2100
+ submission_count: z.number(),
2101
+ account_id: z.number(),
2102
+ owner_id: z.string(),
2103
+ created_at: z.string(),
2104
+ updated_at: z.string(),
2105
+ document: z.unknown(),
2106
+ last_published_at: z.string().nullable(),
2107
+ consumer_auth: z.unknown(),
2108
+ callback_url: z.unknown()
2109
+ }).loose();
2110
+
2111
+ // src/plugins/humanInput/createForm/schemas.ts
2112
+ var CreateFormDescription = "Create a Zapier Form from a title and optional fields. Forms publish by default and return a shareable `hosted_url`; set `draft` to save without publishing.";
2113
+ var CreateFormSchema = z.object({
2114
+ title: z.string().min(1).describe("The title shown in the Forms UI and on the form."),
2115
+ description: z.string().optional().describe("An optional description of the form."),
2116
+ fields: z.array(FormFieldSchema).optional().describe("Initial fields to add to the form."),
2117
+ draft: z.boolean().optional().describe(
2118
+ "When true, save without publishing. Omit to publish immediately, making `hosted_url` live."
2119
+ ),
2120
+ confirmationTitle: z.string().max(200).optional().describe(
2121
+ "Heading shown to the respondent after they submit. Omit to use the form renderer's default."
2122
+ ),
2123
+ confirmationMessage: z.string().max(1e3).optional().describe(
2124
+ "Message shown to the respondent after they submit, below the confirmation title. Omit to use the form renderer's default."
2125
+ ),
2126
+ callbackUrl: z.string().url().optional().describe(
2127
+ "Absolute http/https URL notified with the submission JSON each time the form is answered."
2128
+ ),
2129
+ consumerAuth: ConsumerAuthSchema.optional().describe(
2130
+ "Who may open the published form. `none` (the default) leaves it public to anyone with the link; `zapier` requires the visitor to be signed in to Zapier on the form's owning account."
2131
+ ),
2132
+ document: RawFormDocumentSchema.optional().describe(
2133
+ "Escape hatch: a complete form document tree, sent as-is. When supplied it replaces the document built from `fields`, and `title`, `description`, `confirmationTitle`, and `confirmationMessage` are ignored. Use only for structures the flat field list cannot express, such as approval decisions or multi-column row layout."
2134
+ )
2135
+ }).describe(CreateFormDescription);
2136
+
2137
+ // src/plugins/humanInput/createForm/index.ts
2138
+ var createFormPlugin = defineMethod({
2139
+ ...humanInputDefaults,
2140
+ name: "createForm",
2141
+ imports: [apiPluginRef],
2142
+ type: "create",
2143
+ itemType: "Form",
2144
+ inputSchema: CreateFormSchema,
2145
+ outputSchema: FormSchema,
2146
+ output: "item",
2147
+ run: async ({ imports, input }) => {
2148
+ const api = imports.api;
2149
+ const body = toWireFormAttributes({
2150
+ title: input.title,
2151
+ description: input.description,
2152
+ confirmationTitle: input.confirmationTitle,
2153
+ confirmationMessage: input.confirmationMessage,
2154
+ consumerAuth: input.consumerAuth,
2155
+ callbackUrl: input.callbackUrl,
2156
+ draft: input.draft,
2157
+ fields: input.fields,
2158
+ document: input.document
2159
+ });
2160
+ const rawResponse = await api.post(`${FORMS_API}/forms`, body, {
2161
+ authRequired: true,
2162
+ customErrorHandler: handleFormsAccessError
2163
+ });
2164
+ return { data: FormSchema.parse(rawResponse) };
2165
+ }
2166
+ });
2167
+
1819
2168
  // src/experimental.ts
1820
2169
  var zapierExperimentalSdkPlugin = definePlugin({
1821
2170
  namespace: "zapier",
@@ -1848,7 +2197,10 @@ var zapierExperimentalSdkPlugin = definePlugin({
1848
2197
  runDurablePlugin,
1849
2198
  cancelDurableRunPlugin,
1850
2199
  triggerWorkflowPlugin,
1851
- getTriggerRunPlugin
2200
+ getTriggerRunPlugin,
2201
+ // Human input (experimental). Routed through the Public API Gateway
2202
+ // rather than the sdkapi proxy — see the `/forms` entry in api/client.ts.
2203
+ createFormPlugin
1852
2204
  ]
1853
2205
  });
1854
2206
  function createZapierSdk(options = {}) {