@zapier/zapier-sdk 0.81.0 → 0.82.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.cjs CHANGED
@@ -3140,14 +3140,14 @@ var TriggerInboxCommandBaseSchema = zod.z.object({
3140
3140
  "Abort signal. Aborting cancels in-flight HTTP, releases unprocessed messages, and resolves cleanly. Errors during shutdown still reject."
3141
3141
  )
3142
3142
  });
3143
- TriggerInboxCommandBaseSchema.extend({
3143
+ var DrainTriggerInboxSchema = TriggerInboxCommandBaseSchema.extend({
3144
3144
  maxMessages: zod.z.number().int().min(1).optional().describe(
3145
3145
  "Cap total messages drained. Defaults to draining the inbox until empty."
3146
3146
  )
3147
3147
  }).describe(
3148
3148
  "Drain an existing trigger inbox: lease currently-available messages and process them via onMessage. Returns when the inbox is empty, maxMessages is reached, the abort signal fires, or a fatal error rejects."
3149
3149
  );
3150
- TriggerInboxCommandBaseSchema.extend({
3150
+ var WatchTriggerInboxSchema = TriggerInboxCommandBaseSchema.extend({
3151
3151
  maxDrainIntervalSeconds: zod.z.number().int().min(1).optional().describe(
3152
3152
  "Maximum seconds between safety drain attempts (default: 300). The watcher subscribes to SSE notifications for near-real-time wake-ups; this interval is the backstop that guarantees forward progress if SSE events are missed or the connection drops undetected."
3153
3153
  )
@@ -6785,11 +6785,11 @@ var runActionPlugin = definePlugin(
6785
6785
  timeoutMs
6786
6786
  });
6787
6787
  if (result.errors && result.errors.length > 0) {
6788
- const errorMessage = result.errors.map(
6788
+ const errorMessage2 = result.errors.map(
6789
6789
  (error) => error.detail || error.title || "Unknown error"
6790
6790
  ).join("; ");
6791
6791
  throw new ZapierActionError(
6792
- `Action execution failed: ${errorMessage}`,
6792
+ `Action execution failed: ${errorMessage2}`,
6793
6793
  { appKey, actionKey }
6794
6794
  );
6795
6795
  }
@@ -8752,7 +8752,7 @@ function parseDeprecationDate(value) {
8752
8752
  }
8753
8753
 
8754
8754
  // src/sdk-version.ts
8755
- var SDK_VERSION = (typeof process !== "undefined" && process.env ? "0.81.0" : void 0) || "unknown";
8755
+ var SDK_VERSION = (typeof process !== "undefined" && process.env ? "0.82.0" : void 0) || "unknown";
8756
8756
 
8757
8757
  // src/utils/open-url.ts
8758
8758
  var nodePrefix = "node:";
@@ -9456,16 +9456,16 @@ var ZapierApiClient = class {
9456
9456
  if (typeof errorInfo.data === "string") {
9457
9457
  return { message: `${fallbackMessage}: ${errorInfo.data}` };
9458
9458
  }
9459
- const errorMessage = this.extractErrorMessage(errorInfo.data) || fallbackMessage;
9459
+ const errorMessage2 = this.extractErrorMessage(errorInfo.data) || fallbackMessage;
9460
9460
  if (this.hasErrorArray(errorInfo.data)) {
9461
9461
  if (this.isApiErrorArray(errorInfo.data.errors)) {
9462
9462
  return {
9463
- message: errorMessage,
9463
+ message: errorMessage2,
9464
9464
  errors: errorInfo.data.errors
9465
9465
  };
9466
9466
  } else {
9467
9467
  return {
9468
- message: errorMessage,
9468
+ message: errorMessage2,
9469
9469
  errors: errorInfo.data.errors.map((e) => ({
9470
9470
  status: errorInfo.status,
9471
9471
  code: String(errorInfo.status),
@@ -9475,7 +9475,7 @@ var ZapierApiClient = class {
9475
9475
  };
9476
9476
  }
9477
9477
  }
9478
- return { message: errorMessage };
9478
+ return { message: errorMessage2 };
9479
9479
  } catch {
9480
9480
  return { message: fallbackMessage };
9481
9481
  }
@@ -10498,6 +10498,1658 @@ var getInputFieldsSchemaDeprecatedPlugin = definePlugin(
10498
10498
  }
10499
10499
  })
10500
10500
  );
10501
+ var TriggerInboxStatusSchema = zod.z.union([
10502
+ zod.z.enum([
10503
+ "initializing",
10504
+ "active",
10505
+ "paused",
10506
+ "deleting",
10507
+ "initialization_failure"
10508
+ ]),
10509
+ zod.z.string()
10510
+ ]).describe("Inbox lifecycle status");
10511
+ var TriggerInboxPausedReasonSchema = zod.z.union([
10512
+ zod.z.enum([
10513
+ "user",
10514
+ "authentication",
10515
+ "authentication_access_revoked",
10516
+ "partner_revoked",
10517
+ "subscribe_failed",
10518
+ "migrate_failed",
10519
+ "abandoned",
10520
+ "unknown",
10521
+ "upstream_failures"
10522
+ ]),
10523
+ zod.z.string()
10524
+ ]).describe("Why the inbox was paused, if applicable");
10525
+ var TriggerSubscriptionApiSchema = zod.z.object({
10526
+ connection_id: zod.z.union([zod.z.string(), zod.z.number(), zod.z.null()]),
10527
+ app_key: zod.z.string(),
10528
+ action_key: zod.z.string(),
10529
+ inputs: zod.z.record(zod.z.string(), zod.z.unknown())
10530
+ });
10531
+ var TriggerInboxItemSchema = zod.z.object({
10532
+ id: zod.z.string(),
10533
+ created_at: zod.z.string(),
10534
+ // `key` is an API-layer alias over the same nullable `name` column, so it's
10535
+ // always present but can be null — null means no natural key (inbox created
10536
+ // without one, or key cleared on delete).
10537
+ key: zod.z.string().nullable(),
10538
+ /** @deprecated Use `key` instead. */
10539
+ name: zod.z.string().nullable(),
10540
+ status: TriggerInboxStatusSchema,
10541
+ paused_reason: TriggerInboxPausedReasonSchema.nullable(),
10542
+ notification_url: zod.z.string().nullable(),
10543
+ subscription: TriggerSubscriptionApiSchema
10544
+ });
10545
+
10546
+ // src/plugins/triggers/createTriggerInbox/schemas.ts
10547
+ var CreateTriggerInboxDescription = "Create a new trigger inbox subscription. Always creates a new inbox; use ensureTriggerInbox for get-or-create on a stable key.";
10548
+ var CreateTriggerInboxSchema = zod.z.object({
10549
+ key: TriggerInboxKeyPropertySchema.optional().describe(
10550
+ "Optional inbox key. Auto-generated when omitted. Throws a conflict error if the key is already in use by another subscription."
10551
+ ),
10552
+ /** @deprecated Use `key` instead. */
10553
+ name: TriggerInboxNamePropertySchema.optional().describe(
10554
+ "Optional inbox name. Auto-generated when omitted. Throws a conflict error if the name is already in use by another subscription."
10555
+ ).meta({ deprecated: true }),
10556
+ app: AppPropertySchema,
10557
+ action: ActionPropertySchema,
10558
+ connection: ConnectionPropertySchema.nullable().optional().describe(
10559
+ "Connection alias or connection ID. Optional for triggers that don't require auth."
10560
+ ),
10561
+ inputs: InputsPropertySchema.optional().describe(
10562
+ "Input parameters for the trigger subscription"
10563
+ ),
10564
+ notificationUrl: zod.z.string().url().optional().describe("Webhook URL to POST to when new messages arrive")
10565
+ }).describe(CreateTriggerInboxDescription);
10566
+
10567
+ // src/formatters/triggerInbox.ts
10568
+ var triggerInboxItemFormatter = {
10569
+ format: (item) => {
10570
+ const details = [
10571
+ {
10572
+ text: `Status: ${item.status}`,
10573
+ style: item.status === "active" ? "accent" : "dim"
10574
+ },
10575
+ {
10576
+ text: `Subscription: ${item.subscription.app_key} / ${item.subscription.action_key}`,
10577
+ style: "dim"
10578
+ }
10579
+ ];
10580
+ if (item.paused_reason) {
10581
+ details.push({
10582
+ text: `Paused reason: ${item.paused_reason}`,
10583
+ style: "warning"
10584
+ });
10585
+ }
10586
+ if (item.notification_url) {
10587
+ details.push({
10588
+ text: `Notify: ${item.notification_url}`,
10589
+ style: "dim"
10590
+ });
10591
+ }
10592
+ return {
10593
+ title: item.key ?? item.name ?? `Trigger Inbox ${item.id}`,
10594
+ id: item.id,
10595
+ details
10596
+ };
10597
+ }
10598
+ };
10599
+
10600
+ // src/plugins/triggers/shared.ts
10601
+ var triggersDefaults = {
10602
+ categories: ["trigger"]
10603
+ };
10604
+
10605
+ // src/plugins/triggers/utils.ts
10606
+ var UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
10607
+ async function resolveTriggerInboxId({
10608
+ api,
10609
+ inbox
10610
+ }) {
10611
+ if (UUID_REGEX.test(inbox)) {
10612
+ return inbox;
10613
+ }
10614
+ const rawResponse = await api.get("/trigger-inbox/api/v1/inboxes", {
10615
+ searchParams: { key: inbox, limit: "1" },
10616
+ authRequired: true
10617
+ });
10618
+ const response = rawResponse;
10619
+ const id = response.results?.[0]?.id;
10620
+ if (!id) {
10621
+ throw new ZapierResourceNotFoundError(
10622
+ `No trigger inbox with key "${inbox}" found.`,
10623
+ { resourceType: "trigger_inbox", resourceId: inbox }
10624
+ );
10625
+ }
10626
+ return id;
10627
+ }
10628
+ function extractErrorDetail(data) {
10629
+ if (typeof data !== "object" || data === null) return void 0;
10630
+ const errors = data.errors;
10631
+ if (!Array.isArray(errors) || errors.length === 0) return void 0;
10632
+ const first = errors[0];
10633
+ if (typeof first !== "object" || first === null) return void 0;
10634
+ const detail = first.detail;
10635
+ return typeof detail === "string" ? detail : void 0;
10636
+ }
10637
+
10638
+ // src/plugins/triggers/createTriggerInbox/index.ts
10639
+ var createTriggerInboxPlugin = definePlugin(
10640
+ (sdk) => createPluginMethod(sdk, {
10641
+ ...triggersDefaults,
10642
+ name: "createTriggerInbox",
10643
+ type: "create",
10644
+ itemType: "TriggerInbox",
10645
+ inputSchema: CreateTriggerInboxSchema,
10646
+ outputSchema: TriggerInboxItemSchema,
10647
+ formatter: triggerInboxItemFormatter,
10648
+ // actionKeyResolver and inputsResolver depend on actionType, which is
10649
+ // always "read" for triggers. Pin it as a constant resolver so it's
10650
+ // seeded into resolvedParams without polluting the user-facing schema
10651
+ // (where it would leak into the SDK method signature and CLI flags).
10652
+ resolvers: {
10653
+ key: { type: "static", inputType: "text" },
10654
+ app: appKeyResolver,
10655
+ action: actionKeyResolver,
10656
+ connection: connectionIdResolver,
10657
+ inputs: inputsResolver,
10658
+ actionType: { type: "constant", value: "read" }
10659
+ },
10660
+ handler: async ({ sdk: sdk2, options }) => {
10661
+ const { api } = sdk2.context;
10662
+ const {
10663
+ app: appKey,
10664
+ action: actionKey,
10665
+ connection,
10666
+ inputs = {},
10667
+ notificationUrl
10668
+ } = options;
10669
+ const key2 = options.key ?? options.name;
10670
+ const resolvedConnectionId = await resolveConnectionId({
10671
+ connection,
10672
+ resolveConnection: sdk2.context.resolveConnection
10673
+ });
10674
+ const selectedApi = await sdk2.context.getVersionedImplementationId(appKey);
10675
+ if (!selectedApi) {
10676
+ throw new ZapierConfigurationError(
10677
+ `No current_implementation_id found for app "${appKey}"`,
10678
+ { configType: "current_implementation_id" }
10679
+ );
10680
+ }
10681
+ const requestBody = {
10682
+ subscription: {
10683
+ app_key: selectedApi,
10684
+ action_key: actionKey,
10685
+ inputs,
10686
+ connection_id: resolvedConnectionId ?? null
10687
+ }
10688
+ };
10689
+ if (key2 !== void 0) {
10690
+ requestBody.key = key2;
10691
+ }
10692
+ if (notificationUrl !== void 0) {
10693
+ requestBody.notification_url = notificationUrl;
10694
+ }
10695
+ const rawResponse = await api.post(
10696
+ "/trigger-inbox/api/v1/inboxes",
10697
+ requestBody,
10698
+ {
10699
+ authRequired: true,
10700
+ customErrorHandler: ({ status, data }) => {
10701
+ if (status === 409) {
10702
+ const detail = extractErrorDetail(data);
10703
+ return new ZapierConflictError(
10704
+ detail ?? `An inbox with key "${key2}" already exists with a different subscription.`,
10705
+ { statusCode: status, resourceType: "trigger_inbox" }
10706
+ );
10707
+ }
10708
+ return void 0;
10709
+ }
10710
+ }
10711
+ );
10712
+ return { data: TriggerInboxItemSchema.parse(rawResponse) };
10713
+ }
10714
+ })
10715
+ );
10716
+ var EnsureTriggerInboxDescription = "Get-or-create a trigger inbox by key. Idempotent on (user, account, key): returns the existing inbox if a matching subscription is registered, creates a new one otherwise. Throws ZapierConflictError if the key exists with a different subscription.";
10717
+ var EnsureTriggerInboxBaseSchema = zod.z.object({
10718
+ app: AppPropertySchema,
10719
+ action: ActionPropertySchema,
10720
+ connection: ConnectionPropertySchema.nullable().optional().describe(
10721
+ "Connection alias or connection ID. Optional for triggers that don't require auth."
10722
+ ),
10723
+ inputs: InputsPropertySchema.optional().describe(
10724
+ "Input parameters for the trigger subscription"
10725
+ ),
10726
+ notificationUrl: zod.z.string().url().optional().describe("Webhook URL to POST to when new messages arrive")
10727
+ });
10728
+ var EnsureTriggerInboxSchema = zod.z.object({
10729
+ key: TriggerInboxKeyPropertySchema.describe(
10730
+ "Inbox key; serves as the idempotency key. Required for ensureTriggerInbox \u2014 without one, the API mints a fresh inbox each call (use createTriggerInbox for that path)."
10731
+ )
10732
+ }).merge(EnsureTriggerInboxBaseSchema).describe(EnsureTriggerInboxDescription).meta({ aliases: { name: "key" } });
10733
+ var EnsureTriggerInboxSchemaDeprecated = zod.z.object({
10734
+ name: TriggerInboxNamePropertySchema.describe(
10735
+ "Inbox name; serves as the idempotency key. Required for ensureTriggerInbox \u2014 without one, the API mints a fresh inbox each call (use createTriggerInbox for that path)."
10736
+ )
10737
+ }).merge(EnsureTriggerInboxBaseSchema);
10738
+ var EnsureTriggerInboxInputSchema = zod.z.union([EnsureTriggerInboxSchema, EnsureTriggerInboxSchemaDeprecated]).describe(EnsureTriggerInboxDescription);
10739
+
10740
+ // src/plugins/triggers/ensureTriggerInbox/index.ts
10741
+ var ensureTriggerInboxPlugin = definePlugin(
10742
+ (sdk) => createPluginMethod(sdk, {
10743
+ ...triggersDefaults,
10744
+ name: "ensureTriggerInbox",
10745
+ type: "create",
10746
+ itemType: "TriggerInbox",
10747
+ inputSchema: EnsureTriggerInboxInputSchema,
10748
+ outputSchema: TriggerInboxItemSchema,
10749
+ formatter: triggerInboxItemFormatter,
10750
+ // actionKeyResolver and inputsResolver depend on actionType, which is
10751
+ // always "read" for triggers. Pin it as a constant resolver so it's
10752
+ // seeded into resolvedParams without polluting the user-facing schema.
10753
+ resolvers: {
10754
+ key: { type: "static", inputType: "text" },
10755
+ app: appKeyResolver,
10756
+ action: actionKeyResolver,
10757
+ connection: connectionIdResolver,
10758
+ inputs: inputsResolver,
10759
+ actionType: { type: "constant", value: "read" }
10760
+ },
10761
+ handler: async ({ sdk: sdk2, options }) => {
10762
+ const { api } = sdk2.context;
10763
+ const {
10764
+ app: appKey,
10765
+ action: actionKey,
10766
+ connection,
10767
+ inputs = {},
10768
+ notificationUrl
10769
+ } = options;
10770
+ const key2 = "key" in options ? options.key : options.name;
10771
+ const resolvedConnectionId = await resolveConnectionId({
10772
+ connection,
10773
+ resolveConnection: sdk2.context.resolveConnection
10774
+ });
10775
+ const selectedApi = await sdk2.context.getVersionedImplementationId(appKey);
10776
+ if (!selectedApi) {
10777
+ throw new ZapierConfigurationError(
10778
+ `No current_implementation_id found for app "${appKey}"`,
10779
+ { configType: "current_implementation_id" }
10780
+ );
10781
+ }
10782
+ const requestBody = {
10783
+ key: key2,
10784
+ subscription: {
10785
+ app_key: selectedApi,
10786
+ action_key: actionKey,
10787
+ inputs,
10788
+ connection_id: resolvedConnectionId ?? null
10789
+ }
10790
+ };
10791
+ if (notificationUrl !== void 0) {
10792
+ requestBody.notification_url = notificationUrl;
10793
+ }
10794
+ const rawResponse = await api.put(
10795
+ "/trigger-inbox/api/v1/inboxes",
10796
+ requestBody,
10797
+ {
10798
+ authRequired: true,
10799
+ customErrorHandler: ({ status, data }) => {
10800
+ if (status === 409) {
10801
+ const detail = extractErrorDetail(data);
10802
+ return new ZapierConflictError(
10803
+ detail ?? `An inbox with key "${key2}" already exists with a different subscription.`,
10804
+ { statusCode: status, resourceType: "trigger_inbox" }
10805
+ );
10806
+ }
10807
+ return void 0;
10808
+ }
10809
+ }
10810
+ );
10811
+ return { data: TriggerInboxItemSchema.parse(rawResponse) };
10812
+ }
10813
+ })
10814
+ );
10815
+ var ListTriggerInboxesSchema = zod.z.object({
10816
+ key: zod.z.string().min(1).optional().describe(
10817
+ "Filter by inbox key (exact match). Keys are unique per (user, account), so this returns at most one inbox."
10818
+ ),
10819
+ /** @deprecated Use `key` instead. */
10820
+ name: zod.z.string().min(1).optional().describe(
10821
+ "Filter by inbox name (exact match). Names are unique per (user, account), so this returns at most one inbox."
10822
+ ).meta({ deprecated: true }),
10823
+ status: TriggerInboxStatusSchema.optional().describe(
10824
+ "Filter by inbox status"
10825
+ ),
10826
+ pageSize: zod.z.number().int().min(1).optional().describe("Number of inboxes per page"),
10827
+ maxItems: zod.z.number().int().min(1).optional().describe("Maximum total items to return across all pages"),
10828
+ cursor: zod.z.string().optional().describe("Cursor (offset) to start from for pagination")
10829
+ }).describe("List all trigger inboxes for the authenticated user");
10830
+ var ListTriggerInboxesApiResponseSchema = zod.z.object({
10831
+ count: zod.z.number().int(),
10832
+ next: zod.z.string().nullable().optional(),
10833
+ previous: zod.z.string().nullable().optional(),
10834
+ results: zod.z.array(TriggerInboxItemSchema)
10835
+ });
10836
+
10837
+ // src/plugins/triggers/listTriggerInboxes/index.ts
10838
+ var listTriggerInboxesPlugin = definePlugin(
10839
+ (sdk) => createPaginatedPluginMethod(sdk, {
10840
+ ...triggersDefaults,
10841
+ ...zapierPagination,
10842
+ name: "listTriggerInboxes",
10843
+ type: "list",
10844
+ itemType: "TriggerInbox",
10845
+ inputSchema: ListTriggerInboxesSchema,
10846
+ outputSchema: TriggerInboxItemSchema,
10847
+ formatter: triggerInboxItemFormatter,
10848
+ defaultPageSize: DEFAULT_PAGE_SIZE,
10849
+ handler: async ({ sdk: sdk2, options }) => {
10850
+ const { api } = sdk2.context;
10851
+ const searchParams = {};
10852
+ if (options.pageSize !== void 0) {
10853
+ searchParams.limit = options.pageSize.toString();
10854
+ }
10855
+ if (options.cursor) {
10856
+ searchParams.offset = options.cursor;
10857
+ }
10858
+ if (options.status) {
10859
+ searchParams.status = options.status;
10860
+ }
10861
+ const keyFilter = options.key ?? options.name;
10862
+ if (keyFilter) {
10863
+ searchParams.key = keyFilter;
10864
+ }
10865
+ const rawResponse = await api.get("/trigger-inbox/api/v1/inboxes", {
10866
+ searchParams,
10867
+ authRequired: true
10868
+ });
10869
+ const response = ListTriggerInboxesApiResponseSchema.parse(rawResponse);
10870
+ return {
10871
+ data: response.results,
10872
+ next: response.next ?? null
10873
+ };
10874
+ }
10875
+ })
10876
+ );
10877
+ var GetTriggerInboxSchema = zod.z.object({
10878
+ inbox: TriggerInboxPropertySchema
10879
+ }).describe("Get details of a trigger inbox by ID");
10880
+
10881
+ // src/plugins/triggers/getTriggerInbox/index.ts
10882
+ var getTriggerInboxPlugin = definePlugin(
10883
+ (sdk) => createPluginMethod(sdk, {
10884
+ ...triggersDefaults,
10885
+ name: "getTriggerInbox",
10886
+ type: "item",
10887
+ itemType: "TriggerInbox",
10888
+ inputSchema: GetTriggerInboxSchema,
10889
+ outputSchema: TriggerInboxItemSchema,
10890
+ formatter: triggerInboxItemFormatter,
10891
+ resolvers: { inbox: triggerInboxResolver },
10892
+ handler: async ({ sdk: sdk2, options }) => {
10893
+ const { inbox } = options;
10894
+ const inboxId = await resolveTriggerInboxId({
10895
+ api: sdk2.context.api,
10896
+ inbox
10897
+ });
10898
+ const rawResponse = await sdk2.context.api.get(
10899
+ `/trigger-inbox/api/v1/inboxes/${encodeURIComponent(inboxId)}`,
10900
+ {
10901
+ authRequired: true,
10902
+ resource: { type: "trigger_inbox", id: inboxId }
10903
+ }
10904
+ );
10905
+ return { data: TriggerInboxItemSchema.parse(rawResponse) };
10906
+ }
10907
+ })
10908
+ );
10909
+ var UpdateTriggerInboxSchema = zod.z.object({
10910
+ inbox: TriggerInboxPropertySchema,
10911
+ notificationUrl: zod.z.string().url().nullable().optional().describe(
10912
+ "Webhook URL to POST to when new messages arrive. Pass null to clear."
10913
+ )
10914
+ }).describe("Update settings on an existing trigger inbox");
10915
+
10916
+ // src/plugins/triggers/updateTriggerInbox/index.ts
10917
+ var updateTriggerInboxPlugin = definePlugin(
10918
+ (sdk) => createPluginMethod(sdk, {
10919
+ ...triggersDefaults,
10920
+ name: "updateTriggerInbox",
10921
+ type: "update",
10922
+ itemType: "TriggerInbox",
10923
+ inputSchema: UpdateTriggerInboxSchema,
10924
+ outputSchema: TriggerInboxItemSchema,
10925
+ formatter: triggerInboxItemFormatter,
10926
+ resolvers: { inbox: triggerInboxResolver },
10927
+ handler: async ({ sdk: sdk2, options }) => {
10928
+ const { inbox, notificationUrl } = options;
10929
+ const inboxId = await resolveTriggerInboxId({
10930
+ api: sdk2.context.api,
10931
+ inbox
10932
+ });
10933
+ const requestBody = {};
10934
+ if (notificationUrl !== void 0) {
10935
+ requestBody.notification_url = notificationUrl;
10936
+ }
10937
+ const rawResponse = await sdk2.context.api.patch(
10938
+ `/trigger-inbox/api/v1/inboxes/${encodeURIComponent(inboxId)}`,
10939
+ requestBody,
10940
+ {
10941
+ authRequired: true,
10942
+ resource: { type: "trigger_inbox", id: inboxId }
10943
+ }
10944
+ );
10945
+ return { data: TriggerInboxItemSchema.parse(rawResponse) };
10946
+ }
10947
+ })
10948
+ );
10949
+ var DeleteTriggerInboxSchema = zod.z.object({
10950
+ inbox: TriggerInboxPropertySchema
10951
+ }).describe("Mark a trigger inbox for deletion");
10952
+
10953
+ // src/plugins/triggers/deleteTriggerInbox/index.ts
10954
+ var deleteTriggerInboxPlugin = definePlugin(
10955
+ (sdk) => createPluginMethod(sdk, {
10956
+ ...triggersDefaults,
10957
+ name: "deleteTriggerInbox",
10958
+ type: "delete",
10959
+ itemType: "TriggerInbox",
10960
+ inputSchema: DeleteTriggerInboxSchema,
10961
+ outputSchema: TriggerInboxItemSchema,
10962
+ formatter: triggerInboxItemFormatter,
10963
+ resolvers: { inbox: triggerInboxResolver },
10964
+ confirm: "delete",
10965
+ handler: async ({ sdk: sdk2, options }) => {
10966
+ const { inbox } = options;
10967
+ const inboxId = await resolveTriggerInboxId({
10968
+ api: sdk2.context.api,
10969
+ inbox
10970
+ });
10971
+ const rawResponse = await sdk2.context.api.delete(
10972
+ `/trigger-inbox/api/v1/inboxes/${encodeURIComponent(inboxId)}`,
10973
+ void 0,
10974
+ {
10975
+ authRequired: true,
10976
+ resource: { type: "trigger_inbox", id: inboxId }
10977
+ }
10978
+ );
10979
+ return { data: TriggerInboxItemSchema.parse(rawResponse) };
10980
+ }
10981
+ })
10982
+ );
10983
+ var PauseTriggerInboxSchema = zod.z.object({
10984
+ inbox: TriggerInboxPropertySchema
10985
+ }).describe("Pause a trigger inbox; events stop being collected");
10986
+
10987
+ // src/plugins/triggers/pauseTriggerInbox/index.ts
10988
+ var pauseTriggerInboxPlugin = definePlugin(
10989
+ (sdk) => createPluginMethod(sdk, {
10990
+ ...triggersDefaults,
10991
+ name: "pauseTriggerInbox",
10992
+ type: "update",
10993
+ itemType: "TriggerInbox",
10994
+ inputSchema: PauseTriggerInboxSchema,
10995
+ outputSchema: TriggerInboxItemSchema,
10996
+ formatter: triggerInboxItemFormatter,
10997
+ resolvers: { inbox: triggerInboxResolver },
10998
+ handler: async ({ sdk: sdk2, options }) => {
10999
+ const { inbox } = options;
11000
+ const inboxId = await resolveTriggerInboxId({
11001
+ api: sdk2.context.api,
11002
+ inbox
11003
+ });
11004
+ const rawResponse = await sdk2.context.api.post(
11005
+ `/trigger-inbox/api/v1/inboxes/${encodeURIComponent(inboxId)}/pause`,
11006
+ void 0,
11007
+ {
11008
+ authRequired: true,
11009
+ resource: { type: "trigger_inbox", id: inboxId }
11010
+ }
11011
+ );
11012
+ return { data: TriggerInboxItemSchema.parse(rawResponse) };
11013
+ }
11014
+ })
11015
+ );
11016
+ var ResumeTriggerInboxSchema = zod.z.object({
11017
+ inbox: TriggerInboxPropertySchema
11018
+ }).describe("Resume a paused trigger inbox; events resume being collected");
11019
+
11020
+ // src/plugins/triggers/resumeTriggerInbox/index.ts
11021
+ var resumeTriggerInboxPlugin = definePlugin(
11022
+ (sdk) => createPluginMethod(sdk, {
11023
+ ...triggersDefaults,
11024
+ name: "resumeTriggerInbox",
11025
+ type: "update",
11026
+ itemType: "TriggerInbox",
11027
+ inputSchema: ResumeTriggerInboxSchema,
11028
+ outputSchema: TriggerInboxItemSchema,
11029
+ formatter: triggerInboxItemFormatter,
11030
+ resolvers: { inbox: triggerInboxResolver },
11031
+ handler: async ({ sdk: sdk2, options }) => {
11032
+ const { inbox } = options;
11033
+ const inboxId = await resolveTriggerInboxId({
11034
+ api: sdk2.context.api,
11035
+ inbox
11036
+ });
11037
+ const rawResponse = await sdk2.context.api.post(
11038
+ `/trigger-inbox/api/v1/inboxes/${encodeURIComponent(inboxId)}/resume`,
11039
+ void 0,
11040
+ {
11041
+ authRequired: true,
11042
+ resource: { type: "trigger_inbox", id: inboxId }
11043
+ }
11044
+ );
11045
+ return { data: TriggerInboxItemSchema.parse(rawResponse) };
11046
+ }
11047
+ })
11048
+ );
11049
+ var TriggerMessageStatusSchema = zod.z.union([zod.z.enum(["available", "leased", "acked", "quarantined"]), zod.z.string()]).describe("Message lifecycle status");
11050
+ var TriggerMessageAttributesSchema = zod.z.object({
11051
+ lease_count: zod.z.number().int(),
11052
+ error_message: zod.z.string().nullable(),
11053
+ possible_duplicate_data: zod.z.boolean()
11054
+ });
11055
+ var TriggerMessageItemSchema = zod.z.object({
11056
+ id: zod.z.string(),
11057
+ created_at: zod.z.string(),
11058
+ status: TriggerMessageStatusSchema,
11059
+ message_attributes: TriggerMessageAttributesSchema
11060
+ });
11061
+ var LeasedTriggerMessageItemSchema = TriggerMessageItemSchema.extend({
11062
+ payload: zod.z.record(zod.z.string(), zod.z.unknown())
11063
+ });
11064
+
11065
+ // src/plugins/triggers/listTriggerInboxMessages/schemas.ts
11066
+ var ListTriggerInboxMessagesSchema = zod.z.object({
11067
+ inbox: TriggerInboxPropertySchema,
11068
+ pageSize: zod.z.number().int().min(1).optional().describe("Number of messages per page"),
11069
+ maxItems: zod.z.number().int().min(1).optional().describe("Maximum total items to return across all pages"),
11070
+ cursor: zod.z.string().optional().describe("Pagination cursor")
11071
+ }).describe("List messages in a trigger inbox (no payload, status-only)");
11072
+ var ListTriggerInboxMessagesApiResponseSchema = zod.z.object({
11073
+ next: zod.z.string().nullable().optional(),
11074
+ previous: zod.z.string().nullable().optional(),
11075
+ results: zod.z.array(TriggerMessageItemSchema)
11076
+ });
11077
+
11078
+ // src/formatters/triggerMessage.ts
11079
+ function buildBaseDetails(item) {
11080
+ const details = [
11081
+ { text: `Status: ${item.status}`, style: "dim" },
11082
+ {
11083
+ text: `Lease count: ${item.message_attributes.lease_count}`,
11084
+ style: "dim"
11085
+ }
11086
+ ];
11087
+ if (item.message_attributes.error_message) {
11088
+ details.push({
11089
+ text: `Error: ${item.message_attributes.error_message}`,
11090
+ style: "warning"
11091
+ });
11092
+ }
11093
+ if (item.message_attributes.possible_duplicate_data) {
11094
+ details.push({ text: "Possible duplicate data", style: "warning" });
11095
+ }
11096
+ return details;
11097
+ }
11098
+ var triggerMessageItemFormatter = {
11099
+ format: (item) => ({
11100
+ title: `Message ${item.id}`,
11101
+ id: item.id,
11102
+ details: buildBaseDetails(item)
11103
+ })
11104
+ };
11105
+
11106
+ // src/plugins/triggers/listTriggerInboxMessages/index.ts
11107
+ var listTriggerInboxMessagesPlugin = definePlugin(
11108
+ (sdk) => createPaginatedPluginMethod(sdk, {
11109
+ ...triggersDefaults,
11110
+ ...zapierPagination,
11111
+ name: "listTriggerInboxMessages",
11112
+ type: "list",
11113
+ itemType: "TriggerMessage",
11114
+ inputSchema: ListTriggerInboxMessagesSchema,
11115
+ outputSchema: TriggerMessageItemSchema,
11116
+ formatter: triggerMessageItemFormatter,
11117
+ defaultPageSize: DEFAULT_PAGE_SIZE,
11118
+ resolvers: { inbox: triggerInboxResolver },
11119
+ handler: async ({ sdk: sdk2, options }) => {
11120
+ const { inbox, cursor, pageSize } = options;
11121
+ const inboxId = await resolveTriggerInboxId({
11122
+ api: sdk2.context.api,
11123
+ inbox
11124
+ });
11125
+ const searchParams = {};
11126
+ if (pageSize !== void 0) {
11127
+ searchParams.limit = pageSize.toString();
11128
+ }
11129
+ if (cursor) {
11130
+ searchParams.cursor = cursor;
11131
+ }
11132
+ const rawResponse = await sdk2.context.api.get(
11133
+ `/trigger-inbox/api/v1/inboxes/${encodeURIComponent(inboxId)}/messages`,
11134
+ { searchParams, authRequired: true }
11135
+ );
11136
+ const response = ListTriggerInboxMessagesApiResponseSchema.parse(rawResponse);
11137
+ return {
11138
+ data: response.results,
11139
+ next: response.next ?? null
11140
+ };
11141
+ }
11142
+ })
11143
+ );
11144
+ var LeaseTriggerInboxMessagesSchema = zod.z.object({
11145
+ inbox: TriggerInboxPropertySchema,
11146
+ leaseLimit: LeaseLimitPropertySchema.optional(),
11147
+ leaseSeconds: LeaseSecondsPropertySchema.optional(),
11148
+ signal: zod.z.custom((v) => v instanceof AbortSignal).optional().describe(
11149
+ "Abort signal forwarded to the lease HTTP request. Aborting causes the in-flight request to reject with AbortError."
11150
+ )
11151
+ }).describe(
11152
+ "Lease up to N messages from a trigger inbox. Returns messages plus a lease ID; ack within the lease window to remove from the inbox."
11153
+ );
11154
+ var InboxAttributesSchema = zod.z.object({
11155
+ status: TriggerInboxStatusSchema,
11156
+ paused_reason: TriggerInboxPausedReasonSchema.nullable()
11157
+ });
11158
+ var LeaseTriggerInboxMessagesItemSchema = zod.z.object({
11159
+ lease_id: zod.z.string().nullable(),
11160
+ leased_until: zod.z.string().nullable(),
11161
+ results: zod.z.array(LeasedTriggerMessageItemSchema),
11162
+ inbox_attributes: InboxAttributesSchema
11163
+ });
11164
+
11165
+ // src/plugins/triggers/leaseTriggerInboxMessages/index.ts
11166
+ function parseLeaseConflict(data) {
11167
+ if (typeof data !== "object" || data === null) return {};
11168
+ const detail = data.detail;
11169
+ const inboxAttributes = data.inbox_attributes;
11170
+ let pausedReason;
11171
+ if (typeof inboxAttributes === "object" && inboxAttributes !== null) {
11172
+ const pr = inboxAttributes.paused_reason;
11173
+ if (typeof pr === "string" && pr.length > 0) pausedReason = pr;
11174
+ }
11175
+ return {
11176
+ detail: typeof detail === "string" ? detail : void 0,
11177
+ pausedReason
11178
+ };
11179
+ }
11180
+ var leaseTriggerInboxMessagesPlugin = definePlugin(
11181
+ (sdk) => createPluginMethod(sdk, {
11182
+ ...triggersDefaults,
11183
+ name: "leaseTriggerInboxMessages",
11184
+ type: "create",
11185
+ itemType: "TriggerInboxLease",
11186
+ inputSchema: LeaseTriggerInboxMessagesSchema,
11187
+ outputSchema: LeaseTriggerInboxMessagesItemSchema,
11188
+ resolvers: {
11189
+ inbox: triggerInboxResolver,
11190
+ leaseLimit: { type: "static", inputType: "text" },
11191
+ leaseSeconds: { type: "static", inputType: "text" }
11192
+ },
11193
+ handler: async ({ sdk: sdk2, options }) => {
11194
+ const { inbox, leaseLimit, leaseSeconds, signal } = options;
11195
+ const inboxId = await resolveTriggerInboxId({
11196
+ api: sdk2.context.api,
11197
+ inbox
11198
+ });
11199
+ const requestBody = {};
11200
+ if (leaseLimit !== void 0) {
11201
+ requestBody.lease_limit = leaseLimit;
11202
+ }
11203
+ if (leaseSeconds !== void 0) {
11204
+ requestBody.lease_seconds = leaseSeconds;
11205
+ }
11206
+ const rawResponse = await sdk2.context.api.post(
11207
+ `/trigger-inbox/api/v1/inboxes/${encodeURIComponent(inboxId)}/messages/lease`,
11208
+ requestBody,
11209
+ {
11210
+ authRequired: true,
11211
+ signal,
11212
+ customErrorHandler: ({ status, data }) => {
11213
+ if (status !== 409) return void 0;
11214
+ const { detail, pausedReason } = parseLeaseConflict(data);
11215
+ const baseMessage = detail ?? "Inbox is paused and fully drained";
11216
+ const message = pausedReason ? `${baseMessage} (paused_reason: ${pausedReason})` : baseMessage;
11217
+ return new ZapierConflictError(message, {
11218
+ statusCode: status,
11219
+ resourceType: "trigger_inbox"
11220
+ });
11221
+ }
11222
+ }
11223
+ );
11224
+ return { data: LeaseTriggerInboxMessagesItemSchema.parse(rawResponse) };
11225
+ }
11226
+ })
11227
+ );
11228
+ var AckTriggerInboxMessagesSchema = zod.z.object({
11229
+ inbox: TriggerInboxPropertySchema,
11230
+ lease: LeasePropertySchema,
11231
+ messages: zod.z.array(zod.z.string().min(1)).optional().describe(
11232
+ "Specific message IDs to ack. Omit to ack every message in the lease."
11233
+ )
11234
+ }).describe(
11235
+ "Acknowledge messages from a lease. Acked messages are removed from the inbox; unacked ones return to the available pool when the lease expires."
11236
+ );
11237
+ var AckTriggerInboxMessagesItemSchema = zod.z.object({
11238
+ acked_id: zod.z.string().nullable(),
11239
+ results: zod.z.array(TriggerMessageItemSchema)
11240
+ });
11241
+
11242
+ // src/plugins/triggers/ackTriggerInboxMessages/index.ts
11243
+ var ackTriggerInboxMessagesPlugin = definePlugin(
11244
+ (sdk) => createPluginMethod(sdk, {
11245
+ ...triggersDefaults,
11246
+ name: "ackTriggerInboxMessages",
11247
+ type: "create",
11248
+ itemType: "TriggerInboxAck",
11249
+ inputSchema: AckTriggerInboxMessagesSchema,
11250
+ outputSchema: AckTriggerInboxMessagesItemSchema,
11251
+ resolvers: {
11252
+ inbox: triggerInboxResolver,
11253
+ // No way to look up a lease — leases are short-lived, only the
11254
+ // most recent leaseTriggerInboxMessages caller knows the ID.
11255
+ // Static resolver prompts for free-text input.
11256
+ lease: { type: "static", inputType: "text" },
11257
+ messages: triggerMessagesResolver
11258
+ },
11259
+ handler: async ({ sdk: sdk2, options }) => {
11260
+ const { inbox, lease, messages } = options;
11261
+ const inboxId = await resolveTriggerInboxId({
11262
+ api: sdk2.context.api,
11263
+ inbox
11264
+ });
11265
+ const requestBody = {
11266
+ lease_id: lease
11267
+ };
11268
+ if (messages !== void 0) {
11269
+ requestBody.message_ids = messages;
11270
+ }
11271
+ const rawResponse = await sdk2.context.api.post(
11272
+ `/trigger-inbox/api/v1/inboxes/${encodeURIComponent(inboxId)}/messages/ack`,
11273
+ requestBody,
11274
+ { authRequired: true }
11275
+ );
11276
+ return { data: AckTriggerInboxMessagesItemSchema.parse(rawResponse) };
11277
+ }
11278
+ })
11279
+ );
11280
+ var ReleaseTriggerInboxMessagesSchema = zod.z.object({
11281
+ inbox: TriggerInboxPropertySchema,
11282
+ lease: LeasePropertySchema,
11283
+ messages: zod.z.array(zod.z.string().min(1)).optional().describe(
11284
+ "Specific message IDs to release. Omit to release every message in the lease."
11285
+ )
11286
+ }).describe(
11287
+ "Release messages from a lease back to the inbox without acknowledging them. Released messages become immediately available for re-leasing. The lease attempt still counts against the per-message lease limit; releasing does not refund the attempt."
11288
+ );
11289
+ var ReleaseTriggerInboxMessagesItemSchema = zod.z.object({
11290
+ released_id: zod.z.string().nullable(),
11291
+ results: zod.z.array(TriggerMessageItemSchema)
11292
+ });
11293
+
11294
+ // src/plugins/triggers/releaseTriggerInboxMessages/index.ts
11295
+ var releaseTriggerInboxMessagesPlugin = definePlugin(
11296
+ (sdk) => createPluginMethod(sdk, {
11297
+ ...triggersDefaults,
11298
+ name: "releaseTriggerInboxMessages",
11299
+ type: "create",
11300
+ itemType: "TriggerInboxRelease",
11301
+ inputSchema: ReleaseTriggerInboxMessagesSchema,
11302
+ outputSchema: ReleaseTriggerInboxMessagesItemSchema,
11303
+ resolvers: {
11304
+ inbox: triggerInboxResolver,
11305
+ // No way to look up a lease — leases are short-lived, only the
11306
+ // most recent leaseTriggerInboxMessages caller knows the ID.
11307
+ // Static resolver prompts for free-text input.
11308
+ lease: { type: "static", inputType: "text" },
11309
+ messages: triggerMessagesResolver
11310
+ },
11311
+ handler: async ({ sdk: sdk2, options }) => {
11312
+ const { inbox, lease, messages } = options;
11313
+ const inboxId = await resolveTriggerInboxId({
11314
+ api: sdk2.context.api,
11315
+ inbox
11316
+ });
11317
+ const requestBody = {
11318
+ lease_id: lease
11319
+ };
11320
+ if (messages !== void 0) {
11321
+ requestBody.message_ids = messages;
11322
+ }
11323
+ const rawResponse = await sdk2.context.api.post(
11324
+ `/trigger-inbox/api/v1/inboxes/${encodeURIComponent(inboxId)}/messages/release`,
11325
+ requestBody,
11326
+ { authRequired: true }
11327
+ );
11328
+ return {
11329
+ data: ReleaseTriggerInboxMessagesItemSchema.parse(rawResponse)
11330
+ };
11331
+ }
11332
+ })
11333
+ );
11334
+
11335
+ // src/plugins/triggers/drainTriggerInbox/pipeline.ts
11336
+ function createBatchTracker() {
11337
+ const batches = /* @__PURE__ */ new Map();
11338
+ return {
11339
+ addBatch(id, total) {
11340
+ batches.set(id, { total, inFlight: 0, completed: 0 });
11341
+ },
11342
+ markInFlight(id) {
11343
+ const e = batches.get(id);
11344
+ if (e) e.inFlight++;
11345
+ },
11346
+ /** Decrement inFlight and increment completed. Paired with markInFlight. */
11347
+ markCompleted(id) {
11348
+ const e = batches.get(id);
11349
+ if (!e) return;
11350
+ e.inFlight--;
11351
+ e.completed++;
11352
+ },
11353
+ /** Drop the batch once all items completed; tracker stays small over long drains. */
11354
+ finalizeIfDone(id) {
11355
+ const e = batches.get(id);
11356
+ if (e && e.completed === e.total) batches.delete(id);
11357
+ },
11358
+ inFlightTotal() {
11359
+ let n = 0;
11360
+ for (const e of batches.values()) n += e.inFlight;
11361
+ return n;
11362
+ },
11363
+ /** Items leased but not yet completed (queued + in-flight). */
11364
+ pipelineSize() {
11365
+ let n = 0;
11366
+ for (const e of batches.values()) n += e.total - e.completed;
11367
+ return n;
11368
+ }
11369
+ };
11370
+ }
11371
+ function createWaiter() {
11372
+ const make = () => {
11373
+ let signal;
11374
+ const promise = new Promise((r) => {
11375
+ signal = r;
11376
+ });
11377
+ return { promise, signal };
11378
+ };
11379
+ let current = make();
11380
+ return {
11381
+ wait: () => current.promise,
11382
+ notifyAll: () => {
11383
+ const prev = current;
11384
+ current = make();
11385
+ prev.signal();
11386
+ }
11387
+ };
11388
+ }
11389
+ function addToMap(m, key2, value) {
11390
+ const existing = m.get(key2) ?? [];
11391
+ m.set(key2, [...existing, value]);
11392
+ }
11393
+ async function runBatchedDrainPipeline(options) {
11394
+ const {
11395
+ concurrency,
11396
+ maxItems,
11397
+ leaseSize,
11398
+ fetchBatch,
11399
+ processItem,
11400
+ ackItem,
11401
+ releaseItems
11402
+ } = options;
11403
+ const tracker = createBatchTracker();
11404
+ const waiter = createWaiter();
11405
+ const accumulated = [];
11406
+ const pendingReleases = /* @__PURE__ */ new Map();
11407
+ const queue = [];
11408
+ let totalProcessed = 0;
11409
+ let aborted = false;
11410
+ let exhausted = false;
11411
+ let fetchInProgress = false;
11412
+ let fetchError = void 0;
11413
+ async function tryFetch() {
11414
+ if (fetchInProgress || exhausted || aborted) return;
11415
+ const remainingCap = maxItems !== void 0 ? maxItems - totalProcessed - tracker.pipelineSize() : Number.POSITIVE_INFINITY;
11416
+ if (remainingCap <= 0) return;
11417
+ const requestedSize = Math.min(remainingCap, leaseSize);
11418
+ fetchInProgress = true;
11419
+ try {
11420
+ const result = await fetchBatch(requestedSize);
11421
+ if (result === "exhausted") {
11422
+ exhausted = true;
11423
+ return;
11424
+ }
11425
+ tracker.addBatch(result.id, result.items.length);
11426
+ for (const item of result.items) {
11427
+ queue.push({ item, batchId: result.id });
11428
+ }
11429
+ } catch (err) {
11430
+ fetchError = err;
11431
+ exhausted = true;
11432
+ } finally {
11433
+ fetchInProgress = false;
11434
+ waiter.notifyAll();
11435
+ }
11436
+ }
11437
+ async function processQueueEntry(entry) {
11438
+ tracker.markInFlight(entry.batchId);
11439
+ try {
11440
+ const result = await processItem(entry.item);
11441
+ accumulated.push(result.value);
11442
+ totalProcessed++;
11443
+ if (result.action === "release") {
11444
+ addToMap(pendingReleases, entry.batchId, entry.item.id);
11445
+ }
11446
+ if (result.abort) aborted = true;
11447
+ if (result.action === "ack") {
11448
+ await ackItem(entry.batchId, entry.item.id);
11449
+ }
11450
+ } finally {
11451
+ tracker.markCompleted(entry.batchId);
11452
+ tracker.finalizeIfDone(entry.batchId);
11453
+ waiter.notifyAll();
11454
+ }
11455
+ }
11456
+ async function worker() {
11457
+ while (true) {
11458
+ if (aborted) return;
11459
+ if (maxItems !== void 0 && totalProcessed >= maxItems) return;
11460
+ const entry = queue.shift();
11461
+ if (entry !== void 0) {
11462
+ if (tracker.pipelineSize() < concurrency && !fetchInProgress && !exhausted) {
11463
+ void tryFetch();
11464
+ }
11465
+ await processQueueEntry(entry);
11466
+ continue;
11467
+ }
11468
+ if (!exhausted && !fetchInProgress) void tryFetch();
11469
+ if (queue.length === 0 && !fetchInProgress && (exhausted || aborted) && tracker.inFlightTotal() === 0) {
11470
+ return;
11471
+ }
11472
+ await waiter.wait();
11473
+ }
11474
+ }
11475
+ await tryFetch();
11476
+ if (fetchError !== void 0) throw fetchError;
11477
+ let cleanupError = void 0;
11478
+ try {
11479
+ if (!exhausted || queue.length > 0) {
11480
+ let firstWorkerError = void 0;
11481
+ const workers = Array.from(
11482
+ { length: concurrency },
11483
+ () => worker().catch((err) => {
11484
+ if (firstWorkerError === void 0) firstWorkerError = err;
11485
+ })
11486
+ );
11487
+ await Promise.all(workers);
11488
+ if (firstWorkerError !== void 0) throw firstWorkerError;
11489
+ }
11490
+ if (fetchError !== void 0) throw fetchError;
11491
+ } finally {
11492
+ while (queue.length > 0) {
11493
+ const entry = queue.shift();
11494
+ addToMap(pendingReleases, entry.batchId, entry.item.id);
11495
+ }
11496
+ for (const [batchId, itemIds] of pendingReleases) {
11497
+ try {
11498
+ await releaseItems(batchId, itemIds);
11499
+ } catch (err) {
11500
+ cleanupError ?? (cleanupError = err);
11501
+ }
11502
+ }
11503
+ }
11504
+ if (cleanupError !== void 0) throw cleanupError;
11505
+ return accumulated;
11506
+ }
11507
+
11508
+ // src/plugins/triggers/drainTriggerInbox/index.ts
11509
+ var nonRetryableDrainErrors = /* @__PURE__ */ new WeakSet();
11510
+ function markNonRetryableDrainError(err) {
11511
+ if (typeof err === "object" && err !== null) {
11512
+ nonRetryableDrainErrors.add(err);
11513
+ }
11514
+ return err;
11515
+ }
11516
+ function isNonRetryableDrainError(err) {
11517
+ return typeof err === "object" && err !== null && nonRetryableDrainErrors.has(err);
11518
+ }
11519
+ function isLeaseExpiredError(err) {
11520
+ if (!(err instanceof ZapierValidationError)) return false;
11521
+ return err.errors?.some((e) => e.code === "lease_expired") ?? false;
11522
+ }
11523
+ async function runDrainPass(options) {
11524
+ const {
11525
+ sdk,
11526
+ inboxId,
11527
+ onMessage,
11528
+ concurrency,
11529
+ leaseLimit,
11530
+ leaseSeconds,
11531
+ maxMessages,
11532
+ releaseOnError,
11533
+ continueOnError,
11534
+ onError,
11535
+ signal
11536
+ } = options;
11537
+ let firstFetch = options.firstFetch;
11538
+ let abortedFromCallback = false;
11539
+ let handlerErrorCaptured = false;
11540
+ let firstHandlerError = void 0;
11541
+ const outcomes = await runBatchedDrainPipeline({
11542
+ concurrency,
11543
+ maxItems: maxMessages,
11544
+ leaseSize: leaseLimit,
11545
+ fetchBatch: async (requestedSize) => {
11546
+ if (signal?.aborted) return "exhausted";
11547
+ let lease;
11548
+ try {
11549
+ ({ data: lease } = await sdk.leaseTriggerInboxMessages({
11550
+ inbox: inboxId,
11551
+ leaseLimit: requestedSize,
11552
+ leaseSeconds,
11553
+ signal
11554
+ }));
11555
+ } catch (err) {
11556
+ if (signal?.aborted && isAbortError(err)) return "exhausted";
11557
+ throw err;
11558
+ }
11559
+ if (lease.results.length === 0) {
11560
+ if (firstFetch && lease.inbox_attributes.status === "initialization_failure") {
11561
+ throw markNonRetryableDrainError(
11562
+ new ZapierApiError(
11563
+ `Trigger inbox ${inboxId} is in initialization_failure state \u2014 inspect via getTriggerInbox.`
11564
+ )
11565
+ );
11566
+ }
11567
+ firstFetch = false;
11568
+ return "exhausted";
11569
+ }
11570
+ firstFetch = false;
11571
+ if (!lease.lease_id) return "exhausted";
11572
+ return { id: lease.lease_id, items: lease.results };
11573
+ },
11574
+ processItem: async (message) => {
11575
+ if (signal?.aborted) {
11576
+ return {
11577
+ value: message,
11578
+ action: "release",
11579
+ abort: true
11580
+ };
11581
+ }
11582
+ try {
11583
+ await onMessage(message);
11584
+ return { value: message, action: "ack" };
11585
+ } catch (err) {
11586
+ let action = "ignore";
11587
+ let abort = false;
11588
+ if (err instanceof ZapierAbortDrainSignal) {
11589
+ abort = true;
11590
+ abortedFromCallback = true;
11591
+ if (releaseOnError) action = "release";
11592
+ } else if (err instanceof ZapierReleaseTriggerMessageSignal) {
11593
+ action = "release";
11594
+ } else if (releaseOnError) {
11595
+ action = "release";
11596
+ }
11597
+ if (onError && !(err instanceof ZapierSignal)) {
11598
+ try {
11599
+ await onError(err, message);
11600
+ } catch {
11601
+ }
11602
+ }
11603
+ if (!continueOnError && !(err instanceof ZapierSignal)) {
11604
+ if (!handlerErrorCaptured) {
11605
+ firstHandlerError = err;
11606
+ handlerErrorCaptured = true;
11607
+ }
11608
+ abort = true;
11609
+ }
11610
+ return { value: message, action, abort };
11611
+ }
11612
+ },
11613
+ ackItem: async (leaseId, messageId) => {
11614
+ try {
11615
+ await sdk.ackTriggerInboxMessages({
11616
+ inbox: inboxId,
11617
+ lease: leaseId,
11618
+ messages: [messageId]
11619
+ });
11620
+ } catch (err) {
11621
+ if (!isLeaseExpiredError(err)) throw err;
11622
+ }
11623
+ },
11624
+ releaseItems: async (leaseId, messageIds) => {
11625
+ try {
11626
+ await sdk.releaseTriggerInboxMessages({
11627
+ inbox: inboxId,
11628
+ lease: leaseId,
11629
+ messages: messageIds
11630
+ });
11631
+ } catch (err) {
11632
+ if (!isLeaseExpiredError(err)) throw err;
11633
+ }
11634
+ }
11635
+ });
11636
+ if (handlerErrorCaptured) {
11637
+ throw markNonRetryableDrainError(firstHandlerError);
11638
+ }
11639
+ return { abortedFromCallback, processed: outcomes.length };
11640
+ }
11641
+ function requireOnMessage(onMessage) {
11642
+ if (typeof onMessage !== "function") {
11643
+ throw new ZapierValidationError("onMessage is required.");
11644
+ }
11645
+ return onMessage;
11646
+ }
11647
+ function resolveConcurrencyAndLease(options) {
11648
+ const concurrency = options.concurrency ?? options.leaseLimit ?? 1;
11649
+ const leaseLimit = options.leaseLimit ?? concurrency;
11650
+ return { concurrency, leaseLimit };
11651
+ }
11652
+ var drainTriggerInboxPlugin = definePlugin(
11653
+ (sdk) => {
11654
+ async function drainTriggerInbox(options) {
11655
+ const onMessage = requireOnMessage(options.onMessage);
11656
+ const { concurrency, leaseLimit } = resolveConcurrencyAndLease(options);
11657
+ const inboxId = await resolveTriggerInboxId({
11658
+ api: sdk.context.api,
11659
+ inbox: options.inbox
11660
+ });
11661
+ await runDrainPass({
11662
+ sdk,
11663
+ inboxId,
11664
+ onMessage,
11665
+ concurrency,
11666
+ leaseLimit,
11667
+ leaseSeconds: options.leaseSeconds,
11668
+ maxMessages: options.maxMessages,
11669
+ releaseOnError: options.releaseOnError ?? false,
11670
+ continueOnError: options.continueOnError ?? false,
11671
+ onError: options.onError,
11672
+ signal: options.signal,
11673
+ firstFetch: true
11674
+ });
11675
+ }
11676
+ return {
11677
+ drainTriggerInbox,
11678
+ context: {
11679
+ meta: {
11680
+ drainTriggerInbox: {
11681
+ ...triggersDefaults,
11682
+ type: "create",
11683
+ description: "Drain an existing trigger inbox: lease currently-available messages, process each via onMessage, return when the inbox is empty, maxMessages is reached, or the abort signal fires.",
11684
+ itemType: "void",
11685
+ // The doc generator's default for type="create" + itemType
11686
+ // appends "Item" (e.g. "RecordItem"), which would render
11687
+ // "voidItem" here. drainTriggerInbox returns Promise<void>,
11688
+ // so we override.
11689
+ returnType: "void",
11690
+ inputSchema: DrainTriggerInboxSchema,
11691
+ resolvers: {
11692
+ inbox: triggerInboxResolver
11693
+ },
11694
+ // Returns Promise<void>; the CLI ships a hand-written
11695
+ // drain-trigger-inbox plugin that adds presentation flags
11696
+ // (interactive, --json, etc.) around this command.
11697
+ packages: ["sdk"]
11698
+ }
11699
+ }
11700
+ }
11701
+ };
11702
+ }
11703
+ );
11704
+
11705
+ // src/plugins/triggers/watchTriggerInbox/sse.ts
11706
+ async function* readInboxEvents({
11707
+ api,
11708
+ inboxId,
11709
+ signal,
11710
+ onOpen
11711
+ }) {
11712
+ for await (const message of api.fetchJsonStream(
11713
+ `/trigger-inbox/api/v1/inboxes/${encodeURIComponent(inboxId)}/events`,
11714
+ { method: "GET", signal, authRequired: true, onOpen }
11715
+ )) {
11716
+ if (!message.parsed) continue;
11717
+ const parsed = message.data;
11718
+ if (typeof parsed === "object" && parsed !== null && typeof parsed.inbox_id === "string" && // Only wake on a frame for this inbox. Case-insensitive: the endpoint
11719
+ // echoes the canonical lowercase UUID, but resolveTriggerInboxId passes
11720
+ // a UUID-shaped `inbox` through unchanged, so its casing may differ.
11721
+ parsed.inbox_id.toLowerCase() === inboxId.toLowerCase()) {
11722
+ yield parsed;
11723
+ }
11724
+ }
11725
+ }
11726
+
11727
+ // src/plugins/triggers/watchTriggerInbox/index.ts
11728
+ var SSE_RECONNECT_BACKOFF_MS = [500, 1e3, 2e3, 5e3];
11729
+ var DEFAULT_SAFETY_DRAIN_INTERVAL_MS = 3e5;
11730
+ var SSE_HEALTHY_CONNECTION_MS = 5e3;
11731
+ var ERROR_BACKOFF_CAP = 4;
11732
+ function createDrainLatch() {
11733
+ let pending = false;
11734
+ const make = () => {
11735
+ let resolve2;
11736
+ const promise = new Promise((r) => {
11737
+ resolve2 = r;
11738
+ });
11739
+ return { promise, resolve: resolve2 };
11740
+ };
11741
+ let current = make();
11742
+ return {
11743
+ request() {
11744
+ pending = true;
11745
+ const prev = current;
11746
+ current = make();
11747
+ prev.resolve();
11748
+ },
11749
+ async waitForRequest() {
11750
+ if (pending) {
11751
+ pending = false;
11752
+ return;
11753
+ }
11754
+ await current.promise;
11755
+ pending = false;
11756
+ }
11757
+ };
11758
+ }
11759
+ async function drainRunner({
11760
+ drainOptions,
11761
+ drainRequest,
11762
+ signal,
11763
+ inboxId,
11764
+ debug
11765
+ }) {
11766
+ let firstFetch = true;
11767
+ let consecutiveErrors = 0;
11768
+ let errorAttempts = 0;
11769
+ let drainDegraded = false;
11770
+ while (!signal.aborted) {
11771
+ await drainRequest.waitForRequest();
11772
+ if (signal.aborted) return { kind: "aborted" };
11773
+ let abortedFromCallback = false;
11774
+ try {
11775
+ ({ abortedFromCallback } = await runDrainPass({
11776
+ ...drainOptions,
11777
+ firstFetch
11778
+ }));
11779
+ } catch (error) {
11780
+ if (signal.aborted) return { kind: "aborted" };
11781
+ const isNonObjectThrow = typeof error !== "object" || error === null;
11782
+ if (isNonObjectThrow || isNonRetryableDrainError(error) || isPermanentHttpError(error)) {
11783
+ return { kind: "error", error };
11784
+ }
11785
+ consecutiveErrors = Math.min(consecutiveErrors + 1, ERROR_BACKOFF_CAP);
11786
+ errorAttempts += 1;
11787
+ const delay = calculateErrorBackoffMs(
11788
+ BASE_ERROR_BACKOFF_MS,
11789
+ consecutiveErrors
11790
+ );
11791
+ const statusCode = errorStatusCode(error);
11792
+ const httpPart = statusCode !== void 0 ? ` (HTTP ${statusCode})` : "";
11793
+ if (!drainDegraded && consecutiveErrors >= ERROR_BACKOFF_CAP) {
11794
+ console.warn(
11795
+ `[zapier-sdk] Draining inbox ${inboxId}${httpPart} is failing repeatedly: ${errorMessage(error)}. Continuing to retry with backoff.`
11796
+ );
11797
+ drainDegraded = true;
11798
+ }
11799
+ if (debug) {
11800
+ console.error(
11801
+ `[zapier-sdk] Retrying drain for inbox ${inboxId} (attempt ${errorAttempts}, retry in ${delay}ms)${httpPart}: ${errorMessage(error)}`
11802
+ );
11803
+ }
11804
+ await sleep(delay, signal);
11805
+ if (signal.aborted) return { kind: "aborted" };
11806
+ drainRequest.request();
11807
+ continue;
11808
+ }
11809
+ firstFetch = false;
11810
+ consecutiveErrors = 0;
11811
+ errorAttempts = 0;
11812
+ drainDegraded = false;
11813
+ if (abortedFromCallback) return { kind: "abortedFromCallback" };
11814
+ }
11815
+ return { kind: "aborted" };
11816
+ }
11817
+ function errorStatusCode(err) {
11818
+ return err instanceof ZapierError ? err.statusCode : void 0;
11819
+ }
11820
+ function errorMessage(err) {
11821
+ return err instanceof Error ? err.message : String(err);
11822
+ }
11823
+ async function sseLoop({
11824
+ api,
11825
+ inboxId,
11826
+ drainRequest,
11827
+ safetyDrainMs,
11828
+ signal,
11829
+ debug
11830
+ }) {
11831
+ let attempt = 0;
11832
+ let degraded = false;
11833
+ while (!signal.aborted) {
11834
+ let connected = false;
11835
+ let connectedAt = 0;
11836
+ let transientError;
11837
+ try {
11838
+ for await (const _event of readInboxEvents({
11839
+ api,
11840
+ inboxId,
11841
+ signal,
11842
+ // SSE is edge-triggered with no replay, so draining on connect is the
11843
+ // only way to pick up messages that arrived before this connection —
11844
+ // including the window left by a prior disconnect.
11845
+ onOpen: () => {
11846
+ connected = true;
11847
+ connectedAt = Date.now();
11848
+ degraded = false;
11849
+ drainRequest.request();
11850
+ }
11851
+ })) {
11852
+ drainRequest.request();
11853
+ }
11854
+ if (connected && Date.now() - connectedAt >= SSE_HEALTHY_CONNECTION_MS) {
11855
+ attempt = 0;
11856
+ }
11857
+ } catch (err) {
11858
+ if (signal.aborted || isAbortError(err)) return;
11859
+ if (isPermanentHttpError(err)) {
11860
+ if (!degraded) {
11861
+ const statusCode = errorStatusCode(err);
11862
+ const errorMsg = errorMessage(err);
11863
+ const httpPart = statusCode !== void 0 ? ` (HTTP ${statusCode})` : "";
11864
+ console.warn(
11865
+ `[zapier-sdk] Real-time wake-ups for inbox ${inboxId}${httpPart} paused: ${errorMsg}. Falling back to the periodic safety drain.`
11866
+ );
11867
+ degraded = true;
11868
+ }
11869
+ attempt = 0;
11870
+ if (signal.aborted) return;
11871
+ await sleep(safetyDrainMs, signal);
11872
+ continue;
11873
+ }
11874
+ if (connected) attempt = 0;
11875
+ transientError = err;
11876
+ }
11877
+ if (signal.aborted) return;
11878
+ const delay = SSE_RECONNECT_BACKOFF_MS[Math.min(attempt, SSE_RECONNECT_BACKOFF_MS.length - 1)];
11879
+ attempt = Math.min(attempt + 1, SSE_RECONNECT_BACKOFF_MS.length - 1);
11880
+ if (transientError !== void 0 && debug) {
11881
+ const statusCode = errorStatusCode(transientError);
11882
+ const errorMsg = errorMessage(transientError);
11883
+ const httpPart = statusCode !== void 0 ? ` (HTTP ${statusCode})` : "";
11884
+ console.error(
11885
+ `[zapier-sdk] Reconnecting real-time wake-ups for inbox ${inboxId} (attempt ${attempt}, retry in ${delay}ms)${httpPart}: ${errorMsg}`
11886
+ );
11887
+ }
11888
+ await sleep(delay, signal);
11889
+ }
11890
+ }
11891
+ async function safetyTimerLoop({
11892
+ safetyDrainMs,
11893
+ drainRequest,
11894
+ signal
11895
+ }) {
11896
+ while (!signal.aborted) {
11897
+ await sleep(safetyDrainMs, signal);
11898
+ if (signal.aborted) return;
11899
+ drainRequest.request();
11900
+ }
11901
+ }
11902
+ var watchTriggerInboxPlugin = definePlugin(
11903
+ (sdk) => {
11904
+ async function watchTriggerInbox(options) {
11905
+ const onMessage = requireOnMessage(options.onMessage);
11906
+ const { concurrency, leaseLimit } = resolveConcurrencyAndLease(options);
11907
+ const inboxId = await resolveTriggerInboxId({
11908
+ api: sdk.context.api,
11909
+ inbox: options.inbox
11910
+ });
11911
+ if (options.signal?.aborted) return;
11912
+ const safetyDrainMs = options.maxDrainIntervalSeconds !== void 0 ? options.maxDrainIntervalSeconds * 1e3 : DEFAULT_SAFETY_DRAIN_INTERVAL_MS;
11913
+ const stop = new AbortController();
11914
+ const combined = combineAbortSignals({
11915
+ handles: [
11916
+ ...options.signal ? [{ signal: options.signal, dispose: () => {
11917
+ } }] : [],
11918
+ { signal: stop.signal, dispose: () => {
11919
+ } }
11920
+ ]
11921
+ });
11922
+ const signal = combined?.signal ?? stop.signal;
11923
+ const drainRequest = createDrainLatch();
11924
+ signal.addEventListener("abort", () => drainRequest.request(), {
11925
+ once: true
11926
+ });
11927
+ const debug = sdk.context.options.debug === true;
11928
+ const drainOptions = {
11929
+ sdk,
11930
+ inboxId,
11931
+ onMessage,
11932
+ concurrency,
11933
+ leaseLimit,
11934
+ leaseSeconds: options.leaseSeconds,
11935
+ maxMessages: void 0,
11936
+ releaseOnError: options.releaseOnError ?? false,
11937
+ continueOnError: options.continueOnError ?? false,
11938
+ onError: options.onError,
11939
+ signal
11940
+ };
11941
+ drainRequest.request();
11942
+ const runnerDone = drainRunner({
11943
+ drainOptions,
11944
+ drainRequest,
11945
+ signal,
11946
+ inboxId,
11947
+ debug
11948
+ });
11949
+ const sseDone = sseLoop({
11950
+ api: sdk.context.api,
11951
+ inboxId,
11952
+ drainRequest,
11953
+ safetyDrainMs,
11954
+ signal,
11955
+ debug
11956
+ }).catch(() => {
11957
+ });
11958
+ const safetyDone = safetyTimerLoop({
11959
+ safetyDrainMs,
11960
+ drainRequest,
11961
+ signal
11962
+ }).catch(() => {
11963
+ });
11964
+ let end;
11965
+ try {
11966
+ end = await runnerDone;
11967
+ } finally {
11968
+ stop.abort();
11969
+ await Promise.all([sseDone, safetyDone]);
11970
+ combined?.dispose();
11971
+ }
11972
+ if (end.kind === "error") throw end.error;
11973
+ }
11974
+ return {
11975
+ watchTriggerInbox,
11976
+ context: {
11977
+ meta: {
11978
+ watchTriggerInbox: {
11979
+ ...triggersDefaults,
11980
+ type: "create",
11981
+ description: "Continuously consume a trigger inbox: drain currently-available messages via onMessage, then subscribe to SSE notifications for new arrivals until aborted. A periodic safety drain runs every maxDrainIntervalSeconds (default: 300) to guarantee forward progress if SSE events are missed. Resolves cleanly on signal abort or ZapierAbortDrainSignal from a handler. Transient drain failures (5xx, 429, network blips) retry indefinitely with bounded backoff until they succeed or the watch is aborted; it rejects on a fail-fast handler error, an initialization_failure, or a permanent HTTP error. Real-time wake-up health is reported on stderr: a warning when wake-ups pause and the watch falls back to the safety drain, plus (with debug) transient reconnect notices. Persistent drain failures likewise warn once on stderr while bounded-backoff retries continue.",
11982
+ itemType: "void",
11983
+ // See drainTriggerInbox: override the doc generator's default
11984
+ // suffix so the rendered return type is Promise<void>, not
11985
+ // Promise<voidItem>.
11986
+ returnType: "void",
11987
+ inputSchema: WatchTriggerInboxSchema,
11988
+ resolvers: {
11989
+ inbox: triggerInboxResolver
11990
+ },
11991
+ packages: ["sdk"]
11992
+ }
11993
+ }
11994
+ }
11995
+ };
11996
+ }
11997
+ );
11998
+ var ListTriggersSchema = zod.z.object({
11999
+ app: AppPropertySchema.describe(
12000
+ "App key of triggers to list (e.g., 'SlackCLIAPI' or slug like 'github')"
12001
+ ),
12002
+ pageSize: zod.z.number().min(1).optional().describe("Number of triggers per page"),
12003
+ maxItems: zod.z.number().min(1).optional().describe("Maximum total items to return across all pages"),
12004
+ cursor: zod.z.string().optional().describe("Cursor to start from")
12005
+ }).describe("List all triggers for a specific app");
12006
+
12007
+ // src/plugins/triggers/listTriggers/index.ts
12008
+ var listTriggersPlugin = definePlugin(
12009
+ (sdk) => createPaginatedPluginMethod(sdk, {
12010
+ ...triggersDefaults,
12011
+ name: "listTriggers",
12012
+ type: "list",
12013
+ itemType: "Action",
12014
+ inputSchema: ListTriggersSchema,
12015
+ outputSchema: ActionItemSchema,
12016
+ formatter: actionItemFormatter,
12017
+ defaultPageSize: DEFAULT_PAGE_SIZE,
12018
+ resolvers: { app: appKeyResolver },
12019
+ handler: async ({ sdk: sdk2, options }) => {
12020
+ return await sdk2.listActions({
12021
+ ...options,
12022
+ actionType: "read"
12023
+ });
12024
+ }
12025
+ })
12026
+ );
12027
+ var ListTriggerInputFieldsSchema = zod.z.object({
12028
+ app: AppPropertySchema,
12029
+ action: ActionPropertySchema,
12030
+ connection: ConnectionPropertySchema.optional().describe(
12031
+ "Connection alias or connection ID. Required if the trigger needs a connection to determine available fields."
12032
+ ),
12033
+ inputs: InputsPropertySchema.optional().describe(
12034
+ "Current input values that may affect available fields"
12035
+ ),
12036
+ pageSize: zod.z.number().min(1).optional().describe("Number of input fields per page"),
12037
+ maxItems: zod.z.number().min(1).optional().describe("Maximum total items to return across all pages"),
12038
+ cursor: zod.z.string().optional().describe("Cursor to start from")
12039
+ }).describe("Get the input fields required for a specific trigger");
12040
+
12041
+ // src/plugins/triggers/listTriggerInputFields/index.ts
12042
+ var listTriggerInputFieldsPlugin = definePlugin(
12043
+ (sdk) => createPaginatedPluginMethod(sdk, {
12044
+ ...triggersDefaults,
12045
+ name: "listTriggerInputFields",
12046
+ type: "list",
12047
+ itemType: "RootField",
12048
+ inputSchema: ListTriggerInputFieldsSchema,
12049
+ outputSchema: RootFieldItemSchema,
12050
+ formatter: rootFieldItemFormatter,
12051
+ defaultPageSize: DEFAULT_PAGE_SIZE,
12052
+ // actionKeyResolver and inputsAllOptionalResolver depend on actionType.
12053
+ // Pin it to "read" so they resolve correctly without the user setting it.
12054
+ resolvers: {
12055
+ app: appKeyResolver,
12056
+ action: actionKeyResolver,
12057
+ connection: connectionIdResolver,
12058
+ inputs: inputsAllOptionalResolver,
12059
+ actionType: { type: "constant", value: "read" }
12060
+ },
12061
+ handler: async ({ sdk: sdk2, options }) => {
12062
+ return await sdk2.listActionInputFields({
12063
+ ...options,
12064
+ actionType: "read"
12065
+ });
12066
+ }
12067
+ })
12068
+ );
12069
+ var ListTriggerInputFieldChoicesSchema = zod.z.object({
12070
+ app: AppPropertySchema,
12071
+ action: ActionPropertySchema,
12072
+ inputField: InputFieldPropertySchema,
12073
+ connection: ConnectionPropertySchema.optional().describe(
12074
+ "Connection alias or connection ID. Required if the trigger needs a connection to populate dynamic dropdown options."
12075
+ ),
12076
+ inputs: InputsPropertySchema.optional().describe(
12077
+ "Current input values that may affect available choices"
12078
+ ),
12079
+ page: zod.z.number().int().min(0).optional().describe("Page number for paginated results"),
12080
+ pageSize: zod.z.number().min(1).optional().describe("Number of choices per page"),
12081
+ maxItems: zod.z.number().min(1).optional().describe("Maximum total items to return across all pages"),
12082
+ cursor: zod.z.string().optional().describe("Cursor to start from")
12083
+ }).describe(
12084
+ "Get the available choices for a dynamic dropdown input field on a trigger"
12085
+ );
12086
+
12087
+ // src/plugins/triggers/listTriggerInputFieldChoices/index.ts
12088
+ var listTriggerInputFieldChoicesPlugin = definePlugin(
12089
+ (sdk) => createPaginatedPluginMethod(sdk, {
12090
+ ...triggersDefaults,
12091
+ name: "listTriggerInputFieldChoices",
12092
+ type: "list",
12093
+ itemType: "InputFieldChoice",
12094
+ inputSchema: ListTriggerInputFieldChoicesSchema,
12095
+ outputSchema: InputFieldChoiceItemSchema,
12096
+ formatter: inputFieldChoiceItemFormatter,
12097
+ defaultPageSize: DEFAULT_PAGE_SIZE,
12098
+ resolvers: {
12099
+ app: appKeyResolver,
12100
+ action: actionKeyResolver,
12101
+ connection: connectionIdResolver,
12102
+ inputField: inputFieldKeyResolver,
12103
+ inputs: inputsAllOptionalResolver,
12104
+ actionType: { type: "constant", value: "read" }
12105
+ },
12106
+ handler: async ({ sdk: sdk2, options }) => {
12107
+ return await sdk2.listActionInputFieldChoices({
12108
+ ...options,
12109
+ actionType: "read"
12110
+ });
12111
+ }
12112
+ })
12113
+ );
12114
+ var GetTriggerInputFieldsSchemaSchema = zod.z.object({
12115
+ app: AppPropertySchema.describe(
12116
+ "App key (e.g., 'SlackCLIAPI' or slug like 'github') to get the input schema for"
12117
+ ),
12118
+ action: ActionPropertySchema.describe(
12119
+ "Trigger action key to get the input schema for"
12120
+ ),
12121
+ connection: ConnectionPropertySchema.optional().describe(
12122
+ "Connection alias or connection ID. Required if the trigger needs a connection to determine available fields."
12123
+ ),
12124
+ inputs: InputsPropertySchema.optional().describe(
12125
+ "Current input values that may affect the schema (e.g., when fields depend on other field values)"
12126
+ )
12127
+ }).describe(
12128
+ "Get the JSON Schema representation of input fields for a trigger. Returns a JSON Schema object describing the structure, types, and validation rules for the trigger's input parameters."
12129
+ );
12130
+
12131
+ // src/plugins/triggers/getTriggerInputFieldsSchema/index.ts
12132
+ var getTriggerInputFieldsSchemaPlugin = definePlugin(
12133
+ (sdk) => createPluginMethod(sdk, {
12134
+ ...triggersDefaults,
12135
+ name: "getTriggerInputFieldsSchema",
12136
+ type: "function",
12137
+ inputSchema: GetTriggerInputFieldsSchemaSchema,
12138
+ resolvers: {
12139
+ app: appKeyResolver,
12140
+ action: actionKeyResolver,
12141
+ connection: connectionIdResolver,
12142
+ inputs: inputsAllOptionalResolver,
12143
+ actionType: { type: "constant", value: "read" }
12144
+ },
12145
+ handler: async ({ sdk: sdk2, options }) => {
12146
+ return sdk2.getActionInputFieldsSchema({
12147
+ ...options,
12148
+ actionType: "read"
12149
+ });
12150
+ }
12151
+ })
12152
+ );
10501
12153
  var TableApiItemSchema = zod.z.object({
10502
12154
  id: zod.z.string(),
10503
12155
  name: zod.z.string(),
@@ -11605,10 +13257,12 @@ function buildApplicationLifecycleEvent(data, context = {}) {
11605
13257
  ci_platform: getCiPlatform(),
11606
13258
  ...getTtyContext(),
11607
13259
  agent: getAgent(),
13260
+ used_non_interactive_mode: data.used_non_interactive_mode ?? null,
13261
+ is_headless: data.is_headless ?? null,
11608
13262
  session_id: null,
11609
13263
  metadata: null,
11610
- process_argv: globalThis.process?.argv || null,
11611
13264
  ...data,
13265
+ process_argv: data.process_argv ?? null,
11612
13266
  sdk_version: SDK_VERSION
11613
13267
  };
11614
13268
  }
@@ -11948,10 +13602,10 @@ var eventEmissionPlugin = definePlugin(
11948
13602
  registeredListeners.uncaughtException = uncaughtExceptionHandler;
11949
13603
  globalThis.process.on("uncaughtException", uncaughtExceptionHandler);
11950
13604
  const unhandledRejectionHandler = async (reason, promise) => {
11951
- const errorMessage = reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Unhandled promise rejection";
13605
+ const errorMessage2 = reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Unhandled promise rejection";
11952
13606
  const errorStack = reason instanceof Error ? reason.stack : null;
11953
13607
  let errorEvent = buildErrorEventWithContext({
11954
- error_message: errorMessage,
13608
+ error_message: errorMessage2,
11955
13609
  error_type: "UnhandledRejection",
11956
13610
  error_stack_trace: errorStack,
11957
13611
  error_severity: "critical",
@@ -12077,7 +13731,7 @@ function createZapierSdkWithoutRegistry(options = {}) {
12077
13731
  return createZapierSdk(options);
12078
13732
  }
12079
13733
  function createZapierSdkStack(options = {}) {
12080
- return createZapierCoreStack().use(createOptionsPlugin(options)).use(eventEmissionPlugin).use(apiPlugin).use(manifestPlugin).use(capabilitiesPlugin).use(connectionsPlugin).use(listAppsPlugin).use(getAppPlugin).use(listConnectionsPlugin).use(getConnectionPlugin).use(findFirstConnectionPlugin).use(findUniqueConnectionPlugin).use(getConnectionStartUrlPlugin).use(waitForNewConnectionPlugin).use(createConnectionPlugin).use(listActionsPlugin).use(getActionPlugin).use(listActionInputFieldsPlugin).use(getActionInputFieldsSchemaPlugin).use(listActionInputFieldChoicesPlugin).use(listInputFieldsDeprecatedPlugin).use(getInputFieldsSchemaDeprecatedPlugin).use(listInputFieldChoicesDeprecatedPlugin).use(runActionPlugin).use(listAuthenticationsPlugin).use(getAuthenticationPlugin).use(findFirstAuthenticationPlugin).use(findUniqueAuthenticationPlugin).use(listClientCredentialsPlugin).use(createClientCredentialsPlugin).use(deleteClientCredentialsPlugin).use(fetchPlugin).use(requestPlugin).use(listTablesPlugin).use(getTablePlugin).use(deleteTablePlugin).use(createTablePlugin).use(listTableFieldsPlugin).use(createTableFieldsPlugin).use(deleteTableFieldsPlugin).use(listTableRecordsPlugin).use(getTableRecordPlugin).use(createTableRecordsPlugin).use(deleteTableRecordsPlugin).use(updateTableRecordsPlugin).use(appsPlugin);
13734
+ return createZapierCoreStack().use(createOptionsPlugin(options)).use(eventEmissionPlugin).use(apiPlugin).use(manifestPlugin).use(capabilitiesPlugin).use(connectionsPlugin).use(listAppsPlugin).use(getAppPlugin).use(listConnectionsPlugin).use(getConnectionPlugin).use(findFirstConnectionPlugin).use(findUniqueConnectionPlugin).use(getConnectionStartUrlPlugin).use(waitForNewConnectionPlugin).use(createConnectionPlugin).use(listActionsPlugin).use(getActionPlugin).use(listActionInputFieldsPlugin).use(getActionInputFieldsSchemaPlugin).use(listActionInputFieldChoicesPlugin).use(listInputFieldsDeprecatedPlugin).use(getInputFieldsSchemaDeprecatedPlugin).use(listInputFieldChoicesDeprecatedPlugin).use(runActionPlugin).use(listAuthenticationsPlugin).use(getAuthenticationPlugin).use(findFirstAuthenticationPlugin).use(findUniqueAuthenticationPlugin).use(listClientCredentialsPlugin).use(createClientCredentialsPlugin).use(deleteClientCredentialsPlugin).use(fetchPlugin).use(requestPlugin).use(listTriggerInboxesPlugin).use(createTriggerInboxPlugin).use(ensureTriggerInboxPlugin).use(getTriggerInboxPlugin).use(updateTriggerInboxPlugin).use(deleteTriggerInboxPlugin).use(pauseTriggerInboxPlugin).use(resumeTriggerInboxPlugin).use(listTriggerInboxMessagesPlugin).use(leaseTriggerInboxMessagesPlugin).use(ackTriggerInboxMessagesPlugin).use(releaseTriggerInboxMessagesPlugin).use(drainTriggerInboxPlugin).use(watchTriggerInboxPlugin).use(listTriggersPlugin).use(listTriggerInputFieldsPlugin).use(listTriggerInputFieldChoicesPlugin).use(getTriggerInputFieldsSchemaPlugin).use(listTablesPlugin).use(getTablePlugin).use(deleteTablePlugin).use(createTablePlugin).use(listTableFieldsPlugin).use(createTableFieldsPlugin).use(deleteTableFieldsPlugin).use(listTableRecordsPlugin).use(getTableRecordPlugin).use(createTableRecordsPlugin).use(deleteTableRecordsPlugin).use(updateTableRecordsPlugin).use(appsPlugin);
12081
13735
  }
12082
13736
  var zapierSdkPlugin = definePlugin({
12083
13737
  namespace: "zapier",