@zapier/zapier-sdk 0.70.4 → 0.71.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.
Files changed (81) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +149 -31
  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 +602 -37
  14. package/dist/experimental.d.mts +88 -2
  15. package/dist/experimental.d.ts +90 -4
  16. package/dist/experimental.d.ts.map +1 -1
  17. package/dist/experimental.js +10 -0
  18. package/dist/experimental.mjs +602 -38
  19. package/dist/{index-BNaiNmM-.d.mts → index-B43uST61.d.mts} +181 -12
  20. package/dist/{index-BNaiNmM-.d.ts → index-B43uST61.d.ts} +181 -12
  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/createWorkflow/index.d.ts +1 -0
  27. package/dist/plugins/codeSubstrate/createWorkflow/index.d.ts.map +1 -1
  28. package/dist/plugins/codeSubstrate/createWorkflow/index.js +3 -2
  29. package/dist/plugins/codeSubstrate/createWorkflow/schemas.d.ts +1 -0
  30. package/dist/plugins/codeSubstrate/createWorkflow/schemas.d.ts.map +1 -1
  31. package/dist/plugins/codeSubstrate/createWorkflow/schemas.js +7 -1
  32. package/dist/plugins/codeSubstrate/deleteWorkflow/index.d.ts +1 -1
  33. package/dist/plugins/codeSubstrate/disableWorkflow/index.d.ts +1 -1
  34. package/dist/plugins/codeSubstrate/enableWorkflow/index.d.ts +1 -1
  35. package/dist/plugins/codeSubstrate/getDurableRun/schemas.d.ts +4 -4
  36. package/dist/plugins/codeSubstrate/getWorkflow/index.d.ts +2 -2
  37. package/dist/plugins/codeSubstrate/getWorkflow/schemas.d.ts +1 -1
  38. package/dist/plugins/codeSubstrate/getWorkflowRun/index.d.ts +1 -1
  39. package/dist/plugins/codeSubstrate/getWorkflowVersion/index.d.ts +1 -1
  40. package/dist/plugins/codeSubstrate/listWorkflowRuns/index.d.ts +1 -1
  41. package/dist/plugins/codeSubstrate/listWorkflowVersions/index.d.ts +1 -1
  42. package/dist/plugins/codeSubstrate/listWorkflows/index.d.ts +1 -1
  43. package/dist/plugins/codeSubstrate/listWorkflows/schemas.d.ts +2 -2
  44. package/dist/plugins/codeSubstrate/publishWorkflowVersion/index.d.ts +1 -1
  45. package/dist/plugins/codeSubstrate/runDurable/schemas.js +1 -1
  46. package/dist/plugins/codeSubstrate/shared-schemas.d.ts +2 -2
  47. package/dist/plugins/codeSubstrate/triggerWorkflow/index.d.ts +1 -1
  48. package/dist/plugins/codeSubstrate/updateWorkflow/index.d.ts +1 -1
  49. package/dist/plugins/createConnection/index.d.ts +189 -0
  50. package/dist/plugins/createConnection/index.d.ts.map +1 -0
  51. package/dist/plugins/createConnection/index.js +71 -0
  52. package/dist/plugins/createConnection/schemas.d.ts +21 -0
  53. package/dist/plugins/createConnection/schemas.d.ts.map +1 -0
  54. package/dist/plugins/createConnection/schemas.js +38 -0
  55. package/dist/plugins/getConnectionStartUrl/index.d.ts +206 -0
  56. package/dist/plugins/getConnectionStartUrl/index.d.ts.map +1 -0
  57. package/dist/plugins/getConnectionStartUrl/index.js +39 -0
  58. package/dist/plugins/getConnectionStartUrl/schemas.d.ts +15 -0
  59. package/dist/plugins/getConnectionStartUrl/schemas.d.ts.map +1 -0
  60. package/dist/plugins/getConnectionStartUrl/schemas.js +23 -0
  61. package/dist/plugins/waitForNewConnection/index.d.ts +209 -0
  62. package/dist/plugins/waitForNewConnection/index.d.ts.map +1 -0
  63. package/dist/plugins/waitForNewConnection/index.js +75 -0
  64. package/dist/plugins/waitForNewConnection/schemas.d.ts +17 -0
  65. package/dist/plugins/waitForNewConnection/schemas.d.ts.map +1 -0
  66. package/dist/plugins/waitForNewConnection/schemas.js +39 -0
  67. package/dist/sdk.d.ts +126 -0
  68. package/dist/sdk.d.ts.map +1 -1
  69. package/dist/sdk.js +8 -0
  70. package/dist/types/errors.d.ts +13 -4
  71. package/dist/types/errors.d.ts.map +1 -1
  72. package/dist/types/errors.js +2 -0
  73. package/dist/types/sdk.d.ts +1 -0
  74. package/dist/types/sdk.d.ts.map +1 -1
  75. package/dist/types/sdk.js +5 -1
  76. package/dist/utils/open-url.d.ts.map +1 -1
  77. package/dist/utils/open-url.js +7 -0
  78. package/dist/utils/should-open-browser.d.ts +24 -0
  79. package/dist/utils/should-open-browser.d.ts.map +1 -0
  80. package/dist/utils/should-open-browser.js +55 -0
  81. package/package.json +1 -1
@@ -1168,6 +1168,8 @@ var ZapierApprovalError = class extends ZapierError {
1168
1168
  this.approvalStatus = options.status;
1169
1169
  this.approvalUrl = options.approvalUrl;
1170
1170
  this.pollUrl = options.pollUrl;
1171
+ this.streamUrl = options.streamUrl;
1172
+ this.reason = options.reason;
1171
1173
  }
1172
1174
  };
1173
1175
  var ZapierRelayError = class extends ZapierError {
@@ -1310,6 +1312,11 @@ function getZapierApprovalMode() {
1310
1312
  return value;
1311
1313
  return void 0;
1312
1314
  }
1315
+ function getZapierOpenAutoModeApprovalsInBrowser() {
1316
+ const value = globalThis.process?.env?.ZAPIER_OPEN_AUTO_MODE_APPROVALS_IN_BROWSER;
1317
+ if (value === void 0) return void 0;
1318
+ return value === "true";
1319
+ }
1313
1320
  function getZapierDefaultApprovalMode() {
1314
1321
  const isInteractive = !!globalThis.process?.stdin?.isTTY && !!globalThis.process?.stdout?.isTTY;
1315
1322
  return isInteractive ? "poll" : "throw";
@@ -3184,9 +3191,101 @@ function createSseParserStream() {
3184
3191
  }
3185
3192
  });
3186
3193
  }
3194
+ var ApprovalReviewChunkSchema = z.discriminatedUnion("type", [
3195
+ z.object({
3196
+ type: z.literal("text-delta"),
3197
+ delta: z.string()
3198
+ }).passthrough(),
3199
+ z.object({
3200
+ type: z.literal("tool-input-available"),
3201
+ toolCallId: z.string(),
3202
+ toolName: z.string()
3203
+ }).passthrough(),
3204
+ z.object({
3205
+ type: z.literal("tool-output-available"),
3206
+ toolCallId: z.string(),
3207
+ output: z.unknown()
3208
+ }).passthrough()
3209
+ ]);
3210
+ var ReportDecisionOutputSchema = z.object({
3211
+ success: z.boolean().optional(),
3212
+ decision: z.enum(["approved", "denied"]),
3213
+ reason: z.string().optional()
3214
+ }).passthrough();
3215
+ async function consumeApprovalReviewStream({
3216
+ approvalId,
3217
+ streamUrl,
3218
+ signal,
3219
+ stream,
3220
+ emitEvent
3221
+ }) {
3222
+ try {
3223
+ const toolNames = /* @__PURE__ */ new Map();
3224
+ for await (const frame of stream(streamUrl, {
3225
+ method: "GET",
3226
+ headers: {
3227
+ "Accept-Encoding": "identity"
3228
+ },
3229
+ signal
3230
+ })) {
3231
+ if (!frame.parsed) continue;
3232
+ const payload = parseApprovalReviewStreamPayload(frame.data, toolNames);
3233
+ if (!payload) continue;
3234
+ if (payload.kind === "message") {
3235
+ emitEvent("approval:review_message", {
3236
+ approvalId,
3237
+ streamUrl,
3238
+ data: payload.data,
3239
+ message: payload.message
3240
+ });
3241
+ continue;
3242
+ }
3243
+ emitEvent("approval:review_decision", {
3244
+ approvalId,
3245
+ streamUrl,
3246
+ data: payload.data,
3247
+ decision: payload.decision,
3248
+ ...payload.reason ? { reason: payload.reason } : {}
3249
+ });
3250
+ }
3251
+ } catch (err) {
3252
+ if (isAbortError(err) || signal.aborted) return;
3253
+ emitEvent("approval:review_stream_error", {
3254
+ approvalId,
3255
+ streamUrl,
3256
+ message: err instanceof Error ? err.message : String(err)
3257
+ });
3258
+ }
3259
+ }
3260
+ function parseApprovalReviewStreamPayload(parsed, toolNames) {
3261
+ const chunk = ApprovalReviewChunkSchema.safeParse(parsed);
3262
+ if (!chunk.success) return void 0;
3263
+ switch (chunk.data.type) {
3264
+ case "text-delta": {
3265
+ const message = chunk.data.delta.trim();
3266
+ return message.length > 0 ? { kind: "message", data: parsed, message } : void 0;
3267
+ }
3268
+ case "tool-input-available":
3269
+ toolNames.set(chunk.data.toolCallId, chunk.data.toolName);
3270
+ return void 0;
3271
+ case "tool-output-available": {
3272
+ if (toolNames.get(chunk.data.toolCallId) !== "report_decision") {
3273
+ return void 0;
3274
+ }
3275
+ const decision = ReportDecisionOutputSchema.safeParse(chunk.data.output);
3276
+ if (!decision.success) return void 0;
3277
+ return {
3278
+ kind: "decision",
3279
+ data: parsed,
3280
+ decision: decision.data.decision,
3281
+ ...decision.data.reason ? { reason: decision.data.reason } : {}
3282
+ };
3283
+ }
3284
+ }
3285
+ }
3187
3286
 
3188
3287
  // src/sdk-version.ts
3189
- var SDK_VERSION = (typeof process !== "undefined" && process.env ? "0.70.4" : void 0) || "unknown";
3288
+ var SDK_VERSION = (typeof process !== "undefined" && process.env ? "0.71.1" : void 0) || "unknown";
3190
3289
 
3191
3290
  // src/utils/open-url.ts
3192
3291
  var nodePrefix = "node:";
@@ -3238,6 +3337,9 @@ var openUrl = async (url) => {
3238
3337
  } else if (platform === "win32") {
3239
3338
  command = "rundll32";
3240
3339
  args = ["url.dll,FileProtocolHandler", target];
3340
+ } else if (platform === "linux") {
3341
+ command = "xdg-open";
3342
+ args = [target];
3241
3343
  } else {
3242
3344
  throw new Error(`Unsupported platform: ${platform}`);
3243
3345
  }
@@ -3260,16 +3362,39 @@ async function openApproval(url) {
3260
3362
  } catch {
3261
3363
  }
3262
3364
  }
3263
- var ApprovalStatusSchema = z.enum(["pending_approval", "approved", "denied"]);
3365
+ var ApprovalStatusSchema = z.enum([
3366
+ "pending_approval",
3367
+ "approved",
3368
+ "denied",
3369
+ "failed"
3370
+ ]);
3371
+ var ApprovalModeSchema = z.enum(["manual", "auto"]);
3264
3372
  var CreateApprovalResponseSchema = z.object({
3373
+ id: z.string().optional(),
3265
3374
  status: ApprovalStatusSchema,
3266
- approval_id: z.string(),
3375
+ approval_id: z.string().optional(),
3376
+ mode: ApprovalModeSchema,
3267
3377
  approval_url: z.string().url(),
3268
- poll_url: z.string().url()
3378
+ poll_url: z.string().url(),
3379
+ stream_url: z.string().url().optional(),
3380
+ reason: z.string().optional()
3381
+ }).transform((approval, ctx) => {
3382
+ const id = approval.id ?? approval.approval_id;
3383
+ if (!id) {
3384
+ ctx.addIssue({
3385
+ code: "custom",
3386
+ message: "Approval response must include id"
3387
+ });
3388
+ return z.NEVER;
3389
+ }
3390
+ return { ...approval, id };
3269
3391
  });
3270
3392
  var PollApprovalResponseSchema = z.object({
3393
+ id: z.string().optional(),
3271
3394
  status: ApprovalStatusSchema,
3272
- approval_id: z.string()
3395
+ approval_id: z.string().optional(),
3396
+ mode: ApprovalModeSchema.optional(),
3397
+ reason: z.string().optional()
3273
3398
  });
3274
3399
  var APPROVAL_MAX_POLLING_INTERVAL_MS = 5e3;
3275
3400
  function parseRateLimitHeaders(response) {
@@ -3542,7 +3667,11 @@ var ZapierApiClient = class {
3542
3667
  { statusCode: 403 }
3543
3668
  );
3544
3669
  }
3545
- await this.runOneApprovalRound(init.approvalContext, mode);
3670
+ await this.runOneApprovalRound(
3671
+ init.approvalContext,
3672
+ mode,
3673
+ init.signal ?? void 0
3674
+ );
3546
3675
  }
3547
3676
  throw new ZapierApprovalError(
3548
3677
  `Exceeded maximum approval retries (${maxRetries}) for ${path}`,
@@ -3570,6 +3699,7 @@ var ZapierApiClient = class {
3570
3699
  * any frame), so transport / auth failures surface as usual.
3571
3700
  */
3572
3701
  this.fetchJsonStream = (path, init) => jsonFrames(this.fetchStream(path, init));
3702
+ this.streamTrustedJsonUrl = (url, init) => jsonFrames(this.streamTrustedSseUrl(url, init));
3573
3703
  this.get = async (path, options = {}) => {
3574
3704
  return this.fetchJson("GET", path, void 0, options);
3575
3705
  };
@@ -3909,7 +4039,7 @@ var ZapierApiClient = class {
3909
4039
  // bound `fetchStream` arrow above for parity with the other client methods.
3910
4040
  async *streamSse(path, init) {
3911
4041
  const { onOpen, headers: initHeaders, ...fetchInit } = init ?? {};
3912
- const signal = fetchInit.signal;
4042
+ const signal = fetchInit.signal ?? void 0;
3913
4043
  if (signal?.aborted) return;
3914
4044
  const wasMissingAuthToken = fetchInit.authRequired === true && await this.getAuthToken({
3915
4045
  requiredScopes: fetchInit.requiredScopes
@@ -3927,13 +4057,62 @@ var ZapierApiClient = class {
3927
4057
  if (signal?.aborted || isAbortError(err)) return;
3928
4058
  throw err;
3929
4059
  }
4060
+ yield* this.readSseResponse({
4061
+ response,
4062
+ signal,
4063
+ onOpen,
4064
+ wasMissingAuthToken,
4065
+ requiredScopes: fetchInit.requiredScopes
4066
+ });
4067
+ }
4068
+ // Approval `stream_url` is server-supplied and origin-pinned before use, like
4069
+ // `poll_url`; keep absolute-URL streaming private rather than widening the
4070
+ // public path-based `fetchStream` API.
4071
+ async *streamTrustedSseUrl(url, init) {
4072
+ const { onOpen, headers: initHeaders, ...fetchInit } = init ?? {};
4073
+ const signal = fetchInit.signal ?? void 0;
4074
+ if (signal?.aborted) return;
4075
+ const wasMissingAuthToken = fetchInit.authRequired === true && await this.getAuthToken({
4076
+ requiredScopes: fetchInit.requiredScopes
4077
+ }) == null;
4078
+ const headers = new Headers(initHeaders);
4079
+ if (!headers.has("Accept")) headers.set("Accept", "text/event-stream");
4080
+ let response;
4081
+ try {
4082
+ response = await this.withSemaphore(
4083
+ { url, method: fetchInit.method ?? "GET", signal },
4084
+ () => this.rawFetchUrl(url, {
4085
+ ...fetchInit,
4086
+ method: fetchInit.method ?? "GET",
4087
+ headers
4088
+ })
4089
+ );
4090
+ } catch (err) {
4091
+ if (signal?.aborted || isAbortError(err)) return;
4092
+ throw err;
4093
+ }
4094
+ yield* this.readSseResponse({
4095
+ response,
4096
+ signal,
4097
+ onOpen,
4098
+ wasMissingAuthToken,
4099
+ requiredScopes: fetchInit.requiredScopes
4100
+ });
4101
+ }
4102
+ async *readSseResponse({
4103
+ response,
4104
+ signal,
4105
+ onOpen,
4106
+ wasMissingAuthToken,
4107
+ requiredScopes
4108
+ }) {
3930
4109
  if (!response.ok) {
3931
4110
  const { data } = await this.parseResult(response);
3932
4111
  await this.throwForErrorResponse({
3933
4112
  response,
3934
4113
  responseData: data,
3935
4114
  wasMissingAuthToken,
3936
- requiredScopes: fetchInit.requiredScopes
4115
+ requiredScopes
3937
4116
  });
3938
4117
  }
3939
4118
  if (!response.body) return;
@@ -3959,12 +4138,12 @@ var ZapierApiClient = class {
3959
4138
  /**
3960
4139
  * Run a single approval round: create the approval, open the URL (poll mode)
3961
4140
  * or throw (throw mode), poll until resolved, and emit events. Throws on
3962
- * denied/timeout/unexpected status. Returns on approved.
4141
+ * denied/failed/timeout/unexpected status. Returns on approved.
3963
4142
  *
3964
4143
  * Caller is responsible for passing a non-"disabled" mode; this method
3965
4144
  * unconditionally creates an approval.
3966
4145
  */
3967
- async runOneApprovalRound(buildContext, mode) {
4146
+ async runOneApprovalRound(buildContext, mode, signal) {
3968
4147
  const context = buildContext();
3969
4148
  let approvalResponse;
3970
4149
  try {
@@ -3974,9 +4153,11 @@ var ZapierApiClient = class {
3974
4153
  "Content-Type": "application/json",
3975
4154
  Accept: "application/json"
3976
4155
  },
3977
- body: JSON.stringify({ context })
4156
+ body: JSON.stringify({ context }),
4157
+ signal
3978
4158
  });
3979
4159
  } catch (err) {
4160
+ if (isAbortError(err)) throw err;
3980
4161
  throw new ZapierApiError("Failed to create approval request", {
3981
4162
  statusCode: 0,
3982
4163
  cause: err
@@ -4029,6 +4210,9 @@ var ZapierApiClient = class {
4029
4210
  };
4030
4211
  if (!isLocalhostBaseUrl(this.options.baseUrl)) {
4031
4212
  assertApprovalOrigin(approval.poll_url, sdkapiOrigin, "poll_url");
4213
+ if (approval.stream_url) {
4214
+ assertApprovalOrigin(approval.stream_url, sdkapiOrigin, "stream_url");
4215
+ }
4032
4216
  assertApprovalOrigin(
4033
4217
  approval.approval_url,
4034
4218
  browserOrigin,
@@ -4036,19 +4220,79 @@ var ZapierApiClient = class {
4036
4220
  );
4037
4221
  }
4038
4222
  this.emitEvent("approval:required", {
4039
- approvalId: approval.approval_id,
4040
- approvalUrl: approval.approval_url
4223
+ approvalId: approval.id,
4224
+ approvalUrl: approval.approval_url,
4225
+ mode: approval.mode,
4226
+ ...approval.stream_url ? { streamUrl: approval.stream_url } : {}
4041
4227
  });
4042
- if (mode === "throw") {
4043
- throw new ZapierApprovalError("This request requires approval.", {
4044
- approvalId: approval.approval_id,
4045
- approvalUrl: approval.approval_url,
4046
- pollUrl: approval.poll_url,
4047
- status: "pending"
4048
- });
4228
+ const shouldOpenAutoModeApproval = this.options.openAutoModeApprovalsInBrowser ?? getZapierOpenAutoModeApprovalsInBrowser() ?? false;
4229
+ if (approval.mode === "auto") {
4230
+ if (shouldOpenAutoModeApproval) {
4231
+ await openApproval(approval.approval_url);
4232
+ }
4233
+ if (approval.status === "approved") {
4234
+ this.emitEvent("approval:approved", {
4235
+ approvalId: approval.id
4236
+ });
4237
+ return;
4238
+ }
4239
+ if (approval.status === "denied") {
4240
+ this.emitEvent("approval:denied", {
4241
+ approvalId: approval.id,
4242
+ ...approval.reason ? { reason: approval.reason } : {}
4243
+ });
4244
+ throw new ZapierApprovalError(
4245
+ approval.reason ? `Request denied: ${approval.reason}` : "Request denied by user",
4246
+ {
4247
+ approvalId: approval.id,
4248
+ status: "denied",
4249
+ reason: approval.reason
4250
+ }
4251
+ );
4252
+ }
4253
+ if (approval.status === "failed") {
4254
+ this.throwApprovalFailed({
4255
+ approvalId: approval.id,
4256
+ approvalUrl: approval.approval_url,
4257
+ pollUrl: approval.poll_url,
4258
+ streamUrl: approval.stream_url,
4259
+ reason: approval.reason
4260
+ });
4261
+ }
4262
+ } else {
4263
+ if (mode === "throw") {
4264
+ throw new ZapierApprovalError("This request requires approval.", {
4265
+ approvalId: approval.id,
4266
+ approvalUrl: approval.approval_url,
4267
+ pollUrl: approval.poll_url,
4268
+ streamUrl: approval.stream_url,
4269
+ status: "pending"
4270
+ });
4271
+ }
4272
+ await openApproval(approval.approval_url);
4049
4273
  }
4050
- await openApproval(approval.approval_url);
4051
4274
  const timeoutMs = this.options.approvalTimeoutMs ?? DEFAULT_APPROVAL_TIMEOUT_MS;
4275
+ let streamAbortController;
4276
+ let streamPromise;
4277
+ let removeStreamAbortListener;
4278
+ if (approval.mode === "auto" && approval.stream_url) {
4279
+ const streamUrl = approval.stream_url;
4280
+ streamAbortController = new AbortController();
4281
+ const abortStream = () => streamAbortController?.abort();
4282
+ if (signal?.aborted) {
4283
+ abortStream();
4284
+ } else if (signal) {
4285
+ signal.addEventListener("abort", abortStream, { once: true });
4286
+ removeStreamAbortListener = () => signal.removeEventListener("abort", abortStream);
4287
+ }
4288
+ streamPromise = consumeApprovalReviewStream({
4289
+ approvalId: approval.id,
4290
+ streamUrl,
4291
+ signal: streamAbortController.signal,
4292
+ stream: (url, streamInit) => this.streamTrustedJsonUrl(url, streamInit),
4293
+ emitEvent: (type, payload) => this.emitEvent(type, payload)
4294
+ });
4295
+ }
4052
4296
  let rawPollResult;
4053
4297
  try {
4054
4298
  rawPollResult = await pollUntilComplete({
@@ -4059,14 +4303,16 @@ var ZapierApiClient = class {
4059
4303
  // semaphore — but we deliberately do not hold a slot across the
4060
4304
  // sleep between polls or across the human-approval wait.
4061
4305
  fetchPoll: () => this.withSemaphore(
4062
- { url: approval.poll_url, method: "GET" },
4306
+ { url: approval.poll_url, method: "GET", signal },
4063
4307
  () => this.rawFetchUrl(approval.poll_url, {
4064
4308
  method: "GET",
4065
- headers: { Accept: "application/json" }
4309
+ headers: { Accept: "application/json" },
4310
+ signal
4066
4311
  })
4067
4312
  ),
4068
4313
  timeoutMs,
4069
4314
  maxPollingIntervalMs: APPROVAL_MAX_POLLING_INTERVAL_MS,
4315
+ signal,
4070
4316
  isPending: (body2) => {
4071
4317
  const parsed = PollApprovalResponseSchema.safeParse(body2);
4072
4318
  return parsed.success && parsed.data.status === "pending_approval";
@@ -4074,25 +4320,38 @@ var ZapierApiClient = class {
4074
4320
  });
4075
4321
  } catch (err) {
4076
4322
  if (!(err instanceof ZapierTimeoutError)) {
4323
+ this.emitEvent("approval:error", {
4324
+ approvalId: approval.id,
4325
+ message: err instanceof Error ? err.message : String(err)
4326
+ });
4077
4327
  throw err;
4078
4328
  }
4079
4329
  this.emitEvent("approval:timeout", {
4080
- approvalId: approval.approval_id
4330
+ approvalId: approval.id
4081
4331
  });
4082
4332
  throw new ZapierApprovalError(
4083
4333
  `Approval timed out after ${timeoutMs / 1e3} seconds`,
4084
4334
  {
4085
- approvalId: approval.approval_id,
4335
+ approvalId: approval.id,
4086
4336
  approvalUrl: approval.approval_url,
4087
4337
  pollUrl: approval.poll_url,
4338
+ streamUrl: approval.stream_url,
4088
4339
  status: "timeout",
4089
4340
  cause: err
4090
4341
  }
4091
4342
  );
4343
+ } finally {
4344
+ removeStreamAbortListener?.();
4345
+ streamAbortController?.abort();
4346
+ await streamPromise;
4092
4347
  }
4093
4348
  const pollParse = PollApprovalResponseSchema.safeParse(rawPollResult);
4094
4349
  if (!pollParse.success) {
4095
4350
  const bodyPreview = typeof rawPollResult === "string" ? rawPollResult : JSON.stringify(rawPollResult);
4351
+ this.emitEvent("approval:error", {
4352
+ approvalId: approval.id,
4353
+ message: `Failed to parse approval poll response: ${bodyPreview}`
4354
+ });
4096
4355
  throw new ZapierApiError(
4097
4356
  `Failed to parse approval poll response: ${bodyPreview}`,
4098
4357
  {
@@ -4105,22 +4364,63 @@ var ZapierApiClient = class {
4105
4364
  const pollResult = pollParse.data;
4106
4365
  if (pollResult.status === "denied") {
4107
4366
  this.emitEvent("approval:denied", {
4108
- approvalId: approval.approval_id
4367
+ approvalId: approval.id,
4368
+ ...pollResult.reason ? { reason: pollResult.reason } : {}
4109
4369
  });
4110
- throw new ZapierApprovalError("Request denied by user", {
4111
- approvalId: approval.approval_id,
4112
- status: "denied"
4370
+ throw new ZapierApprovalError(
4371
+ pollResult.reason ? `Request denied: ${pollResult.reason}` : "Request denied by user",
4372
+ {
4373
+ approvalId: approval.id,
4374
+ status: "denied",
4375
+ reason: pollResult.reason
4376
+ }
4377
+ );
4378
+ }
4379
+ if (pollResult.status === "failed") {
4380
+ this.throwApprovalFailed({
4381
+ approvalId: approval.id,
4382
+ approvalUrl: approval.approval_url,
4383
+ pollUrl: approval.poll_url,
4384
+ streamUrl: approval.stream_url,
4385
+ reason: pollResult.reason
4113
4386
  });
4114
4387
  }
4115
4388
  if (pollResult.status !== "approved") {
4389
+ this.emitEvent("approval:error", {
4390
+ approvalId: approval.id,
4391
+ message: `Unexpected approval status received: ${pollResult.status}`
4392
+ });
4116
4393
  throw new ZapierApiError(
4117
4394
  `Unexpected approval status received: ${pollResult.status}`
4118
4395
  );
4119
4396
  }
4120
4397
  this.emitEvent("approval:approved", {
4121
- approvalId: approval.approval_id
4398
+ approvalId: approval.id
4122
4399
  });
4123
4400
  }
4401
+ throwApprovalFailed({
4402
+ approvalId,
4403
+ approvalUrl,
4404
+ pollUrl,
4405
+ streamUrl,
4406
+ reason
4407
+ }) {
4408
+ this.emitEvent("approval:failed", {
4409
+ approvalId,
4410
+ ...reason ? { reason } : {}
4411
+ });
4412
+ throw new ZapierApprovalError(
4413
+ reason ? `Approval failed: ${reason}` : "Approval failed",
4414
+ {
4415
+ approvalId,
4416
+ approvalUrl,
4417
+ pollUrl,
4418
+ streamUrl,
4419
+ status: "failed",
4420
+ reason
4421
+ }
4422
+ );
4423
+ }
4124
4424
  };
4125
4425
  var createZapierApi = (options) => {
4126
4426
  const { debug = false, fetch: originalFetch = globalThis.fetch } = options;
@@ -4181,6 +4481,7 @@ var apiPlugin = definePlugin(
4181
4481
  approvalTimeoutMs,
4182
4482
  maxApprovalRetries,
4183
4483
  approvalMode,
4484
+ openAutoModeApprovalsInBrowser,
4184
4485
  callerPackage
4185
4486
  } = sdk.context.options;
4186
4487
  const api = createZapierApi({
@@ -4196,6 +4497,7 @@ var apiPlugin = definePlugin(
4196
4497
  approvalTimeoutMs,
4197
4498
  maxApprovalRetries,
4198
4499
  approvalMode,
4500
+ openAutoModeApprovalsInBrowser,
4199
4501
  callerPackage
4200
4502
  });
4201
4503
  return {
@@ -6433,6 +6735,260 @@ var findUniqueConnectionPlugin = definePlugin(
6433
6735
  }
6434
6736
  })
6435
6737
  );
6738
+ var GetConnectionStartUrlSchema = z.object({
6739
+ app: AppPropertySchema
6740
+ }).describe(
6741
+ "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```"
6742
+ );
6743
+ var GetConnectionStartUrlItemSchema = z.object({
6744
+ url: z.string().describe(
6745
+ "URL the user should open in their browser to complete the auth flow. Single-use, time-limited."
6746
+ ),
6747
+ expiresAt: z.number().describe(
6748
+ "Unix timestamp (seconds) after which the URL's signature is rejected by zapier.com."
6749
+ ),
6750
+ startedAt: z.number().describe(
6751
+ "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."
6752
+ ),
6753
+ app: z.string().describe(
6754
+ "Versionless app key the URL was minted for (e.g., 'SlackCLIAPI'). Useful for downstream filtering."
6755
+ )
6756
+ }).describe(
6757
+ "The signed start-URL plus metadata needed to poll for completion."
6758
+ );
6759
+
6760
+ // src/plugins/getConnectionStartUrl/index.ts
6761
+ var START_PATH = "/zapier/api/authentications/v1/sdk/connections/start";
6762
+ var getConnectionStartUrlPlugin = definePlugin(
6763
+ (sdk) => createPluginMethod(sdk, {
6764
+ name: "getConnectionStartUrl",
6765
+ categories: ["connection"],
6766
+ type: "create",
6767
+ itemType: "ConnectionStartUrl",
6768
+ inputSchema: GetConnectionStartUrlSchema,
6769
+ outputSchema: GetConnectionStartUrlItemSchema,
6770
+ resolvers: { app: appKeyResolver },
6771
+ handler: async ({
6772
+ sdk: inner,
6773
+ options
6774
+ }) => {
6775
+ const versionedKey = await inner.context.getVersionedImplementationId(
6776
+ options.app
6777
+ );
6778
+ const selectedApi = versionedKey ? versionedKey.split("@")[0] : options.app;
6779
+ setMethodMetadata({ selectedApi });
6780
+ const response = await inner.context.api.post(
6781
+ START_PATH,
6782
+ { selected_api: selectedApi },
6783
+ { authRequired: true }
6784
+ );
6785
+ return {
6786
+ data: GetConnectionStartUrlItemSchema.parse({
6787
+ url: response.url,
6788
+ expiresAt: response.expires_at,
6789
+ startedAt: response.started_at,
6790
+ app: selectedApi
6791
+ })
6792
+ };
6793
+ }
6794
+ })
6795
+ );
6796
+ var WaitForNewConnectionSchema = z.object({
6797
+ app: AppPropertySchema,
6798
+ startedAt: z.number().int().nonnegative().describe(
6799
+ "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."
6800
+ ),
6801
+ timeoutMs: z.number().int().positive().optional().describe(
6802
+ "How long to wait before giving up. Default 5 minutes (300_000)."
6803
+ ),
6804
+ pollIntervalMs: z.number().int().positive().optional().describe(
6805
+ "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)."
6806
+ )
6807
+ }).describe(
6808
+ "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```"
6809
+ );
6810
+ var WaitForNewConnectionItemSchema = z.object({
6811
+ id: z.string().describe(
6812
+ "The new connection's ID. Public UUID when available, falling back to the numeric ID."
6813
+ ),
6814
+ app: z.string().describe(
6815
+ "Versionless app key the connection was created for (e.g., 'SlackCLIAPI')."
6816
+ ),
6817
+ title: z.string().nullable().optional().describe(
6818
+ "Human-readable connection title set by the auth flow, when available."
6819
+ )
6820
+ }).describe("The new connection that was detected.");
6821
+
6822
+ // src/plugins/waitForNewConnection/index.ts
6823
+ var CONNECTIONS_PATH = "/api/v0/connections";
6824
+ var waitForNewConnectionPlugin = definePlugin(
6825
+ (sdk) => createPluginMethod(sdk, {
6826
+ name: "waitForNewConnection",
6827
+ categories: ["connection"],
6828
+ type: "item",
6829
+ itemType: "Connection",
6830
+ inputSchema: WaitForNewConnectionSchema,
6831
+ outputSchema: WaitForNewConnectionItemSchema,
6832
+ resolvers: { app: appKeyResolver },
6833
+ handler: async ({
6834
+ sdk: inner,
6835
+ options
6836
+ }) => {
6837
+ const versionedKey = await inner.context.getVersionedImplementationId(
6838
+ options.app
6839
+ );
6840
+ const appKey = versionedKey ? versionedKey.split("@")[0] : options.app;
6841
+ setMethodMetadata({ selectedApi: appKey });
6842
+ try {
6843
+ const top = await inner.context.api.poll(
6844
+ CONNECTIONS_PATH,
6845
+ {
6846
+ searchParams: {
6847
+ app_key: appKey,
6848
+ // Scope to the current user's own connections. The connection
6849
+ // we're waiting on is by definition owned by the caller; without
6850
+ // this the one-row head-check could match a teammate's freshly
6851
+ // created connection for the same app.
6852
+ owner: "me",
6853
+ is_expired: "false",
6854
+ ordering: "-date",
6855
+ page_size: "1"
6856
+ },
6857
+ authRequired: true,
6858
+ timeoutMs: options.timeoutMs ?? 3e5,
6859
+ initialDelay: options.pollIntervalMs ?? 3e3,
6860
+ isPending: (body) => {
6861
+ const rows = body.data ?? [];
6862
+ const head = rows[0];
6863
+ if (!head?.date) return true;
6864
+ const created = Math.floor(new Date(head.date).getTime() / 1e3);
6865
+ return !Number.isFinite(created) || created < options.startedAt;
6866
+ },
6867
+ resultExtractor: (body) => (
6868
+ // `isPending` guaranteed a fresh row at index 0 before this fires.
6869
+ body.data[0]
6870
+ )
6871
+ }
6872
+ );
6873
+ return {
6874
+ data: WaitForNewConnectionItemSchema.parse({
6875
+ id: String(top.public_id ?? top.id),
6876
+ app: appKey,
6877
+ title: top.title ?? null
6878
+ })
6879
+ };
6880
+ } catch (err) {
6881
+ if (err instanceof ZapierTimeoutError) {
6882
+ throw new ZapierTimeoutError(
6883
+ `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.`
6884
+ );
6885
+ }
6886
+ throw err;
6887
+ }
6888
+ }
6889
+ })
6890
+ );
6891
+
6892
+ // src/utils/should-open-browser.ts
6893
+ function shouldOpenBrowser() {
6894
+ if (isCiEnv()) return false;
6895
+ const env = globalThis.process?.env;
6896
+ if (env?.SSH_TTY || env?.SSH_CONNECTION) return false;
6897
+ if (globalThis.process?.platform === "linux" && !env?.DISPLAY && !env?.WAYLAND_DISPLAY) {
6898
+ return false;
6899
+ }
6900
+ return true;
6901
+ }
6902
+ function isCiEnv() {
6903
+ const env = globalThis.process?.env;
6904
+ 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);
6905
+ }
6906
+ var CreateConnectionSchema = z.object({
6907
+ app: AppPropertySchema,
6908
+ browser: z.enum(["auto", "always", "never"]).default("auto").describe(
6909
+ "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."
6910
+ ),
6911
+ timeoutMs: z.number().int().positive().optional().describe(
6912
+ "How long to wait for the user to complete the connection flow before giving up. Default 5 minutes (300_000)."
6913
+ ),
6914
+ pollIntervalMs: z.number().int().positive().optional().describe(
6915
+ "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)."
6916
+ )
6917
+ }).describe(
6918
+ "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`."
6919
+ );
6920
+ var CreateConnectionItemSchema = z.object({
6921
+ id: z.string().describe(
6922
+ "The new connection's ID. Public UUID when available, falling back to the numeric ID."
6923
+ ),
6924
+ app: z.string().describe(
6925
+ "Versionless app key the connection was created for (e.g., 'SlackCLIAPI')."
6926
+ ),
6927
+ title: z.string().nullable().optional().describe(
6928
+ "Human-readable connection title set by the auth flow, when available."
6929
+ )
6930
+ }).describe("The newly created connection.");
6931
+
6932
+ // src/plugins/createConnection/index.ts
6933
+ var createConnectionPlugin = definePlugin(
6934
+ (sdk) => createPluginMethod(sdk, {
6935
+ name: "createConnection",
6936
+ categories: ["connection"],
6937
+ type: "create",
6938
+ itemType: "Connection",
6939
+ inputSchema: CreateConnectionSchema,
6940
+ outputSchema: CreateConnectionItemSchema,
6941
+ resolvers: { app: appKeyResolver },
6942
+ formatter: {
6943
+ format: (item) => ({
6944
+ title: `Connection created: ${item.title || item.id}`,
6945
+ id: item.id,
6946
+ details: [
6947
+ { text: `App: ${item.app}`, style: "normal" },
6948
+ { text: `ID: ${item.id}`, style: "accent" }
6949
+ ]
6950
+ })
6951
+ },
6952
+ handler: async ({
6953
+ sdk: inner,
6954
+ options
6955
+ }) => {
6956
+ const { data: start } = await inner.getConnectionStartUrl({
6957
+ app: options.app
6958
+ });
6959
+ setMethodMetadata({ selectedApi: start.app });
6960
+ console.error(
6961
+ `
6962
+ Open this URL to complete the connection:
6963
+ ${start.url}
6964
+ `
6965
+ );
6966
+ const shouldOpen = options.browser === "always" || options.browser === "auto" && shouldOpenBrowser();
6967
+ if (shouldOpen) {
6968
+ try {
6969
+ await open_url_default(start.url);
6970
+ } catch {
6971
+ }
6972
+ }
6973
+ const { data: fresh } = await inner.waitForNewConnection({
6974
+ app: start.app,
6975
+ // Server-stamped mint time: measured on the same clock as a
6976
+ // connection's `date`, so the freshness check is immune to
6977
+ // client/server clock skew.
6978
+ startedAt: start.startedAt,
6979
+ timeoutMs: options.timeoutMs,
6980
+ pollIntervalMs: options.pollIntervalMs
6981
+ });
6982
+ return {
6983
+ data: CreateConnectionItemSchema.parse({
6984
+ id: fresh.id,
6985
+ app: start.app,
6986
+ title: fresh.title ?? null
6987
+ })
6988
+ };
6989
+ }
6990
+ })
6991
+ );
6436
6992
 
6437
6993
  // src/plugins/deprecated/authentications.ts
6438
6994
  var listAuthenticationsPlugin = definePlugin(
@@ -9490,7 +10046,7 @@ function createZapierSdkWithoutRegistry(options = {}) {
9490
10046
  return createZapierSdk(options);
9491
10047
  }
9492
10048
  function createZapierSdkStack(options = {}) {
9493
- 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);
10049
+ 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);
9494
10050
  }
9495
10051
  function createZapierSdk(options = {}) {
9496
10052
  return withDeprecatedAddPlugin(createZapierSdkStack(options).toSdk());
@@ -11377,9 +11933,13 @@ var getWorkflowPlugin = definePlugin(
11377
11933
  var CreateWorkflowOptionsSchema = z.object({
11378
11934
  name: z.string().min(1).describe("Workflow name"),
11379
11935
  description: z.string().optional().describe("Optional description for the workflow"),
11936
+ private: z.boolean().optional().describe(
11937
+ "If true, only the creating user can see or manage this workflow. Defaults to false (account-visible)."
11938
+ ),
11939
+ /** @deprecated Use `private` instead. */
11380
11940
  is_private: z.boolean().optional().describe(
11381
11941
  "If true, only the creating user can see or manage this workflow. Defaults to false (account-visible)."
11382
- )
11942
+ ).meta({ deprecated: true })
11383
11943
  }).describe(
11384
11944
  "Create a durable workflow container. Starts disabled with no version; publish a version to add code."
11385
11945
  );
@@ -11414,8 +11974,9 @@ var createWorkflowPlugin = definePlugin(
11414
11974
  if (options.description !== void 0) {
11415
11975
  body.description = options.description;
11416
11976
  }
11417
- if (options.is_private !== void 0) {
11418
- body.is_private = options.is_private;
11977
+ const isPrivate = options.private ?? options.is_private;
11978
+ if (isPrivate !== void 0) {
11979
+ body.is_private = isPrivate;
11419
11980
  }
11420
11981
  const raw = await sdk2.context.api.post(
11421
11982
  "/durableworkflowzaps/api/v0/workflows",
@@ -11804,7 +12365,7 @@ var RunDurableOptionsSchema = z.object({
11804
12365
  'Exact semver of @zapier/zapier-durable to use (e.g. "1.2.3"). Defaults to server-configured version if omitted.'
11805
12366
  ),
11806
12367
  connections: z.record(z.string(), ConnectionMapEntrySchema).optional().describe(
11807
- "Named connection aliases. Maps alias names to Zapier connection IDs."
12368
+ 'Named connection aliases. Maps each alias to an object holding its Zapier connection ID, e.g. `{ "slack": { "connection_id": "123" } }`.'
11808
12369
  ),
11809
12370
  app_versions: z.record(z.string(), AppVersionMapEntrySchema).optional().describe(
11810
12371
  "Pinned app versions. Maps app keys (slugs) to implementation names and versions."
@@ -12483,7 +13044,10 @@ var BaseSdkOptionsSchema = z.object({
12483
13044
  "Maximum number of sequential approval rounds per request (one per gating policy) before giving up. Default: 2."
12484
13045
  ),
12485
13046
  approvalMode: z.enum(["disabled", "poll", "throw"]).optional().describe(
12486
- '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).'
13047
+ '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).'
13048
+ ),
13049
+ openAutoModeApprovalsInBrowser: z.boolean().optional().describe(
13050
+ "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."
12487
13051
  ),
12488
13052
  // Internal
12489
13053
  manifestPath: z.string().optional().describe("Path to a .zapierrc manifest file for app version locking.").meta({ internal: true }),
@@ -12511,10 +13075,10 @@ var registryPlugin = definePlugin((_sdk) => {
12511
13075
 
12512
13076
  // src/experimental.ts
12513
13077
  function createZapierSdkStack2(options = {}) {
12514
- 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(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(listWorkflowsPlugin).use(getWorkflowPlugin).use(createWorkflowPlugin).use(updateWorkflowPlugin).use(enableWorkflowPlugin).use(disableWorkflowPlugin).use(deleteWorkflowPlugin).use(listDurableRunsPlugin).use(getDurableRunPlugin).use(runDurablePlugin).use(cancelDurableRunPlugin).use(publishWorkflowVersionPlugin).use(listWorkflowVersionsPlugin).use(getWorkflowVersionPlugin).use(listWorkflowRunsPlugin).use(getWorkflowRunPlugin).use(getTriggerRunPlugin).use(triggerWorkflowPlugin).use(appsPlugin).use(getProfilePlugin);
13078
+ 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(listWorkflowsPlugin).use(getWorkflowPlugin).use(createWorkflowPlugin).use(updateWorkflowPlugin).use(enableWorkflowPlugin).use(disableWorkflowPlugin).use(deleteWorkflowPlugin).use(listDurableRunsPlugin).use(getDurableRunPlugin).use(runDurablePlugin).use(cancelDurableRunPlugin).use(publishWorkflowVersionPlugin).use(listWorkflowVersionsPlugin).use(getWorkflowVersionPlugin).use(listWorkflowRunsPlugin).use(getWorkflowRunPlugin).use(getTriggerRunPlugin).use(triggerWorkflowPlugin).use(appsPlugin).use(getProfilePlugin);
12515
13079
  }
12516
13080
  function createZapierSdk2(options = {}) {
12517
13081
  return withDeprecatedAddPlugin(createZapierSdkStack2(options).toSdk());
12518
13082
  }
12519
13083
 
12520
- 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, createZapierSdk2 as createZapierSdk, createZapierSdkStack2 as 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 };
13084
+ 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, createZapierSdk2 as createZapierSdk, createZapierSdkStack2 as 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 };