@zapier/zapier-sdk 0.70.3 → 0.71.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +248 -95
  3. package/dist/api/approval-review-stream.d.ts +25 -0
  4. package/dist/api/approval-review-stream.d.ts.map +1 -0
  5. package/dist/api/approval-review-stream.js +104 -0
  6. package/dist/api/client.d.ts.map +1 -1
  7. package/dist/api/client.js +215 -27
  8. package/dist/api/types.d.ts +13 -3
  9. package/dist/api/types.d.ts.map +1 -1
  10. package/dist/constants.d.ts +1 -0
  11. package/dist/constants.d.ts.map +1 -1
  12. package/dist/constants.js +6 -0
  13. package/dist/experimental.cjs +702 -67
  14. package/dist/experimental.d.mts +242 -2
  15. package/dist/experimental.d.ts +240 -0
  16. package/dist/experimental.d.ts.map +1 -1
  17. package/dist/experimental.js +10 -0
  18. package/dist/experimental.mjs +702 -68
  19. package/dist/{index-rIzBEINC.d.mts → index-B43uST61.d.mts} +248 -10
  20. package/dist/{index-rIzBEINC.d.ts → index-B43uST61.d.ts} +248 -10
  21. package/dist/index.cjs +592 -32
  22. package/dist/index.d.mts +1 -1
  23. package/dist/index.mjs +592 -33
  24. package/dist/plugins/api/index.d.ts.map +1 -1
  25. package/dist/plugins/api/index.js +2 -1
  26. package/dist/plugins/codeSubstrate/deleteWorkflow/index.d.ts +9 -0
  27. package/dist/plugins/codeSubstrate/deleteWorkflow/index.d.ts.map +1 -1
  28. package/dist/plugins/codeSubstrate/disableWorkflow/index.d.ts +9 -0
  29. package/dist/plugins/codeSubstrate/disableWorkflow/index.d.ts.map +1 -1
  30. package/dist/plugins/codeSubstrate/enableWorkflow/index.d.ts +9 -0
  31. package/dist/plugins/codeSubstrate/enableWorkflow/index.d.ts.map +1 -1
  32. package/dist/plugins/codeSubstrate/getDurableRun/schemas.d.ts +5 -5
  33. package/dist/plugins/codeSubstrate/getTriggerRun/schemas.d.ts +1 -1
  34. package/dist/plugins/codeSubstrate/getWorkflow/index.d.ts +31 -0
  35. package/dist/plugins/codeSubstrate/getWorkflow/index.d.ts.map +1 -1
  36. package/dist/plugins/codeSubstrate/getWorkflow/schemas.d.ts +42 -0
  37. package/dist/plugins/codeSubstrate/getWorkflow/schemas.d.ts.map +1 -1
  38. package/dist/plugins/codeSubstrate/getWorkflow/schemas.js +20 -0
  39. package/dist/plugins/codeSubstrate/getWorkflowRun/index.d.ts +9 -0
  40. package/dist/plugins/codeSubstrate/getWorkflowRun/index.d.ts.map +1 -1
  41. package/dist/plugins/codeSubstrate/getWorkflowRun/schemas.d.ts +1 -1
  42. package/dist/plugins/codeSubstrate/getWorkflowVersion/index.d.ts +35 -0
  43. package/dist/plugins/codeSubstrate/getWorkflowVersion/index.d.ts.map +1 -1
  44. package/dist/plugins/codeSubstrate/getWorkflowVersion/schemas.d.ts +13 -0
  45. package/dist/plugins/codeSubstrate/getWorkflowVersion/schemas.d.ts.map +1 -1
  46. package/dist/plugins/codeSubstrate/getWorkflowVersion/schemas.js +10 -0
  47. package/dist/plugins/codeSubstrate/listDurableRuns/schemas.d.ts +3 -3
  48. package/dist/plugins/codeSubstrate/listWorkflowRuns/index.d.ts +9 -0
  49. package/dist/plugins/codeSubstrate/listWorkflowRuns/index.d.ts.map +1 -1
  50. package/dist/plugins/codeSubstrate/listWorkflowRuns/schemas.d.ts +3 -3
  51. package/dist/plugins/codeSubstrate/listWorkflowVersions/index.d.ts +22 -0
  52. package/dist/plugins/codeSubstrate/listWorkflowVersions/index.d.ts.map +1 -1
  53. package/dist/plugins/codeSubstrate/listWorkflowVersions/schemas.d.ts +26 -0
  54. package/dist/plugins/codeSubstrate/listWorkflowVersions/schemas.d.ts.map +1 -1
  55. package/dist/plugins/codeSubstrate/listWorkflowVersions/schemas.js +10 -0
  56. package/dist/plugins/codeSubstrate/listWorkflows/index.d.ts +9 -0
  57. package/dist/plugins/codeSubstrate/listWorkflows/index.d.ts.map +1 -1
  58. package/dist/plugins/codeSubstrate/listWorkflows/schemas.d.ts +32 -0
  59. package/dist/plugins/codeSubstrate/listWorkflows/schemas.d.ts.map +1 -1
  60. package/dist/plugins/codeSubstrate/listWorkflows/schemas.js +11 -0
  61. package/dist/plugins/codeSubstrate/publishWorkflowVersion/index.d.ts +22 -0
  62. package/dist/plugins/codeSubstrate/publishWorkflowVersion/index.d.ts.map +1 -1
  63. package/dist/plugins/codeSubstrate/publishWorkflowVersion/schemas.d.ts +14 -1
  64. package/dist/plugins/codeSubstrate/publishWorkflowVersion/schemas.d.ts.map +1 -1
  65. package/dist/plugins/codeSubstrate/publishWorkflowVersion/schemas.js +11 -44
  66. package/dist/plugins/codeSubstrate/runDurable/index.d.ts +6 -0
  67. package/dist/plugins/codeSubstrate/runDurable/index.d.ts.map +1 -1
  68. package/dist/plugins/codeSubstrate/runDurable/index.js +3 -0
  69. package/dist/plugins/codeSubstrate/runDurable/schemas.d.ts +12 -0
  70. package/dist/plugins/codeSubstrate/runDurable/schemas.d.ts.map +1 -1
  71. package/dist/plugins/codeSubstrate/runDurable/schemas.js +33 -0
  72. package/dist/plugins/codeSubstrate/shared-schemas.d.ts +37 -0
  73. package/dist/plugins/codeSubstrate/shared-schemas.d.ts.map +1 -0
  74. package/dist/plugins/codeSubstrate/shared-schemas.js +69 -0
  75. package/dist/plugins/codeSubstrate/triggerWorkflow/index.d.ts +9 -0
  76. package/dist/plugins/codeSubstrate/triggerWorkflow/index.d.ts.map +1 -1
  77. package/dist/plugins/codeSubstrate/updateWorkflow/index.d.ts +11 -0
  78. package/dist/plugins/codeSubstrate/updateWorkflow/index.d.ts.map +1 -1
  79. package/dist/plugins/codeSubstrate/updateWorkflow/schemas.d.ts +2 -0
  80. package/dist/plugins/codeSubstrate/updateWorkflow/schemas.d.ts.map +1 -1
  81. package/dist/plugins/codeSubstrate/updateWorkflow/schemas.js +7 -0
  82. package/dist/plugins/createConnection/index.d.ts +189 -0
  83. package/dist/plugins/createConnection/index.d.ts.map +1 -0
  84. package/dist/plugins/createConnection/index.js +71 -0
  85. package/dist/plugins/createConnection/schemas.d.ts +21 -0
  86. package/dist/plugins/createConnection/schemas.d.ts.map +1 -0
  87. package/dist/plugins/createConnection/schemas.js +38 -0
  88. package/dist/plugins/getConnectionStartUrl/index.d.ts +206 -0
  89. package/dist/plugins/getConnectionStartUrl/index.d.ts.map +1 -0
  90. package/dist/plugins/getConnectionStartUrl/index.js +39 -0
  91. package/dist/plugins/getConnectionStartUrl/schemas.d.ts +15 -0
  92. package/dist/plugins/getConnectionStartUrl/schemas.d.ts.map +1 -0
  93. package/dist/plugins/getConnectionStartUrl/schemas.js +23 -0
  94. package/dist/plugins/waitForNewConnection/index.d.ts +209 -0
  95. package/dist/plugins/waitForNewConnection/index.d.ts.map +1 -0
  96. package/dist/plugins/waitForNewConnection/index.js +75 -0
  97. package/dist/plugins/waitForNewConnection/schemas.d.ts +17 -0
  98. package/dist/plugins/waitForNewConnection/schemas.d.ts.map +1 -0
  99. package/dist/plugins/waitForNewConnection/schemas.js +39 -0
  100. package/dist/sdk.d.ts +126 -0
  101. package/dist/sdk.d.ts.map +1 -1
  102. package/dist/sdk.js +8 -0
  103. package/dist/types/errors.d.ts +13 -4
  104. package/dist/types/errors.d.ts.map +1 -1
  105. package/dist/types/errors.js +2 -0
  106. package/dist/types/sdk.d.ts +1 -0
  107. package/dist/types/sdk.d.ts.map +1 -1
  108. package/dist/types/sdk.js +5 -1
  109. package/dist/utils/open-url.d.ts.map +1 -1
  110. package/dist/utils/open-url.js +7 -0
  111. package/dist/utils/should-open-browser.d.ts +24 -0
  112. package/dist/utils/should-open-browser.d.ts.map +1 -0
  113. package/dist/utils/should-open-browser.js +55 -0
  114. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -1058,6 +1058,11 @@ function getZapierApprovalMode() {
1058
1058
  return value;
1059
1059
  return void 0;
1060
1060
  }
1061
+ function getZapierOpenAutoModeApprovalsInBrowser() {
1062
+ const value = globalThis.process?.env?.ZAPIER_OPEN_AUTO_MODE_APPROVALS_IN_BROWSER;
1063
+ if (value === void 0) return void 0;
1064
+ return value === "true";
1065
+ }
1061
1066
  function getZapierDefaultApprovalMode() {
1062
1067
  const isInteractive = !!globalThis.process?.stdin?.isTTY && !!globalThis.process?.stdout?.isTTY;
1063
1068
  return isInteractive ? "poll" : "throw";
@@ -1281,6 +1286,8 @@ var ZapierApprovalError = class extends ZapierError {
1281
1286
  this.approvalStatus = options.status;
1282
1287
  this.approvalUrl = options.approvalUrl;
1283
1288
  this.pollUrl = options.pollUrl;
1289
+ this.streamUrl = options.streamUrl;
1290
+ this.reason = options.reason;
1284
1291
  }
1285
1292
  };
1286
1293
  var ZapierRelayError = class extends ZapierError {
@@ -6777,9 +6784,101 @@ function createSseParserStream() {
6777
6784
  }
6778
6785
  });
6779
6786
  }
6787
+ var ApprovalReviewChunkSchema = z.discriminatedUnion("type", [
6788
+ z.object({
6789
+ type: z.literal("text-delta"),
6790
+ delta: z.string()
6791
+ }).passthrough(),
6792
+ z.object({
6793
+ type: z.literal("tool-input-available"),
6794
+ toolCallId: z.string(),
6795
+ toolName: z.string()
6796
+ }).passthrough(),
6797
+ z.object({
6798
+ type: z.literal("tool-output-available"),
6799
+ toolCallId: z.string(),
6800
+ output: z.unknown()
6801
+ }).passthrough()
6802
+ ]);
6803
+ var ReportDecisionOutputSchema = z.object({
6804
+ success: z.boolean().optional(),
6805
+ decision: z.enum(["approved", "denied"]),
6806
+ reason: z.string().optional()
6807
+ }).passthrough();
6808
+ async function consumeApprovalReviewStream({
6809
+ approvalId,
6810
+ streamUrl,
6811
+ signal,
6812
+ stream,
6813
+ emitEvent
6814
+ }) {
6815
+ try {
6816
+ const toolNames = /* @__PURE__ */ new Map();
6817
+ for await (const frame of stream(streamUrl, {
6818
+ method: "GET",
6819
+ headers: {
6820
+ "Accept-Encoding": "identity"
6821
+ },
6822
+ signal
6823
+ })) {
6824
+ if (!frame.parsed) continue;
6825
+ const payload = parseApprovalReviewStreamPayload(frame.data, toolNames);
6826
+ if (!payload) continue;
6827
+ if (payload.kind === "message") {
6828
+ emitEvent("approval:review_message", {
6829
+ approvalId,
6830
+ streamUrl,
6831
+ data: payload.data,
6832
+ message: payload.message
6833
+ });
6834
+ continue;
6835
+ }
6836
+ emitEvent("approval:review_decision", {
6837
+ approvalId,
6838
+ streamUrl,
6839
+ data: payload.data,
6840
+ decision: payload.decision,
6841
+ ...payload.reason ? { reason: payload.reason } : {}
6842
+ });
6843
+ }
6844
+ } catch (err) {
6845
+ if (isAbortError(err) || signal.aborted) return;
6846
+ emitEvent("approval:review_stream_error", {
6847
+ approvalId,
6848
+ streamUrl,
6849
+ message: err instanceof Error ? err.message : String(err)
6850
+ });
6851
+ }
6852
+ }
6853
+ function parseApprovalReviewStreamPayload(parsed, toolNames) {
6854
+ const chunk = ApprovalReviewChunkSchema.safeParse(parsed);
6855
+ if (!chunk.success) return void 0;
6856
+ switch (chunk.data.type) {
6857
+ case "text-delta": {
6858
+ const message = chunk.data.delta.trim();
6859
+ return message.length > 0 ? { kind: "message", data: parsed, message } : void 0;
6860
+ }
6861
+ case "tool-input-available":
6862
+ toolNames.set(chunk.data.toolCallId, chunk.data.toolName);
6863
+ return void 0;
6864
+ case "tool-output-available": {
6865
+ if (toolNames.get(chunk.data.toolCallId) !== "report_decision") {
6866
+ return void 0;
6867
+ }
6868
+ const decision = ReportDecisionOutputSchema.safeParse(chunk.data.output);
6869
+ if (!decision.success) return void 0;
6870
+ return {
6871
+ kind: "decision",
6872
+ data: parsed,
6873
+ decision: decision.data.decision,
6874
+ ...decision.data.reason ? { reason: decision.data.reason } : {}
6875
+ };
6876
+ }
6877
+ }
6878
+ }
6780
6879
 
6781
6880
  // src/sdk-version.ts
6782
- var SDK_VERSION = (typeof process !== "undefined" && process.env ? "0.70.3" : void 0) || "unknown";
6881
+ var SDK_VERSION = (typeof process !== "undefined" && process.env ? "0.71.0" : void 0) || "unknown";
6783
6882
 
6784
6883
  // src/utils/open-url.ts
6785
6884
  var nodePrefix = "node:";
@@ -6831,6 +6930,9 @@ var openUrl = async (url) => {
6831
6930
  } else if (platform === "win32") {
6832
6931
  command = "rundll32";
6833
6932
  args = ["url.dll,FileProtocolHandler", target];
6933
+ } else if (platform === "linux") {
6934
+ command = "xdg-open";
6935
+ args = [target];
6834
6936
  } else {
6835
6937
  throw new Error(`Unsupported platform: ${platform}`);
6836
6938
  }
@@ -6853,16 +6955,39 @@ async function openApproval(url) {
6853
6955
  } catch {
6854
6956
  }
6855
6957
  }
6856
- var ApprovalStatusSchema = z.enum(["pending_approval", "approved", "denied"]);
6958
+ var ApprovalStatusSchema = z.enum([
6959
+ "pending_approval",
6960
+ "approved",
6961
+ "denied",
6962
+ "failed"
6963
+ ]);
6964
+ var ApprovalModeSchema = z.enum(["manual", "auto"]);
6857
6965
  var CreateApprovalResponseSchema = z.object({
6966
+ id: z.string().optional(),
6858
6967
  status: ApprovalStatusSchema,
6859
- approval_id: z.string(),
6968
+ approval_id: z.string().optional(),
6969
+ mode: ApprovalModeSchema,
6860
6970
  approval_url: z.string().url(),
6861
- poll_url: z.string().url()
6971
+ poll_url: z.string().url(),
6972
+ stream_url: z.string().url().optional(),
6973
+ reason: z.string().optional()
6974
+ }).transform((approval, ctx) => {
6975
+ const id = approval.id ?? approval.approval_id;
6976
+ if (!id) {
6977
+ ctx.addIssue({
6978
+ code: "custom",
6979
+ message: "Approval response must include id"
6980
+ });
6981
+ return z.NEVER;
6982
+ }
6983
+ return { ...approval, id };
6862
6984
  });
6863
6985
  var PollApprovalResponseSchema = z.object({
6986
+ id: z.string().optional(),
6864
6987
  status: ApprovalStatusSchema,
6865
- approval_id: z.string()
6988
+ approval_id: z.string().optional(),
6989
+ mode: ApprovalModeSchema.optional(),
6990
+ reason: z.string().optional()
6866
6991
  });
6867
6992
  var APPROVAL_MAX_POLLING_INTERVAL_MS = 5e3;
6868
6993
  function parseRateLimitHeaders(response) {
@@ -7135,7 +7260,11 @@ var ZapierApiClient = class {
7135
7260
  { statusCode: 403 }
7136
7261
  );
7137
7262
  }
7138
- await this.runOneApprovalRound(init.approvalContext, mode);
7263
+ await this.runOneApprovalRound(
7264
+ init.approvalContext,
7265
+ mode,
7266
+ init.signal ?? void 0
7267
+ );
7139
7268
  }
7140
7269
  throw new ZapierApprovalError(
7141
7270
  `Exceeded maximum approval retries (${maxRetries}) for ${path}`,
@@ -7163,6 +7292,7 @@ var ZapierApiClient = class {
7163
7292
  * any frame), so transport / auth failures surface as usual.
7164
7293
  */
7165
7294
  this.fetchJsonStream = (path, init) => jsonFrames(this.fetchStream(path, init));
7295
+ this.streamTrustedJsonUrl = (url, init) => jsonFrames(this.streamTrustedSseUrl(url, init));
7166
7296
  this.get = async (path, options = {}) => {
7167
7297
  return this.fetchJson("GET", path, void 0, options);
7168
7298
  };
@@ -7502,7 +7632,7 @@ var ZapierApiClient = class {
7502
7632
  // bound `fetchStream` arrow above for parity with the other client methods.
7503
7633
  async *streamSse(path, init) {
7504
7634
  const { onOpen, headers: initHeaders, ...fetchInit } = init ?? {};
7505
- const signal = fetchInit.signal;
7635
+ const signal = fetchInit.signal ?? void 0;
7506
7636
  if (signal?.aborted) return;
7507
7637
  const wasMissingAuthToken = fetchInit.authRequired === true && await this.getAuthToken({
7508
7638
  requiredScopes: fetchInit.requiredScopes
@@ -7520,13 +7650,62 @@ var ZapierApiClient = class {
7520
7650
  if (signal?.aborted || isAbortError(err)) return;
7521
7651
  throw err;
7522
7652
  }
7653
+ yield* this.readSseResponse({
7654
+ response,
7655
+ signal,
7656
+ onOpen,
7657
+ wasMissingAuthToken,
7658
+ requiredScopes: fetchInit.requiredScopes
7659
+ });
7660
+ }
7661
+ // Approval `stream_url` is server-supplied and origin-pinned before use, like
7662
+ // `poll_url`; keep absolute-URL streaming private rather than widening the
7663
+ // public path-based `fetchStream` API.
7664
+ async *streamTrustedSseUrl(url, init) {
7665
+ const { onOpen, headers: initHeaders, ...fetchInit } = init ?? {};
7666
+ const signal = fetchInit.signal ?? void 0;
7667
+ if (signal?.aborted) return;
7668
+ const wasMissingAuthToken = fetchInit.authRequired === true && await this.getAuthToken({
7669
+ requiredScopes: fetchInit.requiredScopes
7670
+ }) == null;
7671
+ const headers = new Headers(initHeaders);
7672
+ if (!headers.has("Accept")) headers.set("Accept", "text/event-stream");
7673
+ let response;
7674
+ try {
7675
+ response = await this.withSemaphore(
7676
+ { url, method: fetchInit.method ?? "GET", signal },
7677
+ () => this.rawFetchUrl(url, {
7678
+ ...fetchInit,
7679
+ method: fetchInit.method ?? "GET",
7680
+ headers
7681
+ })
7682
+ );
7683
+ } catch (err) {
7684
+ if (signal?.aborted || isAbortError(err)) return;
7685
+ throw err;
7686
+ }
7687
+ yield* this.readSseResponse({
7688
+ response,
7689
+ signal,
7690
+ onOpen,
7691
+ wasMissingAuthToken,
7692
+ requiredScopes: fetchInit.requiredScopes
7693
+ });
7694
+ }
7695
+ async *readSseResponse({
7696
+ response,
7697
+ signal,
7698
+ onOpen,
7699
+ wasMissingAuthToken,
7700
+ requiredScopes
7701
+ }) {
7523
7702
  if (!response.ok) {
7524
7703
  const { data } = await this.parseResult(response);
7525
7704
  await this.throwForErrorResponse({
7526
7705
  response,
7527
7706
  responseData: data,
7528
7707
  wasMissingAuthToken,
7529
- requiredScopes: fetchInit.requiredScopes
7708
+ requiredScopes
7530
7709
  });
7531
7710
  }
7532
7711
  if (!response.body) return;
@@ -7552,12 +7731,12 @@ var ZapierApiClient = class {
7552
7731
  /**
7553
7732
  * Run a single approval round: create the approval, open the URL (poll mode)
7554
7733
  * or throw (throw mode), poll until resolved, and emit events. Throws on
7555
- * denied/timeout/unexpected status. Returns on approved.
7734
+ * denied/failed/timeout/unexpected status. Returns on approved.
7556
7735
  *
7557
7736
  * Caller is responsible for passing a non-"disabled" mode; this method
7558
7737
  * unconditionally creates an approval.
7559
7738
  */
7560
- async runOneApprovalRound(buildContext, mode) {
7739
+ async runOneApprovalRound(buildContext, mode, signal) {
7561
7740
  const context = buildContext();
7562
7741
  let approvalResponse;
7563
7742
  try {
@@ -7567,9 +7746,11 @@ var ZapierApiClient = class {
7567
7746
  "Content-Type": "application/json",
7568
7747
  Accept: "application/json"
7569
7748
  },
7570
- body: JSON.stringify({ context })
7749
+ body: JSON.stringify({ context }),
7750
+ signal
7571
7751
  });
7572
7752
  } catch (err) {
7753
+ if (isAbortError(err)) throw err;
7573
7754
  throw new ZapierApiError("Failed to create approval request", {
7574
7755
  statusCode: 0,
7575
7756
  cause: err
@@ -7622,6 +7803,9 @@ var ZapierApiClient = class {
7622
7803
  };
7623
7804
  if (!isLocalhostBaseUrl(this.options.baseUrl)) {
7624
7805
  assertApprovalOrigin(approval.poll_url, sdkapiOrigin, "poll_url");
7806
+ if (approval.stream_url) {
7807
+ assertApprovalOrigin(approval.stream_url, sdkapiOrigin, "stream_url");
7808
+ }
7625
7809
  assertApprovalOrigin(
7626
7810
  approval.approval_url,
7627
7811
  browserOrigin,
@@ -7629,19 +7813,79 @@ var ZapierApiClient = class {
7629
7813
  );
7630
7814
  }
7631
7815
  this.emitEvent("approval:required", {
7632
- approvalId: approval.approval_id,
7633
- approvalUrl: approval.approval_url
7816
+ approvalId: approval.id,
7817
+ approvalUrl: approval.approval_url,
7818
+ mode: approval.mode,
7819
+ ...approval.stream_url ? { streamUrl: approval.stream_url } : {}
7634
7820
  });
7635
- if (mode === "throw") {
7636
- throw new ZapierApprovalError("This request requires approval.", {
7637
- approvalId: approval.approval_id,
7638
- approvalUrl: approval.approval_url,
7639
- pollUrl: approval.poll_url,
7640
- status: "pending"
7641
- });
7821
+ const shouldOpenAutoModeApproval = this.options.openAutoModeApprovalsInBrowser ?? getZapierOpenAutoModeApprovalsInBrowser() ?? false;
7822
+ if (approval.mode === "auto") {
7823
+ if (shouldOpenAutoModeApproval) {
7824
+ await openApproval(approval.approval_url);
7825
+ }
7826
+ if (approval.status === "approved") {
7827
+ this.emitEvent("approval:approved", {
7828
+ approvalId: approval.id
7829
+ });
7830
+ return;
7831
+ }
7832
+ if (approval.status === "denied") {
7833
+ this.emitEvent("approval:denied", {
7834
+ approvalId: approval.id,
7835
+ ...approval.reason ? { reason: approval.reason } : {}
7836
+ });
7837
+ throw new ZapierApprovalError(
7838
+ approval.reason ? `Request denied: ${approval.reason}` : "Request denied by user",
7839
+ {
7840
+ approvalId: approval.id,
7841
+ status: "denied",
7842
+ reason: approval.reason
7843
+ }
7844
+ );
7845
+ }
7846
+ if (approval.status === "failed") {
7847
+ this.throwApprovalFailed({
7848
+ approvalId: approval.id,
7849
+ approvalUrl: approval.approval_url,
7850
+ pollUrl: approval.poll_url,
7851
+ streamUrl: approval.stream_url,
7852
+ reason: approval.reason
7853
+ });
7854
+ }
7855
+ } else {
7856
+ if (mode === "throw") {
7857
+ throw new ZapierApprovalError("This request requires approval.", {
7858
+ approvalId: approval.id,
7859
+ approvalUrl: approval.approval_url,
7860
+ pollUrl: approval.poll_url,
7861
+ streamUrl: approval.stream_url,
7862
+ status: "pending"
7863
+ });
7864
+ }
7865
+ await openApproval(approval.approval_url);
7642
7866
  }
7643
- await openApproval(approval.approval_url);
7644
7867
  const timeoutMs = this.options.approvalTimeoutMs ?? DEFAULT_APPROVAL_TIMEOUT_MS;
7868
+ let streamAbortController;
7869
+ let streamPromise;
7870
+ let removeStreamAbortListener;
7871
+ if (approval.mode === "auto" && approval.stream_url) {
7872
+ const streamUrl = approval.stream_url;
7873
+ streamAbortController = new AbortController();
7874
+ const abortStream = () => streamAbortController?.abort();
7875
+ if (signal?.aborted) {
7876
+ abortStream();
7877
+ } else if (signal) {
7878
+ signal.addEventListener("abort", abortStream, { once: true });
7879
+ removeStreamAbortListener = () => signal.removeEventListener("abort", abortStream);
7880
+ }
7881
+ streamPromise = consumeApprovalReviewStream({
7882
+ approvalId: approval.id,
7883
+ streamUrl,
7884
+ signal: streamAbortController.signal,
7885
+ stream: (url, streamInit) => this.streamTrustedJsonUrl(url, streamInit),
7886
+ emitEvent: (type, payload) => this.emitEvent(type, payload)
7887
+ });
7888
+ }
7645
7889
  let rawPollResult;
7646
7890
  try {
7647
7891
  rawPollResult = await pollUntilComplete({
@@ -7652,14 +7896,16 @@ var ZapierApiClient = class {
7652
7896
  // semaphore — but we deliberately do not hold a slot across the
7653
7897
  // sleep between polls or across the human-approval wait.
7654
7898
  fetchPoll: () => this.withSemaphore(
7655
- { url: approval.poll_url, method: "GET" },
7899
+ { url: approval.poll_url, method: "GET", signal },
7656
7900
  () => this.rawFetchUrl(approval.poll_url, {
7657
7901
  method: "GET",
7658
- headers: { Accept: "application/json" }
7902
+ headers: { Accept: "application/json" },
7903
+ signal
7659
7904
  })
7660
7905
  ),
7661
7906
  timeoutMs,
7662
7907
  maxPollingIntervalMs: APPROVAL_MAX_POLLING_INTERVAL_MS,
7908
+ signal,
7663
7909
  isPending: (body2) => {
7664
7910
  const parsed = PollApprovalResponseSchema.safeParse(body2);
7665
7911
  return parsed.success && parsed.data.status === "pending_approval";
@@ -7667,25 +7913,38 @@ var ZapierApiClient = class {
7667
7913
  });
7668
7914
  } catch (err) {
7669
7915
  if (!(err instanceof ZapierTimeoutError)) {
7916
+ this.emitEvent("approval:error", {
7917
+ approvalId: approval.id,
7918
+ message: err instanceof Error ? err.message : String(err)
7919
+ });
7670
7920
  throw err;
7671
7921
  }
7672
7922
  this.emitEvent("approval:timeout", {
7673
- approvalId: approval.approval_id
7923
+ approvalId: approval.id
7674
7924
  });
7675
7925
  throw new ZapierApprovalError(
7676
7926
  `Approval timed out after ${timeoutMs / 1e3} seconds`,
7677
7927
  {
7678
- approvalId: approval.approval_id,
7928
+ approvalId: approval.id,
7679
7929
  approvalUrl: approval.approval_url,
7680
7930
  pollUrl: approval.poll_url,
7931
+ streamUrl: approval.stream_url,
7681
7932
  status: "timeout",
7682
7933
  cause: err
7683
7934
  }
7684
7935
  );
7936
+ } finally {
7937
+ removeStreamAbortListener?.();
7938
+ streamAbortController?.abort();
7939
+ await streamPromise;
7685
7940
  }
7686
7941
  const pollParse = PollApprovalResponseSchema.safeParse(rawPollResult);
7687
7942
  if (!pollParse.success) {
7688
7943
  const bodyPreview = typeof rawPollResult === "string" ? rawPollResult : JSON.stringify(rawPollResult);
7944
+ this.emitEvent("approval:error", {
7945
+ approvalId: approval.id,
7946
+ message: `Failed to parse approval poll response: ${bodyPreview}`
7947
+ });
7689
7948
  throw new ZapierApiError(
7690
7949
  `Failed to parse approval poll response: ${bodyPreview}`,
7691
7950
  {
@@ -7698,21 +7957,62 @@ var ZapierApiClient = class {
7698
7957
  const pollResult = pollParse.data;
7699
7958
  if (pollResult.status === "denied") {
7700
7959
  this.emitEvent("approval:denied", {
7701
- approvalId: approval.approval_id
7960
+ approvalId: approval.id,
7961
+ ...pollResult.reason ? { reason: pollResult.reason } : {}
7702
7962
  });
7703
- throw new ZapierApprovalError("Request denied by user", {
7704
- approvalId: approval.approval_id,
7705
- status: "denied"
7963
+ throw new ZapierApprovalError(
7964
+ pollResult.reason ? `Request denied: ${pollResult.reason}` : "Request denied by user",
7965
+ {
7966
+ approvalId: approval.id,
7967
+ status: "denied",
7968
+ reason: pollResult.reason
7969
+ }
7970
+ );
7971
+ }
7972
+ if (pollResult.status === "failed") {
7973
+ this.throwApprovalFailed({
7974
+ approvalId: approval.id,
7975
+ approvalUrl: approval.approval_url,
7976
+ pollUrl: approval.poll_url,
7977
+ streamUrl: approval.stream_url,
7978
+ reason: pollResult.reason
7706
7979
  });
7707
7980
  }
7708
7981
  if (pollResult.status !== "approved") {
7982
+ this.emitEvent("approval:error", {
7983
+ approvalId: approval.id,
7984
+ message: `Unexpected approval status received: ${pollResult.status}`
7985
+ });
7709
7986
  throw new ZapierApiError(
7710
7987
  `Unexpected approval status received: ${pollResult.status}`
7711
7988
  );
7712
7989
  }
7713
7990
  this.emitEvent("approval:approved", {
7714
- approvalId: approval.approval_id
7991
+ approvalId: approval.id
7992
+ });
7993
+ }
7994
+ throwApprovalFailed({
7995
+ approvalId,
7996
+ approvalUrl,
7997
+ pollUrl,
7998
+ streamUrl,
7999
+ reason
8000
+ }) {
8001
+ this.emitEvent("approval:failed", {
8002
+ approvalId,
8003
+ ...reason ? { reason } : {}
7715
8004
  });
8005
+ throw new ZapierApprovalError(
8006
+ reason ? `Approval failed: ${reason}` : "Approval failed",
8007
+ {
8008
+ approvalId,
8009
+ approvalUrl,
8010
+ pollUrl,
8011
+ streamUrl,
8012
+ status: "failed",
8013
+ reason
8014
+ }
8015
+ );
7716
8016
  }
7717
8017
  };
7718
8018
  var createZapierApi = (options) => {
@@ -7774,6 +8074,7 @@ var apiPlugin = definePlugin(
7774
8074
  approvalTimeoutMs,
7775
8075
  maxApprovalRetries,
7776
8076
  approvalMode,
8077
+ openAutoModeApprovalsInBrowser,
7777
8078
  callerPackage
7778
8079
  } = sdk.context.options;
7779
8080
  const api = createZapierApi({
@@ -7789,6 +8090,7 @@ var apiPlugin = definePlugin(
7789
8090
  approvalTimeoutMs,
7790
8091
  maxApprovalRetries,
7791
8092
  approvalMode,
8093
+ openAutoModeApprovalsInBrowser,
7792
8094
  callerPackage
7793
8095
  });
7794
8096
  return {
@@ -8781,6 +9083,260 @@ var zapierCorePlugin = createCorePlugin({
8781
9083
  function createZapierCoreStack() {
8782
9084
  return createPluginStack().use(zapierCorePlugin);
8783
9085
  }
9086
+ var GetConnectionStartUrlSchema = z.object({
9087
+ app: AppPropertySchema
9088
+ }).describe(
9089
+ "Mint a short-lived URL that begins an SDK-initiated connection flow. The URL is signed by zapier.com and bound to the current user/account \u2014 opening it in a different browser session will fail the binding check. Returns the URL as data so the caller decides what to do with it.\n\nUse this directly (rather than the higher-level `create-connection`) when you want either of: (a) hand off the URL and *not* block waiting for completion \u2014 call this alone, skip `wait-for-new-connection` entirely, or (b) do something custom between minting the URL and waiting for the connection \u2014 call this, then email or DM the URL, render it as a QR code for mobile sign-in, etc., then call `wait-for-new-connection`. For the common case where you'd just print and poll back-to-back, `create-connection` is one call.\n\nPair with `wait-for-new-connection` to detect completion: pass the `startedAt` returned here straight through (it's the server's mint time, so polling isn't affected by client clock skew). Example (JS):\n\n```ts\nconst { data: { url, app, startedAt } } = await zapier.getConnectionStartUrl({ app: 'slack' });\n// hand `url` off \u2014 print it, DM it, email it, render a button, whatever\nconst { data: conn } = await zapier.waitForNewConnection({ app, startedAt });\n```"
9090
+ );
9091
+ var GetConnectionStartUrlItemSchema = z.object({
9092
+ url: z.string().describe(
9093
+ "URL the user should open in their browser to complete the auth flow. Single-use, time-limited."
9094
+ ),
9095
+ expiresAt: z.number().describe(
9096
+ "Unix timestamp (seconds) after which the URL's signature is rejected by zapier.com."
9097
+ ),
9098
+ startedAt: z.number().describe(
9099
+ "Unix timestamp (seconds) when the server minted the URL. Use it as the `startedAt` for `wait-for-new-connection` so polling is anchored to server time rather than a possibly-skewed client clock."
9100
+ ),
9101
+ app: z.string().describe(
9102
+ "Versionless app key the URL was minted for (e.g., 'SlackCLIAPI'). Useful for downstream filtering."
9103
+ )
9104
+ }).describe(
9105
+ "The signed start-URL plus metadata needed to poll for completion."
9106
+ );
9107
+
9108
+ // src/plugins/getConnectionStartUrl/index.ts
9109
+ var START_PATH = "/zapier/api/authentications/v1/sdk/connections/start";
9110
+ var getConnectionStartUrlPlugin = definePlugin(
9111
+ (sdk) => createPluginMethod(sdk, {
9112
+ name: "getConnectionStartUrl",
9113
+ categories: ["connection"],
9114
+ type: "create",
9115
+ itemType: "ConnectionStartUrl",
9116
+ inputSchema: GetConnectionStartUrlSchema,
9117
+ outputSchema: GetConnectionStartUrlItemSchema,
9118
+ resolvers: { app: appKeyResolver },
9119
+ handler: async ({
9120
+ sdk: inner,
9121
+ options
9122
+ }) => {
9123
+ const versionedKey = await inner.context.getVersionedImplementationId(
9124
+ options.app
9125
+ );
9126
+ const selectedApi = versionedKey ? versionedKey.split("@")[0] : options.app;
9127
+ setMethodMetadata({ selectedApi });
9128
+ const response = await inner.context.api.post(
9129
+ START_PATH,
9130
+ { selected_api: selectedApi },
9131
+ { authRequired: true }
9132
+ );
9133
+ return {
9134
+ data: GetConnectionStartUrlItemSchema.parse({
9135
+ url: response.url,
9136
+ expiresAt: response.expires_at,
9137
+ startedAt: response.started_at,
9138
+ app: selectedApi
9139
+ })
9140
+ };
9141
+ }
9142
+ })
9143
+ );
9144
+ var WaitForNewConnectionSchema = z.object({
9145
+ app: AppPropertySchema,
9146
+ startedAt: z.number().int().nonnegative().describe(
9147
+ "Unix timestamp (seconds). Only connections whose `date` is at or after this value count as 'new'. Prefer the `startedAt` returned by `get-connection-start-url` \u2014 it's server-stamped, so the comparison isn't thrown off by client clock skew. If you mint the timestamp yourself, capture it *before* showing the start URL so a fast OAuth completion isn't missed."
9148
+ ),
9149
+ timeoutMs: z.number().int().positive().optional().describe(
9150
+ "How long to wait before giving up. Default 5 minutes (300_000)."
9151
+ ),
9152
+ pollIntervalMs: z.number().int().positive().optional().describe(
9153
+ "Delay before the first poll request, in ms. Default 3 seconds (3_000). Subsequent polling cadence is managed by the SDK's polling primitive (backoff with sane defaults)."
9154
+ )
9155
+ }).describe(
9156
+ "Wait for a new connection to appear for the given app. Polls `/api/v0/connections` with server-side `ordering=-date` until the most recent matching row's `date` is at or after the started-at timestamp, then returns it. Pair with `get-connection-start-url` \u2014 that mints the URL the user opens, this waits for the resulting connection to land. Errors with a timeout after the configured timeout (default 5 min). Example (JS):\n\n```ts\nconst { data: { url, app, startedAt } } = await zapier.getConnectionStartUrl({ app: 'slack' });\n// show `url` to the user via the channel they're reading from\nconst { data: conn } = await zapier.waitForNewConnection({ app, startedAt });\n```"
9157
+ );
9158
+ var WaitForNewConnectionItemSchema = z.object({
9159
+ id: z.string().describe(
9160
+ "The new connection's ID. Public UUID when available, falling back to the numeric ID."
9161
+ ),
9162
+ app: z.string().describe(
9163
+ "Versionless app key the connection was created for (e.g., 'SlackCLIAPI')."
9164
+ ),
9165
+ title: z.string().nullable().optional().describe(
9166
+ "Human-readable connection title set by the auth flow, when available."
9167
+ )
9168
+ }).describe("The new connection that was detected.");
9169
+
9170
+ // src/plugins/waitForNewConnection/index.ts
9171
+ var CONNECTIONS_PATH = "/api/v0/connections";
9172
+ var waitForNewConnectionPlugin = definePlugin(
9173
+ (sdk) => createPluginMethod(sdk, {
9174
+ name: "waitForNewConnection",
9175
+ categories: ["connection"],
9176
+ type: "item",
9177
+ itemType: "Connection",
9178
+ inputSchema: WaitForNewConnectionSchema,
9179
+ outputSchema: WaitForNewConnectionItemSchema,
9180
+ resolvers: { app: appKeyResolver },
9181
+ handler: async ({
9182
+ sdk: inner,
9183
+ options
9184
+ }) => {
9185
+ const versionedKey = await inner.context.getVersionedImplementationId(
9186
+ options.app
9187
+ );
9188
+ const appKey = versionedKey ? versionedKey.split("@")[0] : options.app;
9189
+ setMethodMetadata({ selectedApi: appKey });
9190
+ try {
9191
+ const top = await inner.context.api.poll(
9192
+ CONNECTIONS_PATH,
9193
+ {
9194
+ searchParams: {
9195
+ app_key: appKey,
9196
+ // Scope to the current user's own connections. The connection
9197
+ // we're waiting on is by definition owned by the caller; without
9198
+ // this the one-row head-check could match a teammate's freshly
9199
+ // created connection for the same app.
9200
+ owner: "me",
9201
+ is_expired: "false",
9202
+ ordering: "-date",
9203
+ page_size: "1"
9204
+ },
9205
+ authRequired: true,
9206
+ timeoutMs: options.timeoutMs ?? 3e5,
9207
+ initialDelay: options.pollIntervalMs ?? 3e3,
9208
+ isPending: (body) => {
9209
+ const rows = body.data ?? [];
9210
+ const head = rows[0];
9211
+ if (!head?.date) return true;
9212
+ const created = Math.floor(new Date(head.date).getTime() / 1e3);
9213
+ return !Number.isFinite(created) || created < options.startedAt;
9214
+ },
9215
+ resultExtractor: (body) => (
9216
+ // `isPending` guaranteed a fresh row at index 0 before this fires.
9217
+ body.data[0]
9218
+ )
9219
+ }
9220
+ );
9221
+ return {
9222
+ data: WaitForNewConnectionItemSchema.parse({
9223
+ id: String(top.public_id ?? top.id),
9224
+ app: appKey,
9225
+ title: top.title ?? null
9226
+ })
9227
+ };
9228
+ } catch (err) {
9229
+ if (err instanceof ZapierTimeoutError) {
9230
+ throw new ZapierTimeoutError(
9231
+ `Timed out waiting for a new "${appKey}" connection. If the user completed the auth flow, retrieve the connection via sdk.getConnection({ id }) with the ID shown on the completion page.`
9232
+ );
9233
+ }
9234
+ throw err;
9235
+ }
9236
+ }
9237
+ })
9238
+ );
9239
+
9240
+ // src/utils/should-open-browser.ts
9241
+ function shouldOpenBrowser() {
9242
+ if (isCiEnv()) return false;
9243
+ const env = globalThis.process?.env;
9244
+ if (env?.SSH_TTY || env?.SSH_CONNECTION) return false;
9245
+ if (globalThis.process?.platform === "linux" && !env?.DISPLAY && !env?.WAYLAND_DISPLAY) {
9246
+ return false;
9247
+ }
9248
+ return true;
9249
+ }
9250
+ function isCiEnv() {
9251
+ const env = globalThis.process?.env;
9252
+ return !!(env?.CI || env?.CONTINUOUS_INTEGRATION || env?.GITHUB_ACTIONS || env?.JENKINS_URL || env?.GITLAB_CI || env?.CIRCLECI || env?.TRAVIS || env?.BUILDKITE || env?.DRONE || env?.BITBUCKET_PIPELINES_UUID);
9253
+ }
9254
+ var CreateConnectionSchema = z.object({
9255
+ app: AppPropertySchema,
9256
+ browser: z.enum(["auto", "always", "never"]).default("auto").describe(
9257
+ "When to auto-open the URL in a browser. `auto` (default) opens in local sessions and skips opening in CI / SSH / headless-Linux. `always` forces the open attempt. `never` skips it. The URL is always printed to stderr regardless \u2014 a failed or skipped open degrades gracefully to copy-paste."
9258
+ ),
9259
+ timeoutMs: z.number().int().positive().optional().describe(
9260
+ "How long to wait for the user to complete the connection flow before giving up. Default 5 minutes (300_000)."
9261
+ ),
9262
+ pollIntervalMs: z.number().int().positive().optional().describe(
9263
+ "Delay before the first poll request, in ms. Default 3 seconds (3_000). Subsequent polling cadence is managed by the SDK's polling primitive (backoff with sane defaults)."
9264
+ )
9265
+ }).describe(
9266
+ "Create a new app connection, end-to-end. Mints the start URL via `get-connection-start-url`, prints it to stderr, opportunistically opens it in a browser when it looks safe to do so (skipping CI / SSH / headless-Linux by default \u2014 pass `--browser always` to force, `--browser never` to suppress), then polls via `wait-for-new-connection` until the user completes OAuth and the new connection appears. Returns the connection.\n\nThis is the right command for most callers. Reach for the lower-level building blocks when you want either of: (a) hand off the URL and *not* block on completion \u2014 call `get-connection-start-url` alone, no `wait-for-new-connection` needed, or (b) do something custom between minting the URL and waiting \u2014 call `get-connection-start-url`, do your work (email or DM the URL, render a QR code, etc.), then `wait-for-new-connection`."
9267
+ );
9268
+ var CreateConnectionItemSchema = z.object({
9269
+ id: z.string().describe(
9270
+ "The new connection's ID. Public UUID when available, falling back to the numeric ID."
9271
+ ),
9272
+ app: z.string().describe(
9273
+ "Versionless app key the connection was created for (e.g., 'SlackCLIAPI')."
9274
+ ),
9275
+ title: z.string().nullable().optional().describe(
9276
+ "Human-readable connection title set by the auth flow, when available."
9277
+ )
9278
+ }).describe("The newly created connection.");
9279
+
9280
+ // src/plugins/createConnection/index.ts
9281
+ var createConnectionPlugin = definePlugin(
9282
+ (sdk) => createPluginMethod(sdk, {
9283
+ name: "createConnection",
9284
+ categories: ["connection"],
9285
+ type: "create",
9286
+ itemType: "Connection",
9287
+ inputSchema: CreateConnectionSchema,
9288
+ outputSchema: CreateConnectionItemSchema,
9289
+ resolvers: { app: appKeyResolver },
9290
+ formatter: {
9291
+ format: (item) => ({
9292
+ title: `Connection created: ${item.title || item.id}`,
9293
+ id: item.id,
9294
+ details: [
9295
+ { text: `App: ${item.app}`, style: "normal" },
9296
+ { text: `ID: ${item.id}`, style: "accent" }
9297
+ ]
9298
+ })
9299
+ },
9300
+ handler: async ({
9301
+ sdk: inner,
9302
+ options
9303
+ }) => {
9304
+ const { data: start } = await inner.getConnectionStartUrl({
9305
+ app: options.app
9306
+ });
9307
+ setMethodMetadata({ selectedApi: start.app });
9308
+ console.error(
9309
+ `
9310
+ Open this URL to complete the connection:
9311
+ ${start.url}
9312
+ `
9313
+ );
9314
+ const shouldOpen = options.browser === "always" || options.browser === "auto" && shouldOpenBrowser();
9315
+ if (shouldOpen) {
9316
+ try {
9317
+ await open_url_default(start.url);
9318
+ } catch {
9319
+ }
9320
+ }
9321
+ const { data: fresh } = await inner.waitForNewConnection({
9322
+ app: start.app,
9323
+ // Server-stamped mint time: measured on the same clock as a
9324
+ // connection's `date`, so the freshness check is immune to
9325
+ // client/server clock skew.
9326
+ startedAt: start.startedAt,
9327
+ timeoutMs: options.timeoutMs,
9328
+ pollIntervalMs: options.pollIntervalMs
9329
+ });
9330
+ return {
9331
+ data: CreateConnectionItemSchema.parse({
9332
+ id: fresh.id,
9333
+ app: start.app,
9334
+ title: fresh.title ?? null
9335
+ })
9336
+ };
9337
+ }
9338
+ })
9339
+ );
8784
9340
 
8785
9341
  // src/plugins/deprecated/authentications.ts
8786
9342
  var listAuthenticationsPlugin = definePlugin(
@@ -9636,7 +10192,7 @@ function createZapierSdkWithoutRegistry(options = {}) {
9636
10192
  return createZapierSdk(options);
9637
10193
  }
9638
10194
  function createZapierSdkStack(options = {}) {
9639
- 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(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).use(getProfilePlugin);
10195
+ 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).use(getProfilePlugin);
9640
10196
  }
9641
10197
  function createZapierSdk(options = {}) {
9642
10198
  return withDeprecatedAddPlugin(createZapierSdkStack(options).toSdk());
@@ -9682,7 +10238,10 @@ var BaseSdkOptionsSchema = z.object({
9682
10238
  "Maximum number of sequential approval rounds per request (one per gating policy) before giving up. Default: 2."
9683
10239
  ),
9684
10240
  approvalMode: z.enum(["disabled", "poll", "throw"]).optional().describe(
9685
- 'Approval flow behavior. "poll" creates the approval, opens it in a browser, polls until resolved, and retries the original request. "throw" creates the approval and throws a ZapierApprovalError with the approval URL so the caller can surface it. "disabled" throws a ZapierApprovalError on approval-required responses without creating an approval. Resolution order is: explicit option, then ZAPIER_APPROVAL_MODE, then the default behavior (poll for interactive TTY, throw otherwise).'
10241
+ 'Approval flow behavior for manual approvals. "poll" creates the approval, opens it in a browser, polls until resolved, and retries the original request. "throw" creates the manual approval and throws a ZapierApprovalError with the approval URL so the caller can surface it. Server-created auto-mode approvals always poll until they reach a terminal status and retry the original request on approval, even when this option is "throw". "disabled" throws a ZapierApprovalError on approval-required responses without creating an approval. Resolution order is: explicit option, then ZAPIER_APPROVAL_MODE, then the default behavior (poll for interactive TTY, throw otherwise).'
10242
+ ),
10243
+ openAutoModeApprovalsInBrowser: z.boolean().optional().describe(
10244
+ "By default, auto-mode approvals do not open in a browser. Enable this option to open the approval URL and watch the approval process. Resolution order is: explicit option, then ZAPIER_OPEN_AUTO_MODE_APPROVALS_IN_BROWSER, then false."
9686
10245
  ),
9687
10246
  // Internal
9688
10247
  manifestPath: z.string().optional().describe("Path to a .zapierrc manifest file for app version locking.").meta({ internal: true }),
@@ -9708,4 +10267,4 @@ var registryPlugin = definePlugin((_sdk) => {
9708
10267
  return {};
9709
10268
  });
9710
10269
 
9711
- export { ActionKeyPropertySchema, ActionPropertySchema, ActionTimeoutMsPropertySchema, ActionTypePropertySchema, AppKeyPropertySchema, AppPropertySchema, AppsPropertySchema, AuthenticationIdPropertySchema, BaseSdkOptionsSchema, CONTEXT_CACHE_MAX_SIZE, CONTEXT_CACHE_TTL_MS, CORE_ERROR_SYMBOL, ClientCredentialsObjectSchema, ConnectionEntrySchema, ConnectionIdPropertySchema, ConnectionPropertySchema, ConnectionsMapSchema, ConnectionsPropertySchema, CoreErrorCode, CredentialsFunctionSchema, CredentialsObjectSchema, CredentialsSchema, DEFAULT_ACTION_TIMEOUT_MS, DEFAULT_APPROVAL_TIMEOUT_MS, DEFAULT_CONFIG_PATH, DEFAULT_MAX_APPROVAL_RETRIES, DEFAULT_PAGE_SIZE, DebugPropertySchema, FieldsPropertySchema, InputFieldPropertySchema, InputsPropertySchema, LeaseLimitPropertySchema, LeasePropertySchema, LeaseSecondsPropertySchema, LimitPropertySchema, MAX_CONCURRENCY_LIMIT, MAX_PAGE_LIMIT, OffsetPropertySchema, OutputPropertySchema, ParamsPropertySchema, PkceCredentialsObjectSchema, RecordPropertySchema, RecordsPropertySchema, RelayFetchSchema, RelayRequestSchema, ResolvedCredentialsSchema, TablePropertySchema, TablesPropertySchema, TriggerInboxNamePropertySchema, TriggerInboxPropertySchema, ZAPIER_BASE_URL, ZAPIER_MAX_CONCURRENT_REQUESTS, ZAPIER_MAX_NETWORK_RETRIES, ZAPIER_MAX_NETWORK_RETRY_DELAY_MS, ZapierAbortDrainSignal, ZapierActionError, ZapierApiError, ZapierAppNotFoundError, ZapierApprovalError, ZapierAuthenticationError, ZapierBundleError, ZapierConfigurationError, ZapierConflictError, ZapierError, ZapierNotFoundError, ZapierRateLimitError, ZapierRelayError, ZapierReleaseTriggerMessageSignal, ZapierResourceNotFoundError, ZapierSignal, ZapierTimeoutError, ZapierUnknownError, ZapierValidationError, actionKeyResolver, actionTypeResolver, addPlugin, apiPlugin, appKeyResolver, appsPlugin, connectionIdGenericResolver as authenticationIdGenericResolver, connectionIdResolver as authenticationIdResolver, batch, buildApplicationLifecycleEvent, buildCapabilityMessage, buildErrorEvent, buildErrorEventWithContext, buildMethodCalledEvent, cleanupEventListeners, clearTokenCache, clientCredentialsNameResolver, clientIdResolver, composePlugins, connectionIdGenericResolver, connectionIdResolver, connectionsPlugin, createBaseEvent, createClientCredentialsPlugin, createCorePlugin, createFunction, createMemoryCache, createOptionsPlugin, createPaginatedPluginMethod, createPluginMethod, createPluginStack, createSdk, createTableFieldsPlugin, createTablePlugin, createTableRecordsPlugin, createZapierApi, createZapierCoreStack, createZapierSdk, createZapierSdkStack, createZapierSdkWithoutRegistry, definePlugin, deleteClientCredentialsPlugin, deleteTableFieldsPlugin, deleteTablePlugin, deleteTableRecordsPlugin, durableRunIdResolver, eventEmissionPlugin, fetchPlugin, findFirstConnectionPlugin, findManifestEntry, findUniqueConnectionPlugin, formatErrorMessage, generateEventId, getActionInputFieldsSchemaPlugin, getActionPlugin, getAgent, getAppPlugin, getBaseUrlFromCredentials, getCiPlatform, getClientIdFromCredentials, getConnectionPlugin, getCoreErrorCause, getCoreErrorCode, getCpuTime, getCurrentTimestamp, getMemoryUsage, getOrCreateApiClient, getOsInfo, getPlatformVersions, getPreferredManifestEntryKey, getProfilePlugin, getReleaseId, getTablePlugin, getTableRecordPlugin, getTokenFromCliLogin, getTtyContext, getZapierApprovalMode, getZapierDefaultApprovalMode, getZapierSdkService, injectCliLogin, inputFieldKeyResolver, inputsAllOptionalResolver, inputsResolver, invalidateCachedToken, invalidateCredentialsToken, isCi, isCliLoginAvailable, isClientCredentials, isCoreError, isCredentialsFunction, isCredentialsObject, isPermanentHttpError, isPkceCredentials, isPositional, listActionInputFieldChoicesPlugin, listActionInputFieldsPlugin, listActionsPlugin, listAppsPlugin, listClientCredentialsPlugin, listConnectionsPlugin, listTableFieldsPlugin, listTableRecordsPlugin, listTablesPlugin, logDeprecation2 as logDeprecation, manifestPlugin, parseConcurrencyEnvVar, readManifestFromFile, registryPlugin, requestPlugin, resetDeprecationWarnings2 as resetDeprecationWarnings, resolveAuthToken, resolveCredentials, resolveCredentialsFromEnv, runActionPlugin, runInMethodScope, runWithTelemetryContext, tableFieldIdsResolver, tableFieldsResolver, tableFiltersResolver, tableIdResolver, tableNameResolver, tableRecordIdResolver, tableRecordIdsResolver, tableRecordsResolver, tableSortResolver, tableUpdateRecordsResolver, toSnakeCase, toTitleCase, triggerInboxResolver, triggerMessagesResolver, updateTableRecordsPlugin, workflowIdResolver, workflowRunIdResolver, workflowVersionIdResolver, zapierAdaptError };
10270
+ export { ActionKeyPropertySchema, ActionPropertySchema, ActionTimeoutMsPropertySchema, ActionTypePropertySchema, AppKeyPropertySchema, AppPropertySchema, AppsPropertySchema, AuthenticationIdPropertySchema, BaseSdkOptionsSchema, CONTEXT_CACHE_MAX_SIZE, CONTEXT_CACHE_TTL_MS, CORE_ERROR_SYMBOL, ClientCredentialsObjectSchema, ConnectionEntrySchema, ConnectionIdPropertySchema, ConnectionPropertySchema, ConnectionsMapSchema, ConnectionsPropertySchema, CoreErrorCode, CredentialsFunctionSchema, CredentialsObjectSchema, CredentialsSchema, DEFAULT_ACTION_TIMEOUT_MS, DEFAULT_APPROVAL_TIMEOUT_MS, DEFAULT_CONFIG_PATH, DEFAULT_MAX_APPROVAL_RETRIES, DEFAULT_PAGE_SIZE, DebugPropertySchema, FieldsPropertySchema, InputFieldPropertySchema, InputsPropertySchema, LeaseLimitPropertySchema, LeasePropertySchema, LeaseSecondsPropertySchema, LimitPropertySchema, MAX_CONCURRENCY_LIMIT, MAX_PAGE_LIMIT, OffsetPropertySchema, OutputPropertySchema, ParamsPropertySchema, PkceCredentialsObjectSchema, RecordPropertySchema, RecordsPropertySchema, RelayFetchSchema, RelayRequestSchema, ResolvedCredentialsSchema, TablePropertySchema, TablesPropertySchema, TriggerInboxNamePropertySchema, TriggerInboxPropertySchema, ZAPIER_BASE_URL, ZAPIER_MAX_CONCURRENT_REQUESTS, ZAPIER_MAX_NETWORK_RETRIES, ZAPIER_MAX_NETWORK_RETRY_DELAY_MS, ZapierAbortDrainSignal, ZapierActionError, ZapierApiError, ZapierAppNotFoundError, ZapierApprovalError, ZapierAuthenticationError, ZapierBundleError, ZapierConfigurationError, ZapierConflictError, ZapierError, ZapierNotFoundError, ZapierRateLimitError, ZapierRelayError, ZapierReleaseTriggerMessageSignal, ZapierResourceNotFoundError, ZapierSignal, ZapierTimeoutError, ZapierUnknownError, ZapierValidationError, actionKeyResolver, actionTypeResolver, addPlugin, apiPlugin, appKeyResolver, appsPlugin, connectionIdGenericResolver as authenticationIdGenericResolver, connectionIdResolver as authenticationIdResolver, batch, buildApplicationLifecycleEvent, buildCapabilityMessage, buildErrorEvent, buildErrorEventWithContext, buildMethodCalledEvent, cleanupEventListeners, clearTokenCache, clientCredentialsNameResolver, clientIdResolver, composePlugins, connectionIdGenericResolver, connectionIdResolver, connectionsPlugin, createBaseEvent, createClientCredentialsPlugin, createCorePlugin, createFunction, createMemoryCache, createOptionsPlugin, createPaginatedPluginMethod, createPluginMethod, createPluginStack, createSdk, createTableFieldsPlugin, createTablePlugin, createTableRecordsPlugin, createZapierApi, createZapierCoreStack, createZapierSdk, createZapierSdkStack, createZapierSdkWithoutRegistry, definePlugin, deleteClientCredentialsPlugin, deleteTableFieldsPlugin, deleteTablePlugin, deleteTableRecordsPlugin, durableRunIdResolver, eventEmissionPlugin, fetchPlugin, findFirstConnectionPlugin, findManifestEntry, findUniqueConnectionPlugin, formatErrorMessage, generateEventId, getActionInputFieldsSchemaPlugin, getActionPlugin, getAgent, getAppPlugin, getBaseUrlFromCredentials, getCiPlatform, getClientIdFromCredentials, getConnectionPlugin, getCoreErrorCause, getCoreErrorCode, getCpuTime, getCurrentTimestamp, getMemoryUsage, getOrCreateApiClient, getOsInfo, getPlatformVersions, getPreferredManifestEntryKey, getProfilePlugin, getReleaseId, getTablePlugin, getTableRecordPlugin, getTokenFromCliLogin, getTtyContext, getZapierApprovalMode, getZapierDefaultApprovalMode, getZapierOpenAutoModeApprovalsInBrowser, getZapierSdkService, injectCliLogin, inputFieldKeyResolver, inputsAllOptionalResolver, inputsResolver, invalidateCachedToken, invalidateCredentialsToken, isCi, isCliLoginAvailable, isClientCredentials, isCoreError, isCredentialsFunction, isCredentialsObject, isPermanentHttpError, isPkceCredentials, isPositional, listActionInputFieldChoicesPlugin, listActionInputFieldsPlugin, listActionsPlugin, listAppsPlugin, listClientCredentialsPlugin, listConnectionsPlugin, listTableFieldsPlugin, listTableRecordsPlugin, listTablesPlugin, logDeprecation2 as logDeprecation, manifestPlugin, parseConcurrencyEnvVar, readManifestFromFile, registryPlugin, requestPlugin, resetDeprecationWarnings2 as resetDeprecationWarnings, resolveAuthToken, resolveCredentials, resolveCredentialsFromEnv, runActionPlugin, runInMethodScope, runWithTelemetryContext, tableFieldIdsResolver, tableFieldsResolver, tableFiltersResolver, tableIdResolver, tableNameResolver, tableRecordIdResolver, tableRecordIdsResolver, tableRecordsResolver, tableSortResolver, tableUpdateRecordsResolver, toSnakeCase, toTitleCase, triggerInboxResolver, triggerMessagesResolver, updateTableRecordsPlugin, workflowIdResolver, workflowRunIdResolver, workflowVersionIdResolver, zapierAdaptError };