@zapier/zapier-sdk 0.81.1 → 0.82.1

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