@zapier/zapier-sdk 0.49.0 → 0.51.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 (61) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +15 -12
  3. package/dist/api/auth.d.ts +1 -6
  4. package/dist/api/auth.d.ts.map +1 -1
  5. package/dist/api/auth.js +34 -27
  6. package/dist/api/client.d.ts.map +1 -1
  7. package/dist/api/client.js +20 -17
  8. package/dist/api/index.d.ts +1 -1
  9. package/dist/api/index.d.ts.map +1 -1
  10. package/dist/api/index.js +1 -1
  11. package/dist/api/schemas.d.ts +3 -3
  12. package/dist/api/types.d.ts +8 -7
  13. package/dist/api/types.d.ts.map +1 -1
  14. package/dist/auth.d.ts +13 -2
  15. package/dist/auth.d.ts.map +1 -1
  16. package/dist/auth.js +95 -11
  17. package/dist/constants.d.ts +8 -9
  18. package/dist/constants.d.ts.map +1 -1
  19. package/dist/constants.js +8 -11
  20. package/dist/experimental.cjs +184 -52
  21. package/dist/experimental.d.mts +2 -2
  22. package/dist/experimental.d.ts +26 -26
  23. package/dist/experimental.mjs +183 -52
  24. package/dist/{index-C2vsvjgN.d.mts → index-C52BjTXh.d.mts} +124 -18
  25. package/dist/{index-C2vsvjgN.d.ts → index-C52BjTXh.d.ts} +124 -18
  26. package/dist/index.cjs +184 -52
  27. package/dist/index.d.mts +1 -1
  28. package/dist/index.d.ts +2 -1
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +1 -0
  31. package/dist/index.mjs +183 -52
  32. package/dist/plugins/api/index.d.ts.map +1 -1
  33. package/dist/plugins/api/index.js +1 -2
  34. package/dist/plugins/apps/index.d.ts +2 -2
  35. package/dist/plugins/deprecated/inputFields.d.ts +18 -18
  36. package/dist/plugins/getAction/index.d.ts +6 -6
  37. package/dist/plugins/getAction/schemas.d.ts +4 -4
  38. package/dist/plugins/getActionInputFieldsSchema/index.d.ts +5 -5
  39. package/dist/plugins/getActionInputFieldsSchema/schemas.d.ts +4 -4
  40. package/dist/plugins/listActionInputFieldChoices/index.d.ts +5 -5
  41. package/dist/plugins/listActionInputFieldChoices/schemas.d.ts +4 -4
  42. package/dist/plugins/listActionInputFields/index.d.ts +5 -5
  43. package/dist/plugins/listActionInputFields/schemas.d.ts +4 -4
  44. package/dist/plugins/listActions/index.d.ts +3 -3
  45. package/dist/plugins/listActions/schemas.d.ts +4 -4
  46. package/dist/plugins/runAction/index.d.ts +5 -5
  47. package/dist/plugins/runAction/schemas.d.ts +4 -4
  48. package/dist/plugins/triggers/getTriggerInputFieldsSchema/index.d.ts +2 -2
  49. package/dist/plugins/triggers/listTriggerInputFieldChoices/index.d.ts +2 -2
  50. package/dist/plugins/triggers/listTriggerInputFields/index.d.ts +2 -2
  51. package/dist/schemas/Action.d.ts +1 -1
  52. package/dist/sdk.d.ts +52 -52
  53. package/dist/types/errors.d.ts +5 -5
  54. package/dist/types/properties.d.ts +1 -1
  55. package/dist/types/sdk.d.ts +2 -2
  56. package/dist/types/sdk.d.ts.map +1 -1
  57. package/dist/types/sdk.js +4 -11
  58. package/dist/utils/telemetry.d.ts +11 -0
  59. package/dist/utils/telemetry.d.ts.map +1 -0
  60. package/dist/utils/telemetry.js +19 -0
  61. package/package.json +1 -1
@@ -677,6 +677,69 @@ declare const NeedsResponseSchema: z.ZodObject<{
677
677
  * to ensure a single source of truth and eliminate duplication.
678
678
  */
679
679
 
680
+ interface ApiClientOptions {
681
+ baseUrl: string;
682
+ /**
683
+ * Authentication credentials.
684
+ */
685
+ credentials?: Credentials;
686
+ /**
687
+ * @deprecated Use `credentials` instead.
688
+ */
689
+ token?: string;
690
+ debug?: boolean;
691
+ fetch?: typeof globalThis.fetch;
692
+ onEvent?: (event: SdkEvent) => void;
693
+ /**
694
+ * Maximum number of retries for rate-limited requests (429 responses).
695
+ * Set to 0 to disable retries. Default is 3.
696
+ */
697
+ maxNetworkRetries?: number;
698
+ /**
699
+ * Maximum delay in milliseconds to wait for a rate limit retry.
700
+ * If the server requests a longer delay, the request fails immediately.
701
+ * Default is 60000 (60 seconds).
702
+ */
703
+ maxNetworkRetryDelayMs?: number;
704
+ /**
705
+ * Controls how the approval flow is handled.
706
+ * - "disabled": (default when env var is unset) Throw a ZapierApprovalError
707
+ * on approval-required responses without creating an approval.
708
+ * - "poll": Create the approval, open the URL in a browser, poll until
709
+ * resolved, and retry the original request on success.
710
+ * - "throw": Create the approval and throw a ZapierApprovalError immediately
711
+ * with the approval URL so the caller can surface it.
712
+ * Defaults to the ZAPIER_APPROVAL_MODE env var, then "disabled".
713
+ */
714
+ approvalMode?: "disabled" | "poll" | "throw";
715
+ /**
716
+ * Timeout in ms for approval polling. Default: 600000 (10 minutes).
717
+ */
718
+ approvalTimeoutMs?: number;
719
+ /**
720
+ * Maximum number of sequential approval rounds for a single request before
721
+ * giving up. A single request can legitimately require multiple approvals
722
+ * (one per gating policy); this cap prevents a runaway loop if the server
723
+ * keeps returning approval_required. Default: 2.
724
+ */
725
+ maxApprovalRetries?: number;
726
+ /**
727
+ * Identifies the wrapping package that built this client (e.g., the CLI or
728
+ * MCP server). When set, emitted as `x-zapier-sdk-package` /
729
+ * `x-zapier-sdk-package-version` telemetry headers. Omitted by direct
730
+ * `createZapierSdk` callers — their identity is captured by
731
+ * `x-zapier-sdk-version` alone.
732
+ */
733
+ callerPackage?: {
734
+ name: string;
735
+ version: string;
736
+ };
737
+ /**
738
+ * Pluggable key-value cache used to cache access tokens across
739
+ * invocations. See ZapierCache in ../cache.ts.
740
+ */
741
+ cache?: ZapierCache;
742
+ }
680
743
  interface ApiClient {
681
744
  get: <T = unknown>(path: string, options?: RequestOptions) => Promise<T>;
682
745
  post: <T = unknown>(path: string, data?: unknown, options?: RequestOptions) => Promise<T>;
@@ -848,6 +911,39 @@ interface CapabilitiesContext {
848
911
  hasCapability: (key: GatedFlag) => Promise<boolean>;
849
912
  }
850
913
 
914
+ /**
915
+ * API Client Implementation
916
+ *
917
+ * This module contains the core API client implementation, including
918
+ * HTTP method handlers, response processing, and client factory functions.
919
+ */
920
+
921
+ declare const createZapierApi: (options: ApiClientOptions) => ApiClient;
922
+
923
+ /**
924
+ * Zapier API Client Module
925
+ *
926
+ * This module provides a centralized API layer for all HTTP interactions
927
+ * with Zapier's various APIs. It handles authentication, error handling,
928
+ * polling, and provides consistent patterns across all services.
929
+ */
930
+
931
+ /**
932
+ * Utility function to get or create an API client for standalone functions
933
+ *
934
+ * @param config - Configuration that may include an existing API client
935
+ * @returns ApiClient instance
936
+ */
937
+ declare function getOrCreateApiClient(config: {
938
+ baseUrl?: string;
939
+ credentials?: Credentials;
940
+ /** @deprecated Use `credentials` instead */
941
+ token?: string;
942
+ api?: ApiClient;
943
+ debug?: boolean;
944
+ fetch?: typeof globalThis.fetch;
945
+ }): ApiClient;
946
+
851
947
  /**
852
948
  * Event emission types matching Avro schemas for SDK telemetry
853
949
  *
@@ -1399,12 +1495,12 @@ declare const BaseSdkOptionsSchema: z.ZodObject<{
1399
1495
  trackingBaseUrl: z.ZodOptional<z.ZodString>;
1400
1496
  maxNetworkRetries: z.ZodOptional<z.ZodNumber>;
1401
1497
  maxNetworkRetryDelayMs: z.ZodOptional<z.ZodNumber>;
1402
- isInteractive: z.ZodOptional<z.ZodBoolean>;
1403
1498
  approvalTimeoutMs: z.ZodOptional<z.ZodNumber>;
1404
1499
  maxApprovalRetries: z.ZodOptional<z.ZodNumber>;
1405
1500
  approvalMode: z.ZodOptional<z.ZodEnum<{
1501
+ disabled: "disabled";
1406
1502
  poll: "poll";
1407
- fail: "fail";
1503
+ throw: "throw";
1408
1504
  }>>;
1409
1505
  manifestPath: z.ZodOptional<z.ZodString>;
1410
1506
  manifest: z.ZodOptional<z.ZodCustom<Manifest, Manifest>>;
@@ -5621,15 +5717,15 @@ declare class ZapierRateLimitError extends ZapierError {
5621
5717
  * Terminal status of an approval attempt, exposed on `ZapierApprovalError.approvalStatus`.
5622
5718
  *
5623
5719
  * - `pending`: The approval was created but not yet resolved. Only thrown in
5624
- * `approvalMode: "fail"` — the caller is expected to surface the approval URL
5720
+ * `approvalMode: "throw"` — the caller is expected to surface the approval URL
5625
5721
  * to an end user (e.g. an LLM instructing its user to click the link).
5626
5722
  * - `denied`: A human explicitly rejected the approval in the UI.
5627
5723
  * - `policy_denied`: A policy rule blocked the request before (or instead of)
5628
5724
  * creating an approval. Cannot be approved by a human.
5629
- * - `approval_required`: The backend requested approval, but the current
5630
- * session is non-interactive so the SDK cannot open the approval URL. Retry
5631
- * in an interactive session, or use `approvalMode: "fail"` to surface the
5632
- * approval URL to the caller.
5725
+ * - `approval_required`: The backend requested approval, but `approvalMode` is
5726
+ * `"disabled"` (the default) so the SDK did not create an approval. Set
5727
+ * `approvalMode` to `"poll"` or `"throw"` (or the `ZAPIER_APPROVAL_MODE` env
5728
+ * var) to enable the approval flow.
5633
5729
  * - `timeout`: Poll mode exceeded `approvalTimeoutMs` without the approval
5634
5730
  * being resolved.
5635
5731
  * - `max_retries_exceeded`: A single request triggered more sequential approval
@@ -8493,7 +8589,18 @@ interface CliLoginOptions {
8493
8589
  };
8494
8590
  debug?: boolean;
8495
8591
  }
8496
- type CliLoginModule = typeof _zapier_zapier_sdk_cli_login;
8592
+ type CliLoginModule = typeof _zapier_zapier_sdk_cli_login & {
8593
+ getActiveCredentials?: (options?: {
8594
+ baseUrl?: string;
8595
+ }) => {
8596
+ clientId: string;
8597
+ scopes: string[];
8598
+ baseUrl?: string;
8599
+ } | undefined;
8600
+ getStoredClientCredentials?: (options?: {
8601
+ baseUrl?: string;
8602
+ }) => Promise<ClientCredentialsObject | undefined>;
8603
+ };
8497
8604
  /**
8498
8605
  * Inject an already-loaded CLI login module so the SDK skips its dynamic import.
8499
8606
  * This guarantees CLI and SDK share the same module instance in the same process.
@@ -8642,20 +8749,19 @@ declare const DEFAULT_ACTION_TIMEOUT_MS = 180000;
8642
8749
  */
8643
8750
  declare const ZAPIER_MAX_NETWORK_RETRIES: number;
8644
8751
  declare const ZAPIER_MAX_NETWORK_RETRY_DELAY_MS: number;
8645
- /**
8646
- * Whether this session is interactive (user can visit approval URLs).
8647
- *
8648
- * Read lazily so tests can set the env var after module import.
8649
- */
8650
- declare function getZapierIsInteractive(): boolean;
8651
8752
  /**
8652
8753
  * Approval flow behavior from environment variable.
8653
- * - "poll": (default) Opens the approval URL in a browser and polls until resolved.
8654
- * - "fail": Creates the approval and throws immediately with the approval URL.
8754
+ * - "disabled": (default when env var is unset) Throw a ZapierApprovalError on
8755
+ * approval-required responses without creating an approval. Callers must
8756
+ * explicitly opt in to approvals via "poll" or "throw".
8757
+ * - "poll": Create the approval, open the URL in a browser, poll until
8758
+ * resolved, and retry the original request on success.
8759
+ * - "throw": Create the approval and throw a ZapierApprovalError immediately
8760
+ * with the approval URL so the caller can surface it.
8655
8761
  *
8656
8762
  * Read lazily so tests can set the env var after module import.
8657
8763
  */
8658
- declare function getZapierApprovalMode(): "poll" | "fail" | undefined;
8764
+ declare function getZapierApprovalMode(): "disabled" | "poll" | "throw" | undefined;
8659
8765
  /**
8660
8766
  * Default timeout for approval polling (10 minutes)
8661
8767
  */
@@ -9536,4 +9642,4 @@ declare const registryPlugin: (sdk: {
9536
9642
  };
9537
9643
  }) => {};
9538
9644
 
9539
- export { type Resolver as $, type ApiClient as A, type BaseSdkOptions as B, type CapabilitiesContext as C, type DrainTriggerInboxOptions as D, type EventEmissionContext as E, type FieldsetItem as F, type GetAuthenticationPluginProvides as G, type ActionFieldChoice as H, type NeedsRequest as I, type NeedsResponse as J, type Connection as K, type LeasedTriggerMessageItem as L, type Manifest as M, type Need as N, type ConnectionsResponse as O, type PluginMeta as P, type UserProfile as Q, type ResolvedAppLocator as R, isPositional as S, type TriggerMessageStatus as T, type UpdateManifestEntryOptions as U, createFunction as V, type WithAddPlugin as W, type FormattedItem as X, type FormatMetadata as Y, type ZapierSdkOptions as Z, type OutputFormatter as _, type UpdateManifestEntryResult as a, AppPropertySchema as a$, type ArrayResolver as a0, type ResolverMetadata as a1, type StaticResolver as a2, type FieldsResolver as a3, runWithTelemetryContext as a4, toSnakeCase as a5, toTitleCase as a6, batch as a7, type BatchOptions as a8, buildCapabilityMessage as a9, type EnhancedErrorEventData as aA, type MethodCalledEventData as aB, generateEventId as aC, getCurrentTimestamp as aD, getReleaseId as aE, getOsInfo as aF, getPlatformVersions as aG, isCi as aH, getCiPlatform as aI, getMemoryUsage as aJ, getCpuTime as aK, buildApplicationLifecycleEvent as aL, buildErrorEventWithContext as aM, buildErrorEvent as aN, createBaseEvent as aO, buildMethodCalledEvent as aP, type AppItem as aQ, type ConnectionItem as aR, type ActionItem$1 as aS, type InputFieldItem as aT, type InfoFieldItem as aU, type RootFieldItem as aV, type UserProfileItem as aW, type FunctionOptions as aX, type SdkPage as aY, type PaginatedSdkFunction as aZ, AppKeyPropertySchema as a_, logDeprecation as aa, resetDeprecationWarnings as ab, RelayRequestSchema as ac, RelayFetchSchema as ad, createZapierSdkWithoutRegistry as ae, createSdk as af, createOptionsPlugin as ag, type FunctionRegistryEntry as ah, type FunctionDeprecation as ai, BaseSdkOptionsSchema as aj, type Plugin as ak, type PluginProvides as al, definePlugin as am, createPluginMethod as an, createPaginatedPluginMethod as ao, composePlugins as ap, type ActionItem as aq, type ActionTypeItem as ar, type RequestOptions as as, type PollOptions as at, registryPlugin as au, type BaseEvent as av, type MethodCalledEvent as aw, type EventEmissionProvides as ax, type EventContext as ay, type ApplicationLifecycleEventData as az, type AddActionEntryOptions as b, ZapierResourceNotFoundError as b$, ActionTypePropertySchema as b0, ActionKeyPropertySchema as b1, ActionPropertySchema as b2, InputFieldPropertySchema as b3, ConnectionIdPropertySchema as b4, AuthenticationIdPropertySchema as b5, ConnectionPropertySchema as b6, InputsPropertySchema as b7, LimitPropertySchema as b8, OffsetPropertySchema as b9, type LimitProperty as bA, type OffsetProperty as bB, type OutputProperty as bC, type DebugProperty as bD, type ParamsProperty as bE, type ActionTimeoutMsProperty as bF, type TableProperty as bG, type RecordProperty as bH, type RecordsProperty as bI, type FieldsProperty as bJ, type AppsProperty as bK, type TablesProperty as bL, type ConnectionsProperty as bM, type TriggerInboxProperty as bN, type TriggerInboxNameProperty as bO, type LeaseProperty as bP, type LeaseSecondsProperty as bQ, type LeaseLimitProperty as bR, type ApiError as bS, type ErrorOptions as bT, ZapierError as bU, ZapierApiError as bV, ZapierAppNotFoundError as bW, ZapierValidationError as bX, ZapierUnknownError as bY, ZapierAuthenticationError as bZ, ZapierNotFoundError as b_, OutputPropertySchema as ba, DebugPropertySchema as bb, ParamsPropertySchema as bc, ActionTimeoutMsPropertySchema as bd, TablePropertySchema as be, RecordPropertySchema as bf, RecordsPropertySchema as bg, FieldsPropertySchema as bh, AppsPropertySchema as bi, TablesPropertySchema as bj, ConnectionsPropertySchema as bk, TriggerInboxPropertySchema as bl, TriggerInboxNamePropertySchema as bm, LeasePropertySchema as bn, LeaseSecondsPropertySchema as bo, LeaseLimitPropertySchema as bp, type AppKeyProperty as bq, type AppProperty as br, type ActionTypeProperty as bs, type ActionKeyProperty as bt, type ActionProperty as bu, type InputFieldProperty as bv, type ConnectionIdProperty as bw, type ConnectionProperty as bx, type AuthenticationIdProperty as by, type InputsProperty as bz, type AddActionEntryResult as c, appKeyResolver as c$, ZapierConfigurationError as c0, ZapierBundleError as c1, ZapierTimeoutError as c2, ZapierActionError as c3, ZapierConflictError as c4, type RateLimitInfo as c5, ZapierRateLimitError as c6, type ApprovalStatus as c7, ZapierApprovalError as c8, ZapierRelayError as c9, getAppPlugin as cA, type GetAppPluginProvides as cB, getActionPlugin as cC, type GetActionPluginProvides as cD, getConnectionPlugin as cE, type GetConnectionPluginProvides as cF, findFirstConnectionPlugin as cG, type FindFirstConnectionPluginProvides as cH, findUniqueConnectionPlugin as cI, type FindUniqueConnectionPluginProvides as cJ, CONTEXT_CACHE_TTL_MS as cK, CONTEXT_CACHE_MAX_SIZE as cL, runActionPlugin as cM, type RunActionPluginProvides as cN, requestPlugin as cO, type RequestPluginProvides as cP, type ManifestPluginOptions as cQ, getPreferredManifestEntryKey as cR, manifestPlugin as cS, type ManifestPluginProvides as cT, DEFAULT_CONFIG_PATH as cU, type ManifestEntry as cV, getProfilePlugin as cW, type GetProfilePluginProvides as cX, type ApiPluginOptions as cY, apiPlugin as cZ, type ApiPluginProvides as c_, formatErrorMessage as ca, ZapierSignal as cb, appsPlugin as cc, type AppsPluginProvides as cd, type ActionExecutionOptions as ce, type AppFactoryInput as cf, fetchPlugin as cg, type FetchPluginProvides as ch, listAppsPlugin as ci, type ListAppsPluginProvides as cj, listActionsPlugin as ck, type ListActionsPluginProvides as cl, listActionInputFieldsPlugin as cm, type ListActionInputFieldsPluginProvides as cn, listActionInputFieldChoicesPlugin as co, type ListActionInputFieldChoicesPluginProvides as cp, getActionInputFieldsSchemaPlugin as cq, type GetActionInputFieldsSchemaPluginProvides as cr, listConnectionsPlugin as cs, type ListConnectionsPluginProvides as ct, listClientCredentialsPlugin as cu, type ListClientCredentialsPluginProvides as cv, createClientCredentialsPlugin as cw, type CreateClientCredentialsPluginProvides as cx, deleteClientCredentialsPlugin as cy, type DeleteClientCredentialsPluginProvides as cz, type ActionEntry as d, connectionsPlugin as d$, actionTypeResolver as d0, actionKeyResolver as d1, connectionIdResolver as d2, connectionIdGenericResolver as d3, inputsResolver as d4, inputsAllOptionalResolver as d5, inputFieldKeyResolver as d6, clientCredentialsNameResolver as d7, clientIdResolver as d8, tableIdResolver as d9, type LoadingEvent as dA, type EventCallback as dB, type Credentials as dC, type ResolvedCredentials as dD, type CredentialsObject as dE, type ClientCredentialsObject as dF, type PkceCredentialsObject as dG, isClientCredentials as dH, isPkceCredentials as dI, isCredentialsObject as dJ, isCredentialsFunction as dK, type ResolveCredentialsOptions as dL, resolveCredentialsFromEnv as dM, resolveCredentials as dN, getBaseUrlFromCredentials as dO, getClientIdFromCredentials as dP, ClientCredentialsObjectSchema as dQ, PkceCredentialsObjectSchema as dR, CredentialsObjectSchema as dS, ResolvedCredentialsSchema as dT, CredentialsFunctionSchema as dU, type CredentialsFunction as dV, CredentialsSchema as dW, ConnectionEntrySchema as dX, type ConnectionEntry as dY, ConnectionsMapSchema as dZ, type ConnectionsMap as d_, triggerInboxResolver as da, tableRecordIdResolver as db, tableRecordIdsResolver as dc, tableFieldIdsResolver as dd, tableNameResolver as de, tableFieldsResolver as df, tableRecordsResolver as dg, tableUpdateRecordsResolver as dh, tableFiltersResolver as di, tableSortResolver as dj, type ResolveAuthTokenOptions as dk, clearTokenCache as dl, invalidateCachedToken as dm, injectCliLogin as dn, isCliLoginAvailable as dp, getTokenFromCliLogin as dq, resolveAuthToken as dr, invalidateCredentialsToken as ds, type ZapierCache as dt, type ZapierCacheEntry as du, type ZapierCacheSetOptions as dv, createMemoryCache as dw, type SdkEvent as dx, type AuthEvent as dy, type ApiEvent as dz, type PaginatedSdkResult as e, type ConnectionsPluginProvides as e0, ZAPIER_BASE_URL as e1, getZapierSdkService as e2, MAX_PAGE_LIMIT as e3, DEFAULT_PAGE_SIZE as e4, DEFAULT_ACTION_TIMEOUT_MS as e5, ZAPIER_MAX_NETWORK_RETRIES as e6, ZAPIER_MAX_NETWORK_RETRY_DELAY_MS as e7, getZapierIsInteractive as e8, getZapierApprovalMode as e9, createZapierSdk as eA, type ZapierSdk as eB, DEFAULT_APPROVAL_TIMEOUT_MS as ea, DEFAULT_MAX_APPROVAL_RETRIES as eb, listTablesPlugin as ec, type ListTablesPluginProvides as ed, getTablePlugin as ee, type GetTablePluginProvides as ef, createTablePlugin as eg, type CreateTablePluginProvides as eh, deleteTablePlugin as ei, type DeleteTablePluginProvides as ej, listTableFieldsPlugin as ek, type ListTableFieldsPluginProvides as el, createTableFieldsPlugin as em, type CreateTableFieldsPluginProvides as en, deleteTableFieldsPlugin as eo, type DeleteTableFieldsPluginProvides as ep, getTableRecordPlugin as eq, type GetTableRecordPluginProvides as er, listTableRecordsPlugin as es, type ListTableRecordsPluginProvides as et, createTableRecordsPlugin as eu, type CreateTableRecordsPluginProvides as ev, deleteTableRecordsPlugin as ew, type DeleteTableRecordsPluginProvides as ex, updateTableRecordsPlugin as ey, type UpdateTableRecordsPluginProvides as ez, findManifestEntry as f, type PositionalMetadata as g, type ZapierFetchInitOptions as h, type DynamicResolver as i, type WatchTriggerInboxOptions as j, type ActionProxy as k, type ZapierSdkApps as l, ZapierAbortDrainSignal as m, ZapierReleaseTriggerMessageSignal as n, type DrainTriggerInboxCallback as o, type DrainTriggerInboxErrorObserver as p, type ListAuthenticationsPluginProvides as q, readManifestFromFile as r, type FindFirstAuthenticationPluginProvides as s, type FindUniqueAuthenticationPluginProvides as t, type Action as u, type App as v, type Field as w, type Choice as x, type ActionExecutionResult as y, type ActionField as z };
9645
+ export { type Resolver as $, type ApiClient as A, type BaseSdkOptions as B, type CapabilitiesContext as C, type DrainTriggerInboxOptions as D, type EventEmissionContext as E, type FieldsetItem as F, type GetAuthenticationPluginProvides as G, type ActionFieldChoice as H, type NeedsRequest as I, type NeedsResponse as J, type Connection as K, type LeasedTriggerMessageItem as L, type Manifest as M, type Need as N, type ConnectionsResponse as O, type PluginMeta as P, type UserProfile as Q, type ResolvedAppLocator as R, isPositional as S, type TriggerMessageStatus as T, type UpdateManifestEntryOptions as U, createFunction as V, type WithAddPlugin as W, type FormattedItem as X, type FormatMetadata as Y, type ZapierSdkOptions as Z, type OutputFormatter as _, type UpdateManifestEntryResult as a, type PaginatedSdkFunction as a$, type ArrayResolver as a0, type ResolverMetadata as a1, type StaticResolver as a2, type FieldsResolver as a3, runWithTelemetryContext as a4, toSnakeCase as a5, toTitleCase as a6, batch as a7, type BatchOptions as a8, buildCapabilityMessage as a9, type EventContext as aA, type ApplicationLifecycleEventData as aB, type EnhancedErrorEventData as aC, type MethodCalledEventData as aD, generateEventId as aE, getCurrentTimestamp as aF, getReleaseId as aG, getOsInfo as aH, getPlatformVersions as aI, isCi as aJ, getCiPlatform as aK, getMemoryUsage as aL, getCpuTime as aM, buildApplicationLifecycleEvent as aN, buildErrorEventWithContext as aO, buildErrorEvent as aP, createBaseEvent as aQ, buildMethodCalledEvent as aR, type AppItem as aS, type ConnectionItem as aT, type ActionItem$1 as aU, type InputFieldItem as aV, type InfoFieldItem as aW, type RootFieldItem as aX, type UserProfileItem as aY, type FunctionOptions as aZ, type SdkPage as a_, logDeprecation as aa, resetDeprecationWarnings as ab, RelayRequestSchema as ac, RelayFetchSchema as ad, createZapierSdkWithoutRegistry as ae, createSdk as af, createOptionsPlugin as ag, type FunctionRegistryEntry as ah, type FunctionDeprecation as ai, BaseSdkOptionsSchema as aj, type Plugin as ak, type PluginProvides as al, definePlugin as am, createPluginMethod as an, createPaginatedPluginMethod as ao, composePlugins as ap, type ActionItem as aq, type ActionTypeItem as ar, registryPlugin as as, type RequestOptions as at, type PollOptions as au, createZapierApi as av, getOrCreateApiClient as aw, type BaseEvent as ax, type MethodCalledEvent as ay, type EventEmissionProvides as az, type AddActionEntryOptions as b, ZapierAuthenticationError as b$, AppKeyPropertySchema as b0, AppPropertySchema as b1, ActionTypePropertySchema as b2, ActionKeyPropertySchema as b3, ActionPropertySchema as b4, InputFieldPropertySchema as b5, ConnectionIdPropertySchema as b6, AuthenticationIdPropertySchema as b7, ConnectionPropertySchema as b8, InputsPropertySchema as b9, type AuthenticationIdProperty as bA, type InputsProperty as bB, type LimitProperty as bC, type OffsetProperty as bD, type OutputProperty as bE, type DebugProperty as bF, type ParamsProperty as bG, type ActionTimeoutMsProperty as bH, type TableProperty as bI, type RecordProperty as bJ, type RecordsProperty as bK, type FieldsProperty as bL, type AppsProperty as bM, type TablesProperty as bN, type ConnectionsProperty as bO, type TriggerInboxProperty as bP, type TriggerInboxNameProperty as bQ, type LeaseProperty as bR, type LeaseSecondsProperty as bS, type LeaseLimitProperty as bT, type ApiError as bU, type ErrorOptions as bV, ZapierError as bW, ZapierApiError as bX, ZapierAppNotFoundError as bY, ZapierValidationError as bZ, ZapierUnknownError as b_, LimitPropertySchema as ba, OffsetPropertySchema as bb, OutputPropertySchema as bc, DebugPropertySchema as bd, ParamsPropertySchema as be, ActionTimeoutMsPropertySchema as bf, TablePropertySchema as bg, RecordPropertySchema as bh, RecordsPropertySchema as bi, FieldsPropertySchema as bj, AppsPropertySchema as bk, TablesPropertySchema as bl, ConnectionsPropertySchema as bm, TriggerInboxPropertySchema as bn, TriggerInboxNamePropertySchema as bo, LeasePropertySchema as bp, LeaseSecondsPropertySchema as bq, LeaseLimitPropertySchema as br, type AppKeyProperty as bs, type AppProperty as bt, type ActionTypeProperty as bu, type ActionKeyProperty as bv, type ActionProperty as bw, type InputFieldProperty as bx, type ConnectionIdProperty as by, type ConnectionProperty as bz, type AddActionEntryResult as c, apiPlugin as c$, ZapierNotFoundError as c0, ZapierResourceNotFoundError as c1, ZapierConfigurationError as c2, ZapierBundleError as c3, ZapierTimeoutError as c4, ZapierActionError as c5, ZapierConflictError as c6, type RateLimitInfo as c7, ZapierRateLimitError as c8, type ApprovalStatus as c9, deleteClientCredentialsPlugin as cA, type DeleteClientCredentialsPluginProvides as cB, getAppPlugin as cC, type GetAppPluginProvides as cD, getActionPlugin as cE, type GetActionPluginProvides as cF, getConnectionPlugin as cG, type GetConnectionPluginProvides as cH, findFirstConnectionPlugin as cI, type FindFirstConnectionPluginProvides as cJ, findUniqueConnectionPlugin as cK, type FindUniqueConnectionPluginProvides as cL, CONTEXT_CACHE_TTL_MS as cM, CONTEXT_CACHE_MAX_SIZE as cN, runActionPlugin as cO, type RunActionPluginProvides as cP, requestPlugin as cQ, type RequestPluginProvides as cR, type ManifestPluginOptions as cS, getPreferredManifestEntryKey as cT, manifestPlugin as cU, type ManifestPluginProvides as cV, DEFAULT_CONFIG_PATH as cW, type ManifestEntry as cX, getProfilePlugin as cY, type GetProfilePluginProvides as cZ, type ApiPluginOptions as c_, ZapierApprovalError as ca, ZapierRelayError as cb, formatErrorMessage as cc, ZapierSignal as cd, appsPlugin as ce, type AppsPluginProvides as cf, type ActionExecutionOptions as cg, type AppFactoryInput as ch, fetchPlugin as ci, type FetchPluginProvides as cj, listAppsPlugin as ck, type ListAppsPluginProvides as cl, listActionsPlugin as cm, type ListActionsPluginProvides as cn, listActionInputFieldsPlugin as co, type ListActionInputFieldsPluginProvides as cp, listActionInputFieldChoicesPlugin as cq, type ListActionInputFieldChoicesPluginProvides as cr, getActionInputFieldsSchemaPlugin as cs, type GetActionInputFieldsSchemaPluginProvides as ct, listConnectionsPlugin as cu, type ListConnectionsPluginProvides as cv, listClientCredentialsPlugin as cw, type ListClientCredentialsPluginProvides as cx, createClientCredentialsPlugin as cy, type CreateClientCredentialsPluginProvides as cz, type ActionEntry as d, ConnectionsMapSchema as d$, type ApiPluginProvides as d0, appKeyResolver as d1, actionTypeResolver as d2, actionKeyResolver as d3, connectionIdResolver as d4, connectionIdGenericResolver as d5, inputsResolver as d6, inputsAllOptionalResolver as d7, inputFieldKeyResolver as d8, clientCredentialsNameResolver as d9, type AuthEvent as dA, type ApiEvent as dB, type LoadingEvent as dC, type EventCallback as dD, type Credentials as dE, type ResolvedCredentials as dF, type CredentialsObject as dG, type ClientCredentialsObject as dH, type PkceCredentialsObject as dI, isClientCredentials as dJ, isPkceCredentials as dK, isCredentialsObject as dL, isCredentialsFunction as dM, type ResolveCredentialsOptions as dN, resolveCredentialsFromEnv as dO, resolveCredentials as dP, getBaseUrlFromCredentials as dQ, getClientIdFromCredentials as dR, ClientCredentialsObjectSchema as dS, PkceCredentialsObjectSchema as dT, CredentialsObjectSchema as dU, ResolvedCredentialsSchema as dV, CredentialsFunctionSchema as dW, type CredentialsFunction as dX, CredentialsSchema as dY, ConnectionEntrySchema as dZ, type ConnectionEntry as d_, clientIdResolver as da, tableIdResolver as db, triggerInboxResolver as dc, tableRecordIdResolver as dd, tableRecordIdsResolver as de, tableFieldIdsResolver as df, tableNameResolver as dg, tableFieldsResolver as dh, tableRecordsResolver as di, tableUpdateRecordsResolver as dj, tableFiltersResolver as dk, tableSortResolver as dl, type ResolveAuthTokenOptions as dm, clearTokenCache as dn, invalidateCachedToken as dp, injectCliLogin as dq, isCliLoginAvailable as dr, getTokenFromCliLogin as ds, resolveAuthToken as dt, invalidateCredentialsToken as du, type ZapierCache as dv, type ZapierCacheEntry as dw, type ZapierCacheSetOptions as dx, createMemoryCache as dy, type SdkEvent as dz, type PaginatedSdkResult as e, type ConnectionsMap as e0, connectionsPlugin as e1, type ConnectionsPluginProvides as e2, ZAPIER_BASE_URL as e3, getZapierSdkService as e4, MAX_PAGE_LIMIT as e5, DEFAULT_PAGE_SIZE as e6, DEFAULT_ACTION_TIMEOUT_MS as e7, ZAPIER_MAX_NETWORK_RETRIES as e8, ZAPIER_MAX_NETWORK_RETRY_DELAY_MS as e9, type UpdateTableRecordsPluginProvides as eA, createZapierSdk as eB, type ZapierSdk as eC, getZapierApprovalMode as ea, DEFAULT_APPROVAL_TIMEOUT_MS as eb, DEFAULT_MAX_APPROVAL_RETRIES as ec, listTablesPlugin as ed, type ListTablesPluginProvides as ee, getTablePlugin as ef, type GetTablePluginProvides as eg, createTablePlugin as eh, type CreateTablePluginProvides as ei, deleteTablePlugin as ej, type DeleteTablePluginProvides as ek, listTableFieldsPlugin as el, type ListTableFieldsPluginProvides as em, createTableFieldsPlugin as en, type CreateTableFieldsPluginProvides as eo, deleteTableFieldsPlugin as ep, type DeleteTableFieldsPluginProvides as eq, getTableRecordPlugin as er, type GetTableRecordPluginProvides as es, listTableRecordsPlugin as et, type ListTableRecordsPluginProvides as eu, createTableRecordsPlugin as ev, type CreateTableRecordsPluginProvides as ew, deleteTableRecordsPlugin as ex, type DeleteTableRecordsPluginProvides as ey, updateTableRecordsPlugin as ez, findManifestEntry as f, type PositionalMetadata as g, type ZapierFetchInitOptions as h, type DynamicResolver as i, type WatchTriggerInboxOptions as j, type ActionProxy as k, type ZapierSdkApps as l, ZapierAbortDrainSignal as m, ZapierReleaseTriggerMessageSignal as n, type DrainTriggerInboxCallback as o, type DrainTriggerInboxErrorObserver as p, type ListAuthenticationsPluginProvides as q, readManifestFromFile as r, type FindFirstAuthenticationPluginProvides as s, type FindUniqueAuthenticationPluginProvides as t, type Action as u, type App as v, type Field as w, type Choice as x, type ActionExecutionResult as y, type ActionField as z };
package/dist/index.cjs CHANGED
@@ -63,12 +63,10 @@ function parseIntEnvVar(name) {
63
63
  }
64
64
  var ZAPIER_MAX_NETWORK_RETRIES = parseIntEnvVar("ZAPIER_MAX_NETWORK_RETRIES") ?? 3;
65
65
  var ZAPIER_MAX_NETWORK_RETRY_DELAY_MS = parseIntEnvVar("ZAPIER_MAX_NETWORK_RETRY_DELAY_MS") ?? 6e4;
66
- function getZapierIsInteractive() {
67
- return globalThis.process?.env?.ZAPIER_IS_INTERACTIVE === "true";
68
- }
69
66
  function getZapierApprovalMode() {
70
67
  const value = globalThis.process?.env?.ZAPIER_APPROVAL_MODE;
71
- if (value === "poll" || value === "fail") return value;
68
+ if (value === "disabled" || value === "poll" || value === "throw")
69
+ return value;
72
70
  return void 0;
73
71
  }
74
72
  var DEFAULT_APPROVAL_TIMEOUT_MS = 10 * 60 * 1e3;
@@ -5237,33 +5235,40 @@ function getAuthorizationHeader(token) {
5237
5235
  }
5238
5236
  return `Bearer ${token}`;
5239
5237
  }
5240
- function extractUserIdsFromJwt(token) {
5238
+ function readJwtPayload(token) {
5241
5239
  const parts = parseJwt(token);
5242
- if (!parts) {
5243
- return { customuser_id: null, account_id: null };
5244
- }
5240
+ if (!parts) return null;
5241
+ let payload;
5245
5242
  try {
5246
- const payload = JSON.parse(
5247
- Buffer.from(parts[1], "base64url").toString("utf-8")
5248
- );
5249
- let actualPayload = payload;
5250
- if (payload.sub_type === "service" && payload.njwt) {
5251
- const nestedParts = payload.njwt.split(".");
5252
- if (nestedParts.length === 3) {
5253
- actualPayload = JSON.parse(
5243
+ payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf-8"));
5244
+ } catch {
5245
+ return null;
5246
+ }
5247
+ if (payload["sub_type"] === "service" && typeof payload["njwt"] === "string") {
5248
+ const nestedParts = parseJwt(payload["njwt"]);
5249
+ if (nestedParts) {
5250
+ try {
5251
+ return JSON.parse(
5254
5252
  Buffer.from(nestedParts[1], "base64url").toString("utf-8")
5255
5253
  );
5254
+ } catch {
5256
5255
  }
5257
5256
  }
5258
- const accountId = actualPayload["zap:acc"] != null ? parseInt(String(actualPayload["zap:acc"]), 10) : null;
5259
- const customUserId = actualPayload.sub_type === "customuser" && actualPayload.sub != null ? parseInt(String(actualPayload.sub), 10) : null;
5260
- return {
5261
- customuser_id: customUserId !== null && !isNaN(customUserId) ? customUserId : null,
5262
- account_id: accountId !== null && !isNaN(accountId) ? accountId : null
5263
- };
5264
- } catch {
5257
+ }
5258
+ return payload;
5259
+ }
5260
+ function extractUserIdsFromJwt(token) {
5261
+ const payload = readJwtPayload(token);
5262
+ if (!payload) {
5265
5263
  return { customuser_id: null, account_id: null };
5266
5264
  }
5265
+ const accRaw = payload["zap:acc"];
5266
+ const accountId = accRaw != null ? parseInt(String(accRaw), 10) : null;
5267
+ const customUserId = payload["sub_type"] === "customuser" && payload["sub"] != null ? parseInt(String(payload["sub"]), 10) : null;
5268
+ return {
5269
+ customuser_id: customUserId !== null && !isNaN(customUserId) ? customUserId : null,
5270
+ account_id: accountId !== null && !isNaN(accountId) ? accountId : null
5271
+ };
5267
5272
  }
5268
5273
 
5269
5274
  // src/api/debug.ts
@@ -5612,6 +5617,19 @@ function isCredentialsFunction(credentials) {
5612
5617
  return typeof credentials === "function";
5613
5618
  }
5614
5619
 
5620
+ // src/utils/telemetry.ts
5621
+ var emittedOnce = /* @__PURE__ */ new WeakMap();
5622
+ function emitOnce(onEvent, event) {
5623
+ if (!emittedOnce.has(onEvent)) {
5624
+ emittedOnce.set(onEvent, /* @__PURE__ */ new Set());
5625
+ }
5626
+ const fired = emittedOnce.get(onEvent);
5627
+ if (!fired.has(event.type)) {
5628
+ fired.add(event.type);
5629
+ onEvent(event);
5630
+ }
5631
+ }
5632
+
5615
5633
  // src/utils/url-utils.ts
5616
5634
  function getZapierBaseUrl(baseUrl) {
5617
5635
  if (!baseUrl) {
@@ -5834,8 +5852,10 @@ async function resolveCache(options) {
5834
5852
  if (cliLogin?.createCache) {
5835
5853
  try {
5836
5854
  const cache = cliLogin.createCache();
5837
- cachedDefaultCache = cache;
5838
- return cache;
5855
+ if (cache) {
5856
+ cachedDefaultCache = cache;
5857
+ return cache;
5858
+ }
5839
5859
  } catch {
5840
5860
  }
5841
5861
  }
@@ -5847,6 +5867,11 @@ function entryIsValid(entry) {
5847
5867
  if (entry.expiresAt === void 0) return true;
5848
5868
  return entry.expiresAt > Date.now() + TOKEN_EXPIRATION_BUFFER_MS;
5849
5869
  }
5870
+ async function readCachedToken(cacheKey, cache) {
5871
+ const cached = await cache.get(cacheKey);
5872
+ if (cached && entryIsValid(cached)) return cached.value;
5873
+ return void 0;
5874
+ }
5850
5875
  async function invalidateCachedToken(options) {
5851
5876
  const cacheKey = buildCacheKey(options);
5852
5877
  pendingExchanges.delete(cacheKey);
@@ -5960,11 +5985,76 @@ function isCliLoginAvailable() {
5960
5985
  if (cachedCliLogin === void 0) return void 0;
5961
5986
  return cachedCliLogin !== false;
5962
5987
  }
5988
+ function emitAuthResolved(onEvent, mechanism) {
5989
+ if (onEvent) {
5990
+ emitOnce(onEvent, {
5991
+ type: "auth_resolved",
5992
+ payload: { mechanism },
5993
+ timestamp: Date.now()
5994
+ });
5995
+ }
5996
+ }
5997
+ async function getActiveCredentialsFromCli(baseUrl) {
5998
+ const cliLogin = await getCliLogin();
5999
+ return cliLogin?.getActiveCredentials?.({ baseUrl });
6000
+ }
6001
+ async function getStoredClientCredentialsFromCli(baseUrl) {
6002
+ const cliLogin = await getCliLogin();
6003
+ return cliLogin?.getStoredClientCredentials?.({ baseUrl });
6004
+ }
5963
6005
  async function getTokenFromCliLogin(options) {
5964
6006
  const cliLogin = await getCliLogin();
5965
6007
  if (!cliLogin) return void 0;
5966
6008
  return await cliLogin.getToken(options);
5967
6009
  }
6010
+ async function tryStoredClientCredentialToken(options) {
6011
+ const activeCredential = await getActiveCredentialsFromCli(options.baseUrl);
6012
+ if (!activeCredential) return void 0;
6013
+ const resolvedBaseUrl = activeCredential.baseUrl || options.baseUrl || DEFAULT_AUTH_BASE_URL;
6014
+ const mergedScopes = mergeScopes(
6015
+ activeCredential.scopes.join(" "),
6016
+ options.requiredScopes
6017
+ );
6018
+ const cacheKey = buildCacheKey({
6019
+ clientId: activeCredential.clientId,
6020
+ scopes: mergedScopes,
6021
+ baseUrl: resolvedBaseUrl
6022
+ });
6023
+ const cache = await resolveCache(options);
6024
+ const pending = pendingExchanges.get(cacheKey);
6025
+ if (pending) return pending;
6026
+ const cached = await readCachedToken(cacheKey, cache);
6027
+ if (cached !== void 0) {
6028
+ if (options.debug)
6029
+ console.log(
6030
+ `[auth] Using cached token (clientId: ${activeCredential.clientId})`
6031
+ );
6032
+ emitAuthResolved(options.onEvent, "client_credentials");
6033
+ return cached;
6034
+ }
6035
+ const storedCredential = await getStoredClientCredentialsFromCli(resolvedBaseUrl);
6036
+ if (!storedCredential) {
6037
+ await invalidateCachedToken({
6038
+ clientId: activeCredential.clientId,
6039
+ scopes: activeCredential.scopes,
6040
+ baseUrl: resolvedBaseUrl,
6041
+ cache: options.cache
6042
+ });
6043
+ throw new ZapierAuthenticationError(
6044
+ `Stored client credential is missing its secret (clientId: ${activeCredential.clientId}). Run \`zapier-sdk login\` to recreate it.`
6045
+ );
6046
+ }
6047
+ if (options.debug)
6048
+ console.log(
6049
+ `[auth] Using stored client credential (clientId: ${storedCredential.clientId})`
6050
+ );
6051
+ const token = await resolveAuthTokenFromCredentials(
6052
+ storedCredential,
6053
+ options
6054
+ );
6055
+ emitAuthResolved(options.onEvent, "client_credentials");
6056
+ return token;
6057
+ }
5968
6058
  async function resolveAuthToken(options = {}) {
5969
6059
  const credentials = await resolveCredentials({
5970
6060
  credentials: options.credentials,
@@ -5974,14 +6064,24 @@ async function resolveAuthToken(options = {}) {
5974
6064
  if (credentials !== void 0) {
5975
6065
  return resolveAuthTokenFromCredentials(credentials, options);
5976
6066
  }
5977
- return getTokenFromCliLogin({
6067
+ const storedToken = await tryStoredClientCredentialToken(options);
6068
+ if (storedToken !== void 0) return storedToken;
6069
+ if (options.debug) {
6070
+ console.log("[auth] Using JWT (no stored client credential found)");
6071
+ }
6072
+ const jwtToken = await getTokenFromCliLogin({
5978
6073
  onEvent: options.onEvent,
5979
6074
  fetch: options.fetch,
5980
6075
  debug: options.debug
5981
6076
  });
6077
+ if (jwtToken !== void 0) {
6078
+ emitAuthResolved(options.onEvent, "jwt");
6079
+ }
6080
+ return jwtToken;
5982
6081
  }
5983
6082
  async function resolveAuthTokenFromCredentials(credentials, options) {
5984
6083
  if (typeof credentials === "string") {
6084
+ emitAuthResolved(options.onEvent, "token");
5985
6085
  return credentials;
5986
6086
  }
5987
6087
  if (isClientCredentials(credentials)) {
@@ -5994,15 +6094,25 @@ async function resolveAuthTokenFromCredentials(credentials, options) {
5994
6094
  baseUrl: resolvedBaseUrl
5995
6095
  });
5996
6096
  const cache = await resolveCache(options);
5997
- const cached = await cache.get(cacheKey);
5998
- if (cached && entryIsValid(cached)) {
5999
- return cached.value;
6097
+ const cached = await readCachedToken(cacheKey, cache);
6098
+ if (cached !== void 0) {
6099
+ if (options.debug) {
6100
+ console.log(`[auth] Using cached token (clientId: ${clientId})`);
6101
+ }
6102
+ return cached;
6000
6103
  }
6001
6104
  const pending = pendingExchanges.get(cacheKey);
6002
6105
  if (pending) return pending;
6003
6106
  const runLocked = async () => {
6004
- const recheck = await cache.get(cacheKey);
6005
- if (recheck && entryIsValid(recheck)) return recheck.value;
6107
+ const recheck = await readCachedToken(cacheKey, cache);
6108
+ if (recheck !== void 0) {
6109
+ if (options.debug) {
6110
+ console.log(
6111
+ `[auth] Using cached token (clientId: ${clientId}, locked recheck)`
6112
+ );
6113
+ }
6114
+ return recheck;
6115
+ }
6006
6116
  const { accessToken, expiresIn } = await exchangeClientCredentials({
6007
6117
  clientId: credentials.clientId,
6008
6118
  clientSecret: credentials.clientSecret,
@@ -6060,7 +6170,7 @@ async function invalidateCredentialsToken(options) {
6060
6170
  }
6061
6171
 
6062
6172
  // src/sdk-version.ts
6063
- var SDK_VERSION = (typeof process !== "undefined" && process.env ? "0.49.0" : void 0) || "unknown";
6173
+ var SDK_VERSION = (typeof process !== "undefined" && process.env ? "0.51.0" : void 0) || "unknown";
6064
6174
 
6065
6175
  // src/utils/open-url.ts
6066
6176
  var nodePrefix = "node:";
@@ -6335,10 +6445,10 @@ var ZapierApiClient = class {
6335
6445
  }
6336
6446
  if (errorType !== "approval_required") return response;
6337
6447
  if (attempt === maxRetries) break;
6338
- const isInteractive = this.options.isInteractive ?? getZapierIsInteractive();
6339
- if (!isInteractive) {
6448
+ const mode = this.options.approvalMode ?? getZapierApprovalMode() ?? "disabled";
6449
+ if (mode === "disabled") {
6340
6450
  throw new ZapierApprovalError(
6341
- "Approval required but session is not interactive",
6451
+ "Approvals are disabled. Set approvalMode to 'poll' or 'throw' (or ZAPIER_APPROVAL_MODE) to enable.",
6342
6452
  { status: "approval_required" }
6343
6453
  );
6344
6454
  }
@@ -6348,7 +6458,7 @@ var ZapierApiClient = class {
6348
6458
  { statusCode: 403 }
6349
6459
  );
6350
6460
  }
6351
- await this.runOneApprovalRound(init.approvalContext);
6461
+ await this.runOneApprovalRound(init.approvalContext, mode);
6352
6462
  }
6353
6463
  throw new ZapierApprovalError(
6354
6464
  `Exceeded maximum approval retries (${maxRetries}) for ${path}`,
@@ -6641,7 +6751,9 @@ var ZapierApiClient = class {
6641
6751
  if (data && typeof data === "object") {
6642
6752
  headers["Content-Type"] = "application/json";
6643
6753
  }
6644
- const wasMissingAuthToken = options.authRequired && await this.getAuthToken({ requiredScopes: options.requiredScopes }) == null;
6754
+ const wasMissingAuthToken = options.authRequired && await this.getAuthToken({
6755
+ requiredScopes: options.requiredScopes
6756
+ }) == null;
6645
6757
  const response = await this.fetch(path, {
6646
6758
  ...options,
6647
6759
  method,
@@ -6667,10 +6779,13 @@ var ZapierApiClient = class {
6667
6779
  }
6668
6780
  /**
6669
6781
  * Run a single approval round: create the approval, open the URL (poll mode)
6670
- * or throw (fail mode), poll until resolved, and emit events. Throws on
6782
+ * or throw (throw mode), poll until resolved, and emit events. Throws on
6671
6783
  * denied/timeout/unexpected status. Returns on approved.
6784
+ *
6785
+ * Caller is responsible for passing a non-"disabled" mode; this method
6786
+ * unconditionally creates an approval.
6672
6787
  */
6673
- async runOneApprovalRound(buildContext) {
6788
+ async runOneApprovalRound(buildContext, mode) {
6674
6789
  const context = buildContext();
6675
6790
  let approvalResponse;
6676
6791
  try {
@@ -6745,8 +6860,7 @@ var ZapierApiClient = class {
6745
6860
  approvalId: approval.approval_id,
6746
6861
  approvalUrl: approval.approval_url
6747
6862
  });
6748
- const approvalMode = this.options.approvalMode ?? getZapierApprovalMode();
6749
- if (approvalMode === "fail") {
6863
+ if (mode === "throw") {
6750
6864
  throw new ZapierApprovalError("This request requires approval.", {
6751
6865
  approvalId: approval.approval_id,
6752
6866
  approvalUrl: approval.approval_url,
@@ -6833,6 +6947,28 @@ var createZapierApi = (options) => {
6833
6947
  });
6834
6948
  };
6835
6949
 
6950
+ // src/api/index.ts
6951
+ function getOrCreateApiClient(config) {
6952
+ const {
6953
+ baseUrl = ZAPIER_BASE_URL,
6954
+ credentials,
6955
+ token,
6956
+ api: providedApi,
6957
+ debug = false,
6958
+ fetch: customFetch
6959
+ } = config;
6960
+ if (providedApi) {
6961
+ return providedApi;
6962
+ }
6963
+ return createZapierApi({
6964
+ baseUrl,
6965
+ credentials,
6966
+ token,
6967
+ debug,
6968
+ fetch: customFetch
6969
+ });
6970
+ }
6971
+
6836
6972
  // src/plugins/api/index.ts
6837
6973
  var apiPlugin = definePlugin(
6838
6974
  (sdk) => {
@@ -6845,7 +6981,6 @@ var apiPlugin = definePlugin(
6845
6981
  debug = false,
6846
6982
  maxNetworkRetries = ZAPIER_MAX_NETWORK_RETRIES,
6847
6983
  maxNetworkRetryDelayMs = ZAPIER_MAX_NETWORK_RETRY_DELAY_MS,
6848
- isInteractive,
6849
6984
  approvalTimeoutMs,
6850
6985
  maxApprovalRetries,
6851
6986
  approvalMode,
@@ -6860,7 +6995,6 @@ var apiPlugin = definePlugin(
6860
6995
  onEvent,
6861
6996
  maxNetworkRetries,
6862
6997
  maxNetworkRetryDelayMs,
6863
- isInteractive,
6864
6998
  approvalTimeoutMs,
6865
6999
  maxApprovalRetries,
6866
7000
  approvalMode,
@@ -8746,16 +8880,13 @@ var BaseSdkOptionsSchema = zod.z.object({
8746
8880
  * Default is 60000 (60 seconds).
8747
8881
  */
8748
8882
  maxNetworkRetryDelayMs: zod.z.number().optional().describe("Max delay in ms to wait for retry (default: 60000).").meta({ valueHint: "ms" }),
8749
- isInteractive: zod.z.boolean().optional().describe(
8750
- "Whether this session is interactive (user can visit approval URLs). Defaults to ZAPIER_IS_INTERACTIVE env var."
8751
- ).meta({ internal: true }),
8752
- approvalTimeoutMs: zod.z.number().optional().describe("Timeout in ms for approval polling. Default: 600000 (10 min).").meta({ valueHint: "ms", internal: true }),
8883
+ approvalTimeoutMs: zod.z.number().optional().describe("Timeout in ms for approval polling. Default: 600000 (10 min).").meta({ valueHint: "ms" }),
8753
8884
  maxApprovalRetries: zod.z.number().optional().describe(
8754
8885
  "Maximum number of sequential approval rounds per request (one per gating policy) before giving up. Default: 2."
8755
- ).meta({ internal: true }),
8756
- approvalMode: zod.z.enum(["poll", "fail"]).optional().describe(
8757
- 'Approval flow behavior. "poll" opens browser and polls (default). "fail" creates the approval and throws immediately with the approval URL.'
8758
- ).meta({ internal: true }),
8886
+ ),
8887
+ approvalMode: zod.z.enum(["disabled", "poll", "throw"]).optional().describe(
8888
+ 'Approval flow behavior. "disabled" (default) throws a ZapierApprovalError on approval-required responses without creating an approval. "poll" creates the approval, opens it in a browser, polls until resolved, and retries the original request. "throw" creates the approval and throws a ZapierApprovalError with the approval URL so the caller can surface it. Defaults to the ZAPIER_APPROVAL_MODE env var, then "disabled".'
8889
+ ),
8759
8890
  // Internal
8760
8891
  manifestPath: zod.z.string().optional().describe("Path to a .zapierrc manifest file for app version locking.").meta({ internal: true }),
8761
8892
  manifest: zod.z.custom().optional().describe("Manifest for app version locking.").meta({ internal: true }),
@@ -8880,6 +9011,7 @@ exports.createSdk = createSdk;
8880
9011
  exports.createTableFieldsPlugin = createTableFieldsPlugin;
8881
9012
  exports.createTablePlugin = createTablePlugin;
8882
9013
  exports.createTableRecordsPlugin = createTableRecordsPlugin;
9014
+ exports.createZapierApi = createZapierApi;
8883
9015
  exports.createZapierSdk = createZapierSdk;
8884
9016
  exports.createZapierSdkWithoutRegistry = createZapierSdkWithoutRegistry;
8885
9017
  exports.definePlugin = definePlugin;
@@ -8903,6 +9035,7 @@ exports.getConnectionPlugin = getConnectionPlugin;
8903
9035
  exports.getCpuTime = getCpuTime;
8904
9036
  exports.getCurrentTimestamp = getCurrentTimestamp;
8905
9037
  exports.getMemoryUsage = getMemoryUsage;
9038
+ exports.getOrCreateApiClient = getOrCreateApiClient;
8906
9039
  exports.getOsInfo = getOsInfo;
8907
9040
  exports.getPlatformVersions = getPlatformVersions;
8908
9041
  exports.getPreferredManifestEntryKey = getPreferredManifestEntryKey;
@@ -8912,7 +9045,6 @@ exports.getTablePlugin = getTablePlugin;
8912
9045
  exports.getTableRecordPlugin = getTableRecordPlugin;
8913
9046
  exports.getTokenFromCliLogin = getTokenFromCliLogin;
8914
9047
  exports.getZapierApprovalMode = getZapierApprovalMode;
8915
- exports.getZapierIsInteractive = getZapierIsInteractive;
8916
9048
  exports.getZapierSdkService = getZapierSdkService;
8917
9049
  exports.injectCliLogin = injectCliLogin;
8918
9050
  exports.inputFieldKeyResolver = inputFieldKeyResolver;