@superdurable/connector-zoom 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1434 @@
1
+ import {
2
+ ConfigSchema,
3
+ Connection,
4
+ ConnectorID,
5
+ CreateMeetingBranch,
6
+ CreateMeetingBranchCreated,
7
+ CreateMeetingBranchDefect,
8
+ CreateMeetingBranchProviderRejected,
9
+ CreateMeetingBranchUncertain,
10
+ CreateMeetingDefinition,
11
+ CreateMeetingInputSchema,
12
+ CreateMeetingMetadata,
13
+ GetMeetingBranch,
14
+ GetMeetingBranchDefect,
15
+ GetMeetingBranchFound,
16
+ GetMeetingBranchInvalidResponse,
17
+ GetMeetingBranchNotFound,
18
+ GetMeetingBranchProviderRejected,
19
+ GetMeetingDefinition,
20
+ GetMeetingInputSchema,
21
+ GetMeetingMetadata,
22
+ ListMeetingsBranch,
23
+ ListMeetingsBranchDefect,
24
+ ListMeetingsBranchInvalidResponse,
25
+ ListMeetingsBranchListed,
26
+ ListMeetingsBranchProviderRejected,
27
+ ListMeetingsDefinition,
28
+ ListMeetingsInputSchema,
29
+ ListMeetingsMetadata,
30
+ ListPastMeetingParticipantsBranch,
31
+ ListPastMeetingParticipantsBranchDefect,
32
+ ListPastMeetingParticipantsBranchInvalidResponse,
33
+ ListPastMeetingParticipantsBranchListed,
34
+ ListPastMeetingParticipantsBranchNotFound,
35
+ ListPastMeetingParticipantsBranchProviderRejected,
36
+ ListPastMeetingParticipantsDefinition,
37
+ ListPastMeetingParticipantsInputSchema,
38
+ ListPastMeetingParticipantsMetadata,
39
+ MeetingPageSchema,
40
+ MeetingParticipantSchema,
41
+ MeetingSchema,
42
+ MeetingSettingsInputSchema,
43
+ MeetingSettingsSchema,
44
+ MeetingSummarySchema,
45
+ ParticipantPageSchema,
46
+ ProviderID,
47
+ UpdateMeetingBranch,
48
+ UpdateMeetingBranchDefect,
49
+ UpdateMeetingBranchNotFound,
50
+ UpdateMeetingBranchProviderRejected,
51
+ UpdateMeetingBranchUpdated,
52
+ UpdateMeetingDefinition,
53
+ UpdateMeetingInputSchema,
54
+ UpdateMeetingMetadata,
55
+ UpdatedMeetingSchema,
56
+ decodeCredentials,
57
+ decodeSharedCredentials,
58
+ newConnection,
59
+ newConnectionWithOperations,
60
+ newProjectConnection,
61
+ newProjectCredentialProvider
62
+ } from "./chunk-RBP47TKQ.js";
63
+
64
+ // src/generated/steps.ts
65
+ import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
66
+ function newListMeetingsStep(configuration) {
67
+ const { connection, connectionName, listed, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
68
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
69
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listMeetings(), connection: connection.reference, branches: [
70
+ goToBranch("listed", listed),
71
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
72
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
73
+ ...defect2 ? [goToBranch("defect", defect2)] : []
74
+ ] });
75
+ }
76
+ function newGetMeetingStep(configuration) {
77
+ const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
78
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
79
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.getMeeting(), connection: connection.reference, branches: [
80
+ goToBranch("found", found),
81
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
82
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
83
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
84
+ ...defect2 ? [goToBranch("defect", defect2)] : []
85
+ ] });
86
+ }
87
+ function newCreateMeetingStep(configuration) {
88
+ const { connection, connectionName, created, providerRejected, uncertain, defect: defect2, ...stepConfiguration } = configuration;
89
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
90
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.createMeeting(), connection: connection.reference, branches: [
91
+ goToBranch("created", created),
92
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
93
+ ...uncertain ? [goToBranch("uncertain", uncertain)] : [],
94
+ ...defect2 ? [goToBranch("defect", defect2)] : []
95
+ ] });
96
+ }
97
+ function newUpdateMeetingStep(configuration) {
98
+ const { connection, connectionName, updated, notFound, providerRejected, defect: defect2, ...stepConfiguration } = configuration;
99
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
100
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.updateMeeting(), connection: connection.reference, branches: [
101
+ goToBranch("updated", updated),
102
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
103
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
104
+ ...defect2 ? [goToBranch("defect", defect2)] : []
105
+ ] });
106
+ }
107
+ function newListPastMeetingParticipantsStep(configuration) {
108
+ const { connection, connectionName, listed, notFound, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
109
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
110
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listPastMeetingParticipants(), connection: connection.reference, branches: [
111
+ goToBranch("listed", listed),
112
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
113
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
114
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
115
+ ...defect2 ? [goToBranch("defect", defect2)] : []
116
+ ] });
117
+ }
118
+
119
+ // src/client.ts
120
+ import { ReauthorizationRequiredError, resolveCredential, resolveCredentialAfterRejection } from "@superdurable/connectors-sdk";
121
+ import { AddressRefusal, BodyTooLargeError, MaxErrorBodyBytes, ProviderTransportError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
122
+ import { ManifestCredentialRefreshDriver } from "@superdurable/connectors-sdk/oauthtoken";
123
+
124
+ // src/generated/refresh.ts
125
+ var Authorization = {
126
+ "fields": [
127
+ {
128
+ "name": "oauth_client_id",
129
+ "required": true,
130
+ "type": "string"
131
+ },
132
+ {
133
+ "name": "oauth_client_secret",
134
+ "required": true,
135
+ "type": "secretString"
136
+ },
137
+ {
138
+ "name": "access_token",
139
+ "required": true,
140
+ "type": "secretString"
141
+ },
142
+ {
143
+ "name": "refresh_token",
144
+ "required": true,
145
+ "type": "secretString"
146
+ }
147
+ ],
148
+ "oauth2": {
149
+ "clientIDCredential": "oauth_client_id",
150
+ "clientSecretCredential": "oauth_client_secret",
151
+ "credentialMappings": [
152
+ {
153
+ "credential": "access_token",
154
+ "source": "access_token"
155
+ },
156
+ {
157
+ "credential": "refresh_token",
158
+ "source": "refresh_token"
159
+ }
160
+ ],
161
+ "refresh": {
162
+ "missingExpiry": "reject",
163
+ "scopeSeparators": "whitespaceAndComma",
164
+ "storedMissingExpiry": "refresh",
165
+ "terminalErrorCodes": [
166
+ "invalid_request",
167
+ "invalid_client",
168
+ "invalid_grant",
169
+ "unauthorized_client"
170
+ ],
171
+ "tokenExchangeTimeout": "8s"
172
+ },
173
+ "scopes": [
174
+ "meeting:read:list_meetings",
175
+ "meeting:read:meeting",
176
+ "meeting:write:meeting",
177
+ "meeting:update:meeting",
178
+ "meeting:read:list_past_participants"
179
+ ],
180
+ "tokenEndpoint": "https://zoom.us/oauth/token",
181
+ "tokenEndpointAuthMethod": "client_secret_basic"
182
+ },
183
+ "refreshable": true,
184
+ "type": "oauth2"
185
+ };
186
+ var CredentialFields = {
187
+ "access_token": "accessToken",
188
+ "oauth_client_id": "oauthClientId",
189
+ "oauth_client_secret": "oauthClientSecret",
190
+ "refresh_token": "refreshToken"
191
+ };
192
+
193
+ // src/operations.ts
194
+ import { newMutationBranch, newMutationRetry, newMutationUncertain, newQueryBranch, newQueryRetry, zeroReceipt } from "@superdurable/connectors-sdk";
195
+ import { newFence, CheckpointError, InsufficientTimeError } from "@superdurable/connectors-sdk/singledispatch";
196
+
197
+ // src/meeting.ts
198
+ var timestampPattern = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:[.,](\d+))?(Z|([+-])(\d{2}):(\d{2}))$/;
199
+ var emptyMeeting = { id: 0, topic: "", settings: { hostVideo: false, participantVideo: false, joinBeforeHost: false, muteUponEntry: false, waitingRoom: false } };
200
+ var emptyMeetingPage = { meetings: [], totalRecords: 0 };
201
+ function object(value) {
202
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("Zoom returned an unusable object");
203
+ return value;
204
+ }
205
+ function responseObject(body) {
206
+ const rawJSON = JSON.rawJSON;
207
+ const parseWithSource = JSON.parse;
208
+ return object(parseWithSource(Buffer.from(body).toString("utf8"), (_key, value, context) => typeof value === "number" ? rawJSON(context.source) : value));
209
+ }
210
+ function string(value) {
211
+ if (value === void 0 || value === null) return "";
212
+ if (typeof value !== "string") throw new TypeError("Zoom returned a non-string field");
213
+ return value;
214
+ }
215
+ function integer(value) {
216
+ if (value === void 0 || value === null) return 0;
217
+ const literal = value && typeof value === "object" && "rawJSON" in value ? String(value.rawJSON) : "";
218
+ if (!/^-?(0|[1-9][0-9]*)$/.test(literal)) throw new TypeError("Zoom returned a non-integer field");
219
+ const number = Number(literal);
220
+ if (!Number.isSafeInteger(number)) throw new TypeError("Zoom returned a non-integer field");
221
+ return number;
222
+ }
223
+ function boolean(value) {
224
+ if (value === void 0 || value === null) return false;
225
+ if (typeof value !== "boolean") throw new TypeError("Zoom returned a non-boolean field");
226
+ return value;
227
+ }
228
+ function zoomTime(value) {
229
+ const raw = string(value);
230
+ if (!raw) return void 0;
231
+ const match = timestampPattern.exec(raw);
232
+ if (!match) throw new TypeError("Zoom returned an invalid timestamp");
233
+ const [, yearText, monthText, dayText, hourText, minuteText, secondText, fraction, zone2, sign, zoneHourText, zoneMinuteText] = match;
234
+ const year = Number(yearText), month = Number(monthText), day = Number(dayText);
235
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
236
+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
237
+ if (month < 1 || month > 12 || day < 1 || day > days[month - 1] || Number(hourText) > 23 || Number(minuteText) > 59 || Number(secondText) > 59 || zone2 !== "Z" && (Number(zoneHourText) > 24 || Number(zoneMinuteText) > 60)) throw new TypeError("Zoom returned an invalid timestamp");
238
+ const offset = zone2 === "Z" ? 0 : (Number(zoneHourText) * 60 + Number(zoneMinuteText)) * (sign === "+" ? 1 : -1);
239
+ const calendar = /* @__PURE__ */ new Date(0);
240
+ calendar.setUTCFullYear(year, month - 1, day);
241
+ calendar.setUTCHours(Number(hourText), Number(minuteText), Number(secondText), 0);
242
+ const milliseconds = calendar.getTime() - offset * 6e4;
243
+ const instant = new Date(milliseconds);
244
+ if (!Number.isFinite(milliseconds)) throw new TypeError("Zoom returned an invalid timestamp");
245
+ const nanoseconds = (fraction ?? "").slice(0, 9).padEnd(9, "0");
246
+ const trimmed = nanoseconds.replace(/0+$/, "");
247
+ return instant.toISOString().replace(/\.\d{3}Z$/, "") + (trimmed ? `.${trimmed}` : "") + "Z";
248
+ }
249
+ function meetingID(value) {
250
+ if (!Number.isSafeInteger(value) || value < 1) throw new TypeError("meetingId must be Zoom's positive numeric meeting ID");
251
+ }
252
+ function pageToken(value = "") {
253
+ if (Buffer.byteLength(value) > 1024 || !/^[!-~]*$/.test(value)) throw new TypeError("pageToken must be printable ASCII without spaces and at most 1024 bytes");
254
+ }
255
+ function pageSize(value = 0) {
256
+ if (value === 0) return 30;
257
+ if (!Number.isSafeInteger(value) || value < 1 || value > 300) throw new TypeError("pageSize must be between 1 and 300");
258
+ return value;
259
+ }
260
+ function topic(value) {
261
+ if (!value.trim()) throw new TypeError("topic is required");
262
+ if ([...value].length > 200) throw new TypeError("topic must be valid UTF-8 of at most 200 characters");
263
+ }
264
+ function agenda(value) {
265
+ if ([...value].length > 2e3) throw new TypeError("agenda must be valid UTF-8 of at most 2000 characters");
266
+ }
267
+ function duration(value) {
268
+ if (!Number.isSafeInteger(value) || value < 1 || value > 1440) throw new TypeError("durationMinutes must be between 1 and 1440");
269
+ }
270
+ function zone(value) {
271
+ if (!value || value !== value.trim() || value === "Local") throw new TypeError("timeZone must be an IANA time zone name");
272
+ try {
273
+ new Intl.DateTimeFormat("en-US", { timeZone: value });
274
+ } catch {
275
+ throw new TypeError("timeZone is not a known IANA time zone name");
276
+ }
277
+ }
278
+ function start(value, timeZone) {
279
+ zone(timeZone);
280
+ const instant = zoomTime(value);
281
+ if (!instant || !timestampPattern.test(value) || (timestampPattern.exec(value)?.[7] ?? "").replace(/0/g, "") !== "") throw new TypeError("startTime must be a whole-second RFC 3339 instant with an explicit offset");
282
+ return instant;
283
+ }
284
+ function settings(input) {
285
+ if (!input) return void 0;
286
+ if (input.autoRecording && !["none", "local", "cloud"].includes(input.autoRecording)) throw new TypeError("settings.autoRecording must be none, local, or cloud");
287
+ const value = {
288
+ ...input.hostVideo !== void 0 ? { host_video: input.hostVideo } : {},
289
+ ...input.participantVideo !== void 0 ? { participant_video: input.participantVideo } : {},
290
+ ...input.joinBeforeHost !== void 0 ? { join_before_host: input.joinBeforeHost } : {},
291
+ ...input.muteUponEntry !== void 0 ? { mute_upon_entry: input.muteUponEntry } : {},
292
+ ...input.waitingRoom !== void 0 ? { waiting_room: input.waitingRoom } : {},
293
+ ...input.autoRecording ? { auto_recording: input.autoRecording } : {}
294
+ };
295
+ return Object.keys(value).length ? value : void 0;
296
+ }
297
+ function createRequest(input) {
298
+ topic(input.topic);
299
+ duration(input.durationMinutes);
300
+ agenda(input.agenda ?? "");
301
+ const instant = start(input.startTime, input.timeZone);
302
+ const override = settings(input.settings);
303
+ return {
304
+ payload: {
305
+ topic: input.topic,
306
+ type: 2,
307
+ start_time: instant,
308
+ duration: input.durationMinutes,
309
+ timezone: input.timeZone,
310
+ ...input.agenda ? { agenda: input.agenda } : {},
311
+ ...override ? { settings: override } : {}
312
+ },
313
+ requested: {
314
+ id: 0,
315
+ topic: input.topic,
316
+ type: 2,
317
+ startTime: instant,
318
+ durationMinutes: input.durationMinutes,
319
+ timeZone: input.timeZone,
320
+ ...input.agenda ? { agenda: input.agenda } : {},
321
+ settings: emptyMeeting.settings
322
+ }
323
+ };
324
+ }
325
+ function updateRequest(input, now) {
326
+ meetingID(input.meetingId);
327
+ const payload = {};
328
+ if (input.topic) {
329
+ topic(input.topic);
330
+ payload.topic = input.topic;
331
+ }
332
+ if (input.agenda !== void 0) {
333
+ agenda(input.agenda);
334
+ payload.agenda = input.agenda;
335
+ }
336
+ if (input.startTime) {
337
+ const instant = start(input.startTime, input.timeZone ?? "");
338
+ if (Date.parse(instant) <= now.getTime()) throw new TypeError("startTime is not in the future");
339
+ payload.start_time = instant;
340
+ payload.timezone = input.timeZone;
341
+ } else if (input.timeZone) throw new TypeError("timeZone requires startTime");
342
+ if (input.durationMinutes) {
343
+ duration(input.durationMinutes);
344
+ payload.duration = input.durationMinutes;
345
+ }
346
+ const override = settings(input.settings);
347
+ if (override) payload.settings = override;
348
+ if (!Object.keys(payload).length) throw new TypeError("updateMeeting needs at least one change");
349
+ return payload;
350
+ }
351
+ function decodeMeeting(value) {
352
+ const raw = object(value);
353
+ const id = integer(raw.id), length = integer(raw.duration);
354
+ if (id < 1 || length < 0) throw new TypeError("Zoom returned an unusable meeting");
355
+ const joinUrl = string(raw.join_url);
356
+ if (joinUrl) {
357
+ const url = new URL(joinUrl);
358
+ if (url.protocol !== "https:" || !url.hostname || url.username || url.password) throw new TypeError("Zoom returned an unusable meeting");
359
+ }
360
+ const rawSettings = raw.settings == null ? {} : object(raw.settings);
361
+ const meeting = { id, topic: string(raw.topic), settings: {
362
+ hostVideo: boolean(rawSettings.host_video),
363
+ participantVideo: boolean(rawSettings.participant_video),
364
+ joinBeforeHost: boolean(rawSettings.join_before_host),
365
+ muteUponEntry: boolean(rawSettings.mute_upon_entry),
366
+ waitingRoom: boolean(rawSettings.waiting_room),
367
+ ...string(rawSettings.auto_recording) ? { autoRecording: string(rawSettings.auto_recording) } : {}
368
+ } };
369
+ const fields = [["uuid", raw.uuid], ["hostId", raw.host_id], ["hostEmail", raw.host_email], ["status", raw.status], ["timeZone", raw.timezone], ["agenda", raw.agenda], ["joinUrl", raw.join_url]];
370
+ for (const [key, rawValue] of fields) {
371
+ const value2 = string(rawValue);
372
+ if (value2) meeting[key] = value2;
373
+ }
374
+ const type = integer(raw.type);
375
+ if (type) meeting.type = type;
376
+ if (length) meeting.durationMinutes = length;
377
+ const startTime = zoomTime(raw.start_time);
378
+ if (startTime) meeting.startTime = startTime;
379
+ const createdAt = zoomTime(raw.created_at);
380
+ if (createdAt) meeting.createdAt = createdAt;
381
+ return meeting;
382
+ }
383
+ function meetingSummary(meeting) {
384
+ const { id, uuid, hostId, topic: topic2, type, startTime, durationMinutes, timeZone, agenda: agenda2, joinUrl, createdAt } = meeting;
385
+ return {
386
+ id,
387
+ topic: topic2,
388
+ ...uuid ? { uuid } : {},
389
+ ...hostId ? { hostId } : {},
390
+ ...type ? { type } : {},
391
+ ...startTime ? { startTime } : {},
392
+ ...durationMinutes ? { durationMinutes } : {},
393
+ ...timeZone ? { timeZone } : {},
394
+ ...agenda2 ? { agenda: agenda2 } : {},
395
+ ...joinUrl ? { joinUrl } : {},
396
+ ...createdAt ? { createdAt } : {}
397
+ };
398
+ }
399
+ function participantPage(value, id) {
400
+ const raw = object(value), total = integer(raw.total_records), token = string(raw.next_page_token);
401
+ if (total < 0 || raw.participants !== void 0 && raw.participants !== null && !Array.isArray(raw.participants)) throw new TypeError("Zoom returned an unusable participant page");
402
+ pageToken(token);
403
+ const participants = (raw.participants ?? []).map((value2) => {
404
+ const item = object(value2), durationSeconds = integer(item.duration);
405
+ if (durationSeconds < 0) throw new TypeError("Zoom returned an unusable participant page");
406
+ const joinTime = zoomTime(item.join_time), leaveTime = zoomTime(item.leave_time);
407
+ return {
408
+ durationSeconds,
409
+ isInternalUser: boolean(item.internal_user),
410
+ ...string(item.id) ? { id: string(item.id) } : {},
411
+ ...string(item.name) ? { name: string(item.name) } : {},
412
+ ...string(item.user_email) ? { email: string(item.user_email) } : {},
413
+ ...joinTime ? { joinTime } : {},
414
+ ...leaveTime ? { leaveTime } : {},
415
+ ...string(item.status) ? { status: string(item.status) } : {}
416
+ };
417
+ });
418
+ return { meetingId: id, participants, totalRecords: total, ...token ? { nextPageToken: token } : {} };
419
+ }
420
+
421
+ // src/operations.ts
422
+ var emptyParticipants = { meetingId: 0, participants: [], totalRecords: 0 };
423
+ var emptyUpdate = { meetingId: 0 };
424
+ var successful = (status) => status >= 200 && status < 300;
425
+ function code(body) {
426
+ try {
427
+ const value = integer(responseObject(body).code);
428
+ return value >= 0 && value <= 4294967295 ? String(value) : "";
429
+ } catch {
430
+ return "";
431
+ }
432
+ }
433
+ function statusMessage(message, status, errorCode) {
434
+ return `${message} with HTTP ${status}${errorCode ? ` (code ${errorCode})` : ""}`;
435
+ }
436
+ function classify(client, operation, exchange) {
437
+ if ("error" in exchange) return { outcome: "retry", failure: zoomFailure(operation, "TRANSPORT", "Zoom could not be reached"), errorCode: "", retryAfter: 0 };
438
+ const { response, isTooLarge, reflectsCredential } = exchange, status = response.status;
439
+ const errorCode = code(response.body), retryAfter = client.retryAfter(response.headers);
440
+ if (successful(status)) {
441
+ if (isTooLarge) return { outcome: "invalid", failure: zoomFailure(operation, "RESPONSE_TOO_LARGE", "Zoom response exceeds the configured size limit"), errorCode: "", retryAfter: 0 };
442
+ if (reflectsCredential) return { outcome: "invalid", failure: zoomFailure(operation, "PROTOCOL", "Zoom response contained the connection credential"), errorCode: "", retryAfter: 0 };
443
+ return { outcome: "usable", errorCode: "", retryAfter: 0 };
444
+ }
445
+ if (status >= 300 && status < 400) return { outcome: "invalid", failure: zoomFailure(operation, "PROTOCOL", statusMessage("Zoom redirected the request", status, "")), errorCode: "", retryAfter: 0 };
446
+ if (status === 404) return { outcome: "notFound", failure: zoomFailure(operation, "NOT_FOUND", statusMessage("Zoom reported the resource missing", status, errorCode)), errorCode, retryAfter: 0 };
447
+ if (status === 429) {
448
+ let daily = false;
449
+ try {
450
+ const message = object(JSON.parse(Buffer.from(response.body).toString())).message;
451
+ daily = typeof message === "string" && message.trim().toLowerCase().startsWith("you have reached the maximum daily rate limit for this api.");
452
+ } catch {
453
+ }
454
+ return { outcome: daily ? "rejected" : "retry", failure: zoomFailure(operation, "RATE_LIMIT", statusMessage(daily ? "Zoom daily API rate limit reached" : "Zoom rate limited the request", status, errorCode)), errorCode, retryAfter: daily ? 0 : retryAfter };
455
+ }
456
+ if (status === 409) return { outcome: "retry", failure: zoomFailure(operation, "CONFLICT", statusMessage("Zoom reported a conflict", status, errorCode)), errorCode, retryAfter: 0 };
457
+ if (status === 408 || status >= 500) return { outcome: "retry", failure: zoomFailure(operation, "AVAILABILITY", statusMessage("Zoom is temporarily unavailable", status, errorCode)), errorCode, retryAfter };
458
+ const kind = status === 401 ? "AUTHENTICATION" : status === 403 ? "AUTHORIZATION" : status === 412 ? "CONFLICT" : "PROVIDER_REJECTION";
459
+ return { outcome: "rejected", failure: zoomFailure(operation, kind, statusMessage("Zoom rejected the request", status, errorCode)), errorCode, retryAfter: 0 };
460
+ }
461
+ function defect(operation, error) {
462
+ return zoomFailure(operation, "VALIDATION", error instanceof Error ? error.message : String(error));
463
+ }
464
+ function queryCredential(resolved, empty) {
465
+ return resolved.retry ? newQueryRetry(resolved.failure, 0) : newQueryBranch("defect", empty, zeroReceipt(), resolved.failure);
466
+ }
467
+ function mutationCredential(resolved, empty) {
468
+ return resolved.retry ? newMutationRetry(resolved.failure, 0) : newMutationBranch("defect", empty, zeroReceipt(), resolved.failure);
469
+ }
470
+ var ListMeetingsOperation = class {
471
+ /** Bind one Zoom client. */
472
+ constructor(client) {
473
+ this.client = client;
474
+ }
475
+ client;
476
+ /** Return the manifest definition. */
477
+ definition() {
478
+ return ListMeetingsDefinition;
479
+ }
480
+ /** Invoke one bounded meeting-list request. */
481
+ async invoke(call, input) {
482
+ let query;
483
+ try {
484
+ const type = input.type || "upcoming";
485
+ if (!["upcoming", "scheduled", "live", "previous_meetings"].includes(type)) throw new TypeError("type must be upcoming, scheduled, live, or previous_meetings");
486
+ pageToken(input.pageToken);
487
+ query = new URLSearchParams({ type, page_size: String(pageSize(input.pageSize)) });
488
+ if (input.pageToken) query.set("next_page_token", input.pageToken);
489
+ } catch (error) {
490
+ return newQueryBranch("defect", emptyMeetingPage, zeroReceipt(), defect("listMeetings", error));
491
+ }
492
+ const resolved = await this.client.resolveCredentials(call, "listMeetings");
493
+ if ("failure" in resolved) return queryCredential(resolved, emptyMeetingPage);
494
+ const exchange = await this.client.exchange(call, resolved.credentials, "GET", "/users/me/meetings", query);
495
+ if ("error" in exchange) return exchange.error === "notBuilt" ? newQueryBranch("defect", emptyMeetingPage, zeroReceipt(), zoomFailure("listMeetings", "LOCAL_DEFECT", "Zoom request could not be built")) : newQueryRetry(zoomFailure("listMeetings", "TRANSPORT", "Zoom could not be reached"), 0);
496
+ const result = classify(this.client, "listMeetings", exchange), receipt = this.client.receipt(call, "", result.errorCode);
497
+ if (result.outcome === "retry") return newQueryRetry(result.failure, result.retryAfter);
498
+ if (result.outcome === "invalid") return newQueryBranch("invalidResponse", emptyMeetingPage, receipt, result.failure);
499
+ if (result.outcome !== "usable") return newQueryBranch("providerRejected", emptyMeetingPage, receipt, result.failure);
500
+ try {
501
+ const raw = responseObject(exchange.response.body), total = integer(raw.total_records), next = raw.next_page_token ?? "";
502
+ if (total < 0 || typeof next !== "string" || raw.meetings !== void 0 && raw.meetings !== null && !Array.isArray(raw.meetings)) throw new TypeError("invalid page");
503
+ pageToken(next);
504
+ const meetings = (raw.meetings ?? []).map((item) => meetingSummary(decodeMeeting(item)));
505
+ return newQueryBranch("listed", { meetings, totalRecords: total, ...next ? { nextPageToken: next } : {} }, receipt);
506
+ } catch {
507
+ return newQueryBranch("invalidResponse", emptyMeetingPage, receipt, zoomFailure("listMeetings", "PROTOCOL", "Zoom returned an unusable meeting page"));
508
+ }
509
+ }
510
+ };
511
+ var GetMeetingOperation = class {
512
+ /** Bind one Zoom client. */
513
+ constructor(client) {
514
+ this.client = client;
515
+ }
516
+ client;
517
+ /** Return the manifest definition. */
518
+ definition() {
519
+ return GetMeetingDefinition;
520
+ }
521
+ /** Invoke one bounded meeting read. */
522
+ async invoke(call, input) {
523
+ try {
524
+ meetingID(input.meetingId);
525
+ } catch (error) {
526
+ return newQueryBranch("defect", emptyMeeting, zeroReceipt(), defect("getMeeting", error));
527
+ }
528
+ const resolved = await this.client.resolveCredentials(call, "getMeeting");
529
+ if ("failure" in resolved) return queryCredential(resolved, emptyMeeting);
530
+ const id = String(input.meetingId), exchange = await this.client.exchange(call, resolved.credentials, "GET", `/meetings/${id}`);
531
+ if ("error" in exchange) return exchange.error === "notBuilt" ? newQueryBranch("defect", emptyMeeting, zeroReceipt(), zoomFailure("getMeeting", "LOCAL_DEFECT", "Zoom request could not be built")) : newQueryRetry(zoomFailure("getMeeting", "TRANSPORT", "Zoom could not be reached"), 0);
532
+ const result = classify(this.client, "getMeeting", exchange), receipt = this.client.receipt(call, id, result.errorCode);
533
+ if (result.outcome === "retry") return newQueryRetry(result.failure, result.retryAfter);
534
+ if (result.outcome === "notFound") return newQueryBranch("notFound", { ...emptyMeeting, id: input.meetingId }, receipt, result.failure);
535
+ if (result.outcome === "invalid") return newQueryBranch("invalidResponse", emptyMeeting, receipt, result.failure);
536
+ if (result.outcome !== "usable") return newQueryBranch("providerRejected", emptyMeeting, receipt, result.failure);
537
+ try {
538
+ const meeting = decodeMeeting(responseObject(exchange.response.body));
539
+ if (meeting.id !== input.meetingId) throw new TypeError("wrong meeting");
540
+ return newQueryBranch("found", meeting, receipt);
541
+ } catch {
542
+ return newQueryBranch("invalidResponse", emptyMeeting, receipt, zoomFailure("getMeeting", "PROTOCOL", "Zoom returned an unusable meeting"));
543
+ }
544
+ }
545
+ };
546
+ var UpdateMeetingOperation = class {
547
+ /** Bind one Zoom client. */
548
+ constructor(client) {
549
+ this.client = client;
550
+ }
551
+ client;
552
+ /** Return the manifest definition. */
553
+ definition() {
554
+ return UpdateMeetingDefinition;
555
+ }
556
+ /** Derive the receipt key from Dex's Call ID. */
557
+ idempotencyKey(callId) {
558
+ return callId;
559
+ }
560
+ /** Invoke one repeat-safe meeting patch. */
561
+ async invoke(call, input) {
562
+ let payload;
563
+ try {
564
+ payload = updateRequest(input, /* @__PURE__ */ new Date());
565
+ } catch (error) {
566
+ return newMutationBranch("defect", emptyUpdate, zeroReceipt(), defect("updateMeeting", error));
567
+ }
568
+ const resolved = await this.client.resolveCredentials(call, "updateMeeting");
569
+ if ("failure" in resolved) return mutationCredential(resolved, emptyUpdate);
570
+ const id = String(input.meetingId), updated = { meetingId: input.meetingId };
571
+ const exchange = await this.client.exchange(call, resolved.credentials, "PATCH", `/meetings/${id}`, void 0, payload);
572
+ if ("error" in exchange) return exchange.error === "notBuilt" ? newMutationBranch("defect", emptyUpdate, zeroReceipt(), zoomFailure("updateMeeting", "LOCAL_DEFECT", "Zoom request could not be built")) : newMutationRetry(zoomFailure("updateMeeting", "TRANSPORT", "Zoom could not be reached"), 0);
573
+ if (successful(exchange.response.status)) return newMutationBranch("updated", updated, this.client.receipt(call, id));
574
+ const result = classify(this.client, "updateMeeting", exchange), receipt = this.client.receipt(call, id, result.errorCode);
575
+ if (result.outcome === "retry") return newMutationRetry(result.failure, result.retryAfter);
576
+ return newMutationBranch(result.outcome === "notFound" ? "notFound" : "providerRejected", updated, receipt, result.failure);
577
+ }
578
+ };
579
+ var ListPastMeetingParticipantsOperation = class {
580
+ /** Bind one Zoom client. */
581
+ constructor(client) {
582
+ this.client = client;
583
+ }
584
+ client;
585
+ /** Return the manifest definition. */
586
+ definition() {
587
+ return ListPastMeetingParticipantsDefinition;
588
+ }
589
+ /** Invoke one bounded participant-list request. */
590
+ async invoke(call, input) {
591
+ let query;
592
+ try {
593
+ meetingID(input.meetingId);
594
+ pageToken(input.pageToken);
595
+ query = new URLSearchParams({ page_size: String(pageSize(input.pageSize)) });
596
+ if (input.pageToken) query.set("next_page_token", input.pageToken);
597
+ } catch (error) {
598
+ return newQueryBranch("defect", emptyParticipants, zeroReceipt(), defect("listPastMeetingParticipants", error));
599
+ }
600
+ const resolved = await this.client.resolveCredentials(call, "listPastMeetingParticipants");
601
+ if ("failure" in resolved) return queryCredential(resolved, emptyParticipants);
602
+ const id = String(input.meetingId), empty = { ...emptyParticipants, meetingId: input.meetingId };
603
+ const exchange = await this.client.exchange(call, resolved.credentials, "GET", `/past_meetings/${id}/participants`, query);
604
+ if ("error" in exchange) return exchange.error === "notBuilt" ? newQueryBranch("defect", emptyParticipants, zeroReceipt(), zoomFailure("listPastMeetingParticipants", "LOCAL_DEFECT", "Zoom request could not be built")) : newQueryRetry(zoomFailure("listPastMeetingParticipants", "TRANSPORT", "Zoom could not be reached"), 0);
605
+ const result = classify(this.client, "listPastMeetingParticipants", exchange), receipt = this.client.receipt(call, id, result.errorCode);
606
+ if (result.outcome === "retry") return newQueryRetry(result.failure, result.retryAfter);
607
+ if (result.outcome === "notFound") return newQueryBranch("notFound", empty, receipt, result.failure);
608
+ if (result.outcome === "invalid") return newQueryBranch("invalidResponse", empty, receipt, result.failure);
609
+ if (result.outcome !== "usable") return newQueryBranch("providerRejected", empty, receipt, result.failure);
610
+ try {
611
+ return newQueryBranch("listed", participantPage(responseObject(exchange.response.body), input.meetingId), receipt);
612
+ } catch {
613
+ return newQueryBranch("invalidResponse", empty, receipt, zoomFailure("listPastMeetingParticipants", "PROTOCOL", "Zoom returned an unusable participant page"));
614
+ }
615
+ }
616
+ };
617
+ var CreateMeetingOperation = class {
618
+ /** Bind one Zoom client. */
619
+ constructor(client) {
620
+ this.client = client;
621
+ }
622
+ client;
623
+ /** Return the manifest definition. */
624
+ definition() {
625
+ return CreateMeetingDefinition;
626
+ }
627
+ /** Derive the receipt key from Dex's Call ID. */
628
+ idempotencyKey(callId) {
629
+ return callId;
630
+ }
631
+ /** Invoke one fenced create attempt. */
632
+ async invoke(call, input) {
633
+ let built;
634
+ try {
635
+ built = createRequest(input);
636
+ } catch (error) {
637
+ return newMutationBranch("defect", emptyMeeting, zeroReceipt(), defect("createMeeting", error));
638
+ }
639
+ let fence;
640
+ try {
641
+ fence = newFence(call, 3e4);
642
+ } catch {
643
+ return newMutationBranch("defect", emptyMeeting, zeroReceipt(), zoomFailure("createMeeting", "LOCAL_DEFECT", "Zoom create dispatch fence could not be initialized"));
644
+ }
645
+ const decision = fence.decide();
646
+ if (decision.kind === "failClosed") return newMutationUncertain(built.requested, zoomFailure("createMeeting", "TRANSPORT", "the Zoom create checkpoint could not be trusted"), this.client.receipt(call));
647
+ if (decision.kind === "readBackRequired") {
648
+ const providerId = decision.marker?.providerId;
649
+ if (!providerId || decision.marker?.callId !== call.id) return newMutationUncertain(built.requested, zoomFailure("createMeeting", "TRANSPORT", "an earlier Zoom create may have succeeded without a confirmed meeting ID"), this.client.receipt(call));
650
+ return this.readBack(call, built.requested, providerId);
651
+ }
652
+ if (Date.parse(built.requested.startTime) <= Date.now()) {
653
+ try {
654
+ await fence.recordNotSent();
655
+ } catch {
656
+ return newMutationRetry(zoomFailure("createMeeting", "AVAILABILITY", "Zoom create not-sent checkpoint was unavailable"), 0);
657
+ }
658
+ return newMutationBranch("defect", emptyMeeting, zeroReceipt(), zoomFailure("createMeeting", "VALIDATION", "startTime is not in the future, and Zoom would replace it with the current time"));
659
+ }
660
+ const resolved = await this.client.resolveCredentials(call, "createMeeting");
661
+ if ("failure" in resolved) {
662
+ try {
663
+ await fence.recordNotSent();
664
+ } catch {
665
+ return newMutationRetry(zoomFailure("createMeeting", "AVAILABILITY", "Zoom credentials and the not-sent checkpoint were unavailable"), 0);
666
+ }
667
+ return mutationCredential(resolved, emptyMeeting);
668
+ }
669
+ let exchange;
670
+ try {
671
+ exchange = await fence.dispatch((signal) => this.client.exchange(call, resolved.credentials, "POST", "/users/me/meetings", void 0, built.payload, true, signal));
672
+ } catch (error) {
673
+ if (error instanceof CheckpointError || error instanceof InsufficientTimeError) return newMutationRetry(zoomFailure("createMeeting", "AVAILABILITY", "Zoom create was not sent before the attempt deadline or checkpoint"), 0);
674
+ return newMutationUncertain(built.requested, zoomFailure("createMeeting", "TRANSPORT", "Zoom meeting outcome is unknown"), this.client.receipt(call));
675
+ }
676
+ if ("error" in exchange) {
677
+ if (exchange.error === "notBuilt") return newMutationBranch("defect", emptyMeeting, zeroReceipt(), zoomFailure("createMeeting", "LOCAL_DEFECT", "Zoom request could not be built"));
678
+ if (exchange.error === "beforeSend") {
679
+ try {
680
+ await fence.recordCanResend();
681
+ } catch {
682
+ return newMutationRetry(zoomFailure("createMeeting", "AVAILABILITY", "Zoom was not reached but the resend checkpoint failed"), 0);
683
+ }
684
+ return newMutationRetry(zoomFailure("createMeeting", "TRANSPORT", "Zoom could not be reached, so no meeting was created"), 0);
685
+ }
686
+ return newMutationUncertain(built.requested, zoomFailure("createMeeting", "TRANSPORT", "Zoom meeting outcome is unknown"), this.client.receipt(call));
687
+ }
688
+ if (successful(exchange.response.status)) {
689
+ if (exchange.isTooLarge) return newMutationUncertain(built.requested, zoomFailure("createMeeting", "RESPONSE_TOO_LARGE", "Zoom accepted the request but its response exceeds the configured size limit"), this.client.receipt(call));
690
+ if (exchange.reflectsCredential) return newMutationUncertain(built.requested, zoomFailure("createMeeting", "PROTOCOL", "Zoom accepted the request but its response contained the connection credential"), this.client.receipt(call));
691
+ let meeting;
692
+ try {
693
+ meeting = decodeMeeting(responseObject(exchange.response.body));
694
+ } catch {
695
+ return newMutationUncertain(built.requested, zoomFailure("createMeeting", "PROTOCOL", "Zoom accepted the request but returned an unusable meeting"), this.client.receipt(call));
696
+ }
697
+ try {
698
+ await fence.recordProviderId(String(meeting.id));
699
+ } catch {
700
+ }
701
+ return newMutationBranch("created", meeting, this.client.receipt(call, String(meeting.id)));
702
+ }
703
+ const result = classify(this.client, "createMeeting", exchange), receipt = this.client.receipt(call, "", result.errorCode), status = exchange.response.status;
704
+ if (status === 401) {
705
+ const refreshed = await this.client.refreshAfterRejection(call, resolved.credentials.accessToken.reveal());
706
+ if (refreshed === "unsupported") return newMutationBranch(
707
+ "providerRejected",
708
+ built.requested,
709
+ receipt,
710
+ zoomFailure("createMeeting", "AUTHENTICATION", "Zoom rejected the connection credential; reconnect the connection")
711
+ );
712
+ if (refreshed === "replaced") {
713
+ try {
714
+ await fence.recordCanResend();
715
+ } catch {
716
+ return newMutationRetry(zoomFailure("createMeeting", "AVAILABILITY", "Zoom rejected the credential but the resend checkpoint failed"), 0);
717
+ }
718
+ return newMutationRetry(result.failure, 0);
719
+ }
720
+ return newMutationBranch(
721
+ "providerRejected",
722
+ built.requested,
723
+ receipt,
724
+ zoomFailure(
725
+ "createMeeting",
726
+ refreshed === "reauthorize" ? "AUTHENTICATION" : "AVAILABILITY",
727
+ refreshed === "reauthorize" ? "Zoom connection requires reauthorization; reconnect the connection" : "Zoom credential refresh is temporarily unavailable"
728
+ )
729
+ );
730
+ }
731
+ if (status === 429 && result.outcome === "rejected") return newMutationBranch("providerRejected", built.requested, receipt, result.failure);
732
+ if (status === 429 || status === 503) {
733
+ try {
734
+ await fence.recordCanResend();
735
+ } catch {
736
+ return newMutationRetry(zoomFailure("createMeeting", "AVAILABILITY", "Zoom rejected the create but the resend checkpoint failed"), 0);
737
+ }
738
+ return newMutationRetry(result.failure, result.retryAfter);
739
+ }
740
+ if (status === 409 || status >= 500 || status === 408) return newMutationUncertain(built.requested, result.failure, receipt);
741
+ if (status >= 400 && status < 500) return newMutationBranch("providerRejected", built.requested, receipt, result.failure);
742
+ return newMutationUncertain(built.requested, result.failure, receipt);
743
+ }
744
+ async readBack(call, requested, providerId) {
745
+ const id = Number(providerId);
746
+ if (!Number.isSafeInteger(id) || id < 1) return newMutationUncertain(requested, zoomFailure("createMeeting", "PROTOCOL", "the accepted Zoom meeting ID could not be read back"), this.client.receipt(call, providerId));
747
+ const resolved = await this.client.resolveCredentials(call, "createMeeting");
748
+ if ("failure" in resolved) return resolved.retry ? newMutationRetry(resolved.failure, 0) : newMutationUncertain(requested, resolved.failure, this.client.receipt(call, providerId));
749
+ const exchange = await this.client.exchange(call, resolved.credentials, "GET", `/meetings/${providerId}`);
750
+ if ("error" in exchange) return newMutationRetry(zoomFailure("createMeeting", "TRANSPORT", "Zoom meeting read-back could not be reached"), 0);
751
+ const result = classify(this.client, "createMeeting", exchange);
752
+ if (result.outcome === "retry") return newMutationRetry(result.failure, result.retryAfter);
753
+ if (result.outcome === "usable") {
754
+ try {
755
+ const meeting = decodeMeeting(responseObject(exchange.response.body));
756
+ if (meeting.id === id) return newMutationBranch("created", meeting, this.client.receipt(call, providerId));
757
+ } catch {
758
+ }
759
+ }
760
+ return newMutationUncertain(requested, zoomFailure("createMeeting", "PROTOCOL", "Zoom could not confirm the accepted meeting"), this.client.receipt(call, providerId));
761
+ }
762
+ };
763
+
764
+ // src/client.ts
765
+ var defaultEndpoint = "https://api.zoom.us/v2";
766
+ var defaultPollIntervalMs = 12e4;
767
+ var MinimumPollIntervalMs = 3e4;
768
+ var ZoomClient2 = class {
769
+ /**
770
+ * Validate connection settings before a Step resolves credentials. An omitted or zero pollIntervalMs uses
771
+ * the manifest's two minutes; one under 30 seconds throws, as Go's New does.
772
+ */
773
+ constructor(config, credentials, options = {}) {
774
+ this.credentials = credentials;
775
+ if (!credentials) throw new TypeError("Zoom credential provider is required");
776
+ this.endpoint = validateBaseURL(config.endpoint || defaultEndpoint);
777
+ this.maxResponseBytes = config.maxResponseBytes || 2097152;
778
+ if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes < 1) throw new TypeError("Zoom maxResponseBytes must be positive");
779
+ this.pollIntervalMs = config.pollIntervalMs || defaultPollIntervalMs;
780
+ if (!Number.isFinite(this.pollIntervalMs) || this.pollIntervalMs < MinimumPollIntervalMs) throw new TypeError("Zoom pollInterval must be at least 30s");
781
+ this.send = options.send ?? sendProviderRequest;
782
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
783
+ }
784
+ credentials;
785
+ endpoint;
786
+ maxResponseBytes;
787
+ /** The meetingChanged Trigger's delay between polls in milliseconds; at least MinimumPollIntervalMs. */
788
+ pollIntervalMs;
789
+ send;
790
+ now;
791
+ /** The generated OAuth refresh policy every credential resolution uses, including Trigger polls. */
792
+ refreshDriver = new ManifestCredentialRefreshDriver({ providerName: "Zoom", auth: Authorization, credentialFields: CredentialFields });
793
+ /** The client clock, used for receipts, Retry-After, and Trigger observation times. */
794
+ currentTime() {
795
+ return this.now();
796
+ }
797
+ /** Bind the meeting list query. */
798
+ listMeetings() {
799
+ return new ListMeetingsOperation(this);
800
+ }
801
+ /** Bind the meeting detail query. */
802
+ getMeeting() {
803
+ return new GetMeetingOperation(this);
804
+ }
805
+ /** Bind the fenced meeting create mutation. */
806
+ createMeeting() {
807
+ return new CreateMeetingOperation(this);
808
+ }
809
+ /** Bind the meeting patch mutation. */
810
+ updateMeeting() {
811
+ return new UpdateMeetingOperation(this);
812
+ }
813
+ /** Bind the participant list query. */
814
+ listPastMeetingParticipants() {
815
+ return new ListPastMeetingParticipantsOperation(this);
816
+ }
817
+ /** Resolve generated renewable credentials and preserve terminal versus retryable failures. */
818
+ async resolveCredentials(call, operation) {
819
+ try {
820
+ const credentials = await resolveCredential(this.credentials, call, this.refreshDriver, call.context.cancellationSignal);
821
+ if (!credentials.accessToken || !isHeaderSafeCredential(credentials.accessToken.reveal()))
822
+ return { failure: zoomFailure(operation, "AUTHENTICATION", "Zoom connection credentials are unavailable; reconnect the connection"), retry: false };
823
+ return { credentials };
824
+ } catch (error) {
825
+ if (error instanceof ReauthorizationRequiredError) return { failure: zoomFailure(operation, "AUTHENTICATION", "Zoom connection requires reauthorization; reconnect the connection"), retry: false };
826
+ return { failure: zoomFailure(operation, "AVAILABILITY", "Zoom connection credentials could not be refreshed"), retry: true };
827
+ }
828
+ }
829
+ /** Force one generated refresh after Zoom rejects a fenced create credential. */
830
+ async refreshAfterRejection(call, previousAccessToken) {
831
+ if (!("resolveAfterRejection" in this.credentials)) return "unsupported";
832
+ try {
833
+ const replacement = await resolveCredentialAfterRejection(this.credentials, call, this.refreshDriver, call.context.cancellationSignal);
834
+ return replacement.accessToken?.reveal() && replacement.accessToken.reveal() !== previousAccessToken ? "replaced" : "reauthorize";
835
+ } catch (error) {
836
+ return error instanceof ReauthorizationRequiredError ? "reauthorize" : "retryable";
837
+ }
838
+ }
839
+ /** Send one bounded request and refresh once after a rejected credential when allowed. */
840
+ async exchange(call, credentials, method, path, query, payload, isFencedWrite = false, signal) {
841
+ const queryString = query ? encodeGoQuery(query) : "";
842
+ const url = `${this.endpoint}${path}${queryString ? `?${queryString}` : ""}`;
843
+ for (let attempt = 0; attempt < 2; attempt++) {
844
+ const accessToken = credentials.accessToken.reveal();
845
+ const request = {
846
+ url,
847
+ method,
848
+ headers: { Authorization: `Bearer ${accessToken}`, Accept: "application/json", ...payload === void 0 ? {} : { "Content-Type": "application/json" } },
849
+ ...payload === void 0 ? {} : { body: Buffer.from(JSON.stringify(payload), "utf8") },
850
+ maxResponseBytes: Math.max(this.maxResponseBytes, MaxErrorBodyBytes),
851
+ maxErrorResponseBytes: MaxErrorBodyBytes,
852
+ ignoreErrorBodyReadFailure: true,
853
+ timeoutMs: 2e4,
854
+ addressPolicy: "unrestricted",
855
+ signal: signal ?? call.context.cancellationSignal
856
+ };
857
+ let result;
858
+ try {
859
+ const response = await this.send(request);
860
+ const isTooLarge = response.status >= 200 && response.status < 300 && response.body.length > this.maxResponseBytes;
861
+ result = {
862
+ response: { ...response, body: isTooLarge ? new Uint8Array() : response.body },
863
+ isTooLarge,
864
+ reflectsCredential: !isTooLarge && accessToken !== "" && Buffer.from(response.body).includes(Buffer.from(accessToken))
865
+ };
866
+ } catch (error) {
867
+ if (error instanceof BodyTooLargeError && error.status !== void 0) result = { response: { status: error.status, headers: error.headers ?? {}, body: new Uint8Array() }, isTooLarge: error.status >= 200 && error.status < 300, reflectsCredential: false };
868
+ else if (error instanceof ProviderTransportError) return { error: error.isProvablyNotSent ? "beforeSend" : "afterSend" };
869
+ else if (error instanceof AddressRefusal || error instanceof TypeError) return { error: "notBuilt" };
870
+ else return { error: "afterSend" };
871
+ }
872
+ if (result.response.status !== 401 || attempt !== 0 || isFencedWrite || !("resolveAfterRejection" in this.credentials)) return result;
873
+ try {
874
+ credentials = await resolveCredentialAfterRejection(this.credentials, call, this.refreshDriver, call.context.cancellationSignal);
875
+ if (!credentials.accessToken?.reveal()) return result;
876
+ } catch {
877
+ return result;
878
+ }
879
+ }
880
+ return { error: "afterSend" };
881
+ }
882
+ /** Build a secret-free receipt containing only the provider meeting ID and numeric error code. */
883
+ receipt(call, objectId = "", errorCode = "") {
884
+ return {
885
+ callId: call.id,
886
+ ...call.idempotencyKey ? { idempotencyKey: call.idempotencyKey } : {},
887
+ provider: "zoom",
888
+ ...objectId ? { providerObjectId: objectId } : {},
889
+ observedAt: this.now().toISOString(),
890
+ ...errorCode ? { metadata: { zoomErrorCode: errorCode } } : {}
891
+ };
892
+ }
893
+ /** Parse Retry-After with the SDK's bounded rules. */
894
+ retryAfter(headers) {
895
+ const value = headers["retry-after"];
896
+ return parseRetryAfter(typeof value === "string" ? value : "", this.now());
897
+ }
898
+ };
899
+ function zoomFailure(operation, kind, message) {
900
+ return { kind, provider: "zoom", operation, message };
901
+ }
902
+ function encodeGoQuery(query) {
903
+ const escape = (value) => encodeURIComponent(value).replace(/%20/g, "+").replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
904
+ return [...query].sort(([left], [right]) => Buffer.compare(Buffer.from(left), Buffer.from(right))).map(([key, value]) => `${escape(key)}=${escape(value)}`).join("&");
905
+ }
906
+
907
+ // src/project.ts
908
+ function encodeCredentials(credentials) {
909
+ return {
910
+ oauth_client_id: credentials.oauthClientId,
911
+ oauth_client_secret: credentials.oauthClientSecret.reveal(),
912
+ access_token: credentials.accessToken.reveal(),
913
+ refresh_token: credentials.refreshToken.reveal()
914
+ };
915
+ }
916
+ function newProjectConnection2(project, connectionName, options = {}) {
917
+ return newProjectConnection(project, connectionName, (loadedProject, name) => {
918
+ const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "zoom" && entry.connectionName === name);
919
+ if (!selected) throw new TypeError("Zoom project connection is not configured");
920
+ const config = ConfigSchema.parse(selected.configuration);
921
+ const pollIntervalMs = pollIntervalMilliseconds(selected.configuration.pollInterval);
922
+ return new ZoomClient2({
923
+ ...config.endpoint !== void 0 ? { endpoint: config.endpoint } : {},
924
+ ...config.maxResponseBytes !== void 0 ? { maxResponseBytes: config.maxResponseBytes } : {},
925
+ ...pollIntervalMs !== void 0 ? { pollIntervalMs } : {}
926
+ }, newProjectCredentialProvider(loadedProject, name, decodeCredentials, encodeCredentials, decodeSharedCredentials), options);
927
+ });
928
+ }
929
+ function pollIntervalMilliseconds(value) {
930
+ if (value === void 0 || value === null) return void 0;
931
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new TypeError("Zoom configuration pollInterval has an invalid type");
932
+ return value / 1e6;
933
+ }
934
+
935
+ // src/meeting_snapshot.ts
936
+ import { createHash } from "crypto";
937
+ import { z } from "zod";
938
+ var MeetingChangeScheduled = "scheduled";
939
+ var MeetingChangeUpdated = "updated";
940
+ var MeetingChangeRemoved = "removed";
941
+ var MeetingChangeKindSchema = z.enum([MeetingChangeScheduled, MeetingChangeUpdated, MeetingChangeRemoved]);
942
+ var MeetingChangedTriggerConfigurationSchema = z.strictObject({
943
+ /**
944
+ * Limits deliveries to these kinds; empty delivers scheduled, updated, and removed. Skipped kinds still
945
+ * advance the stored snapshot, so they are never delivered later.
946
+ */
947
+ changeKinds: z.array(z.string()).nullable().optional()
948
+ }).superRefine((configuration, context) => {
949
+ const seen = /* @__PURE__ */ new Set();
950
+ for (const kind of configuration.changeKinds ?? []) {
951
+ if (!MeetingChangeKindSchema.safeParse(kind).success) context.addIssue({ code: "custom", message: `meetingChanged changeKinds entry ${JSON.stringify(kind)} must be scheduled, updated, or removed` });
952
+ else if (seen.has(kind)) context.addIssue({ code: "custom", message: `meetingChanged changeKinds repeats ${JSON.stringify(kind)}` });
953
+ seen.add(kind);
954
+ }
955
+ });
956
+ var MeetingChangedEventSchema = z.object({
957
+ /** The derived change kind. */
958
+ changeKind: MeetingChangeKindSchema,
959
+ /**
960
+ * The meeting as this poll listed it. For a removed meeting it is the last listed state, without uuid or
961
+ * joinUrl, which the stored snapshot never keeps.
962
+ */
963
+ meeting: MeetingSummarySchema,
964
+ /** The state the previous poll listed, without uuid or joinUrl; set only for updated. */
965
+ previousMeeting: MeetingSummarySchema.optional()
966
+ });
967
+ function deliversMeetingChange(configuration, kind) {
968
+ const kinds = configuration.changeKinds ?? [];
969
+ return kinds.length === 0 || kinds.includes(kind);
970
+ }
971
+ function goJSON(value) {
972
+ const text = typeof value === "string" ? JSON.stringify(wellFormed(value)) : JSON.stringify(value);
973
+ return text.replace(/[<>&\u2028\u2029]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
974
+ }
975
+ function trackedMeetingJSON(summary) {
976
+ const fields = [["id", summary.id]];
977
+ if (summary.hostId) fields.push(["hostId", summary.hostId]);
978
+ fields.push(["topic", summary.topic]);
979
+ if (summary.type) fields.push(["type", summary.type]);
980
+ if (summary.startTime) fields.push(["startTime", summary.startTime]);
981
+ if (summary.durationMinutes) fields.push(["durationMinutes", summary.durationMinutes]);
982
+ if (summary.timeZone) fields.push(["timeZone", summary.timeZone]);
983
+ if (summary.agenda) fields.push(["agenda", summary.agenda]);
984
+ if (summary.createdAt) fields.push(["createdAt", summary.createdAt]);
985
+ return Buffer.from(`{${fields.map(([name, value]) => `${goJSON(name)}:${goJSON(value)}`).join(",")}}`, "utf8");
986
+ }
987
+ function instantNanoseconds(timestamp) {
988
+ const [whole = "", fraction = ""] = timestamp.replace(/Z$/, "").split(".");
989
+ return BigInt(Date.parse(`${whole}Z`)) * 1000000n + BigInt(fraction.padEnd(9, "0").slice(0, 9) || "0");
990
+ }
991
+ function wellFormed(text) {
992
+ return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "\uFFFD");
993
+ }
994
+ var ListedMeeting = class {
995
+ /** Keep the listed summary beside its tracked JSON. */
996
+ constructor(summary) {
997
+ this.summary = summary;
998
+ this.value = trackedMeetingJSON(summary);
999
+ this.#hash = createHash("sha256").update(this.value).digest().subarray(0, 16).toString("hex");
1000
+ }
1001
+ summary;
1002
+ /** The tracked JSON, so a removal or update carries the last listed state. */
1003
+ value;
1004
+ #hash;
1005
+ /** The decimal meeting ID. */
1006
+ snapshotKey() {
1007
+ return String(this.summary.id);
1008
+ }
1009
+ /** The first 16 bytes of SHA-256 over the tracked fields. */
1010
+ snapshotHash() {
1011
+ return this.#hash;
1012
+ }
1013
+ /** The tracked JSON. */
1014
+ snapshotValue() {
1015
+ return this.value;
1016
+ }
1017
+ /** Order two listings of one meeting ID: the earlier start, then the smaller hash. */
1018
+ listsBefore(other) {
1019
+ const start2 = this.summary.startTime, otherStart = other.summary.startTime;
1020
+ if (start2 && otherStart) {
1021
+ const startNanoseconds = instantNanoseconds(start2), otherNanoseconds = instantNanoseconds(otherStart);
1022
+ if (startNanoseconds !== otherNanoseconds) return startNanoseconds < otherNanoseconds;
1023
+ } else if (!start2 !== !otherStart) return Boolean(start2);
1024
+ return this.#hash < other.#hash;
1025
+ }
1026
+ };
1027
+ var trackedMeetingSchema = z.object({
1028
+ id: z.number().int().positive(),
1029
+ hostId: z.string().nullish(),
1030
+ topic: z.string().nullish(),
1031
+ type: z.number().int().nullish(),
1032
+ startTime: z.string().nullish(),
1033
+ durationMinutes: z.number().int().nullish(),
1034
+ timeZone: z.string().nullish(),
1035
+ agenda: z.string().nullish(),
1036
+ createdAt: z.string().nullish()
1037
+ });
1038
+ function decodeTrackedMeeting(entry) {
1039
+ let tracked;
1040
+ try {
1041
+ tracked = trackedMeetingSchema.parse(JSON.parse(Buffer.from(entry.value ?? new Uint8Array()).toString("utf8")));
1042
+ } catch {
1043
+ throw new Error("stored Zoom meeting snapshot entry is invalid");
1044
+ }
1045
+ if (String(tracked.id) !== entry.key) throw new Error("stored Zoom meeting snapshot entry is invalid");
1046
+ const summary = { id: tracked.id, topic: tracked.topic ?? "" };
1047
+ if (tracked.hostId) summary.hostId = tracked.hostId;
1048
+ if (tracked.type) summary.type = tracked.type;
1049
+ if (tracked.startTime) summary.startTime = tracked.startTime;
1050
+ if (tracked.durationMinutes) summary.durationMinutes = tracked.durationMinutes;
1051
+ if (tracked.timeZone) summary.timeZone = tracked.timeZone;
1052
+ if (tracked.agenda) summary.agenda = tracked.agenda;
1053
+ if (tracked.createdAt) summary.createdAt = tracked.createdAt;
1054
+ return summary;
1055
+ }
1056
+ function meetingChangeId(kind, key, previous, currentHash, sequence) {
1057
+ const parts = [kind, key, currentHash];
1058
+ if (previous) parts.push(previous.hash, String(previous.seen));
1059
+ else if (sequence > 0) parts.push(String(sequence));
1060
+ const digest = createHash("sha256").update(wellFormed(parts.join("\0")), "utf8").digest();
1061
+ return `zoom-meeting-${digest.subarray(0, 16).toString("hex")}`;
1062
+ }
1063
+ function newMeetingChangedTriggerEvent(previous, currentHash, sequence, payload, observedAt) {
1064
+ const key = String(payload.meeting.id);
1065
+ const occurredAt = payload.changeKind === MeetingChangeScheduled && payload.meeting.createdAt ? new Date(payload.meeting.createdAt) : observedAt;
1066
+ return { id: meetingChangeId(payload.changeKind, key, previous, currentHash, sequence), occurredAt, payload };
1067
+ }
1068
+
1069
+ // src/trigger.ts
1070
+ import {
1071
+ mustTriggerBindingDefinition,
1072
+ newTrigger
1073
+ } from "@superdurable/connectors-sdk";
1074
+ import { newBindingPoller, newBindingTriggerSource, newMemoryCursorStore, newRunner } from "@superdurable/connectors-sdk/pollingtrigger";
1075
+ import { ObjectNotFoundError, decodeTriggerConfiguration, newDurableTriggerTarget } from "@superdurable/connectors-sdk/projectconfig";
1076
+
1077
+ // src/meeting_list_fetcher.ts
1078
+ import { ReauthorizationRequiredError as ReauthorizationRequiredError2, TriggerDeliveryAbortedError, resolveCredential as resolveCredential2 } from "@superdurable/connectors-sdk";
1079
+ import {
1080
+ DefaultKeyedSnapshotEntries,
1081
+ applyKeyedSnapshotChanges,
1082
+ diffKeyedSnapshot,
1083
+ markCursorInvalid,
1084
+ markRateLimited,
1085
+ newTriggerCredentialCall,
1086
+ waitForPollRequest
1087
+ } from "@superdurable/connectors-sdk/pollingtrigger";
1088
+ import { isHeaderSafeCredential as isHeaderSafeCredential2 } from "@superdurable/connectors-sdk/providerhttp";
1089
+ var meetingListCursorVersion = 1;
1090
+ var maximumPageSize = 300;
1091
+ var maximumMeetingListPages = Math.floor(DefaultKeyedSnapshotEntries / maximumPageSize) + 2;
1092
+ var MeetingChangesPerPage = 100;
1093
+ var MeetingSnapshotOptions = { keepValues: true };
1094
+ var PageTokenRejectedError = class extends Error {
1095
+ };
1096
+ function encodeMeetingListCursor(position) {
1097
+ const fields = [`"version":${position.version}`];
1098
+ if (position.hostId) fields.push(`"hostId":${goJSON(position.hostId)}`);
1099
+ if (position.sequence) fields.push(`"sequence":${position.sequence}`);
1100
+ return `{${fields.join(",")}}`;
1101
+ }
1102
+ function decodeMeetingListCursor(token) {
1103
+ let value;
1104
+ try {
1105
+ value = responseObjectOrNull(token);
1106
+ } catch {
1107
+ return void 0;
1108
+ }
1109
+ if (value === null) return { version: 0, hostId: "", sequence: 0 };
1110
+ const raw = value;
1111
+ try {
1112
+ const hostId = raw.hostId ?? "";
1113
+ if (typeof hostId !== "string") return void 0;
1114
+ return { version: integer(raw.version), hostId, sequence: integer(raw.sequence) };
1115
+ } catch {
1116
+ return void 0;
1117
+ }
1118
+ }
1119
+ function responseObjectOrNull(token) {
1120
+ if (token.trim() === "null") return null;
1121
+ return responseObject(Buffer.from(token, "utf8"));
1122
+ }
1123
+ function soleHostId(listing) {
1124
+ return listing.hostIds.size === 1 ? [...listing.hostIds][0] : "";
1125
+ }
1126
+ var compareKeys = (left, right) => Buffer.compare(Buffer.from(left), Buffer.from(right));
1127
+ var MeetingListFetcher = class {
1128
+ /** Bind the client, connection, Trigger identity, and validated configuration. */
1129
+ constructor(client, connection, trigger, configuration) {
1130
+ this.client = client;
1131
+ this.connection = connection;
1132
+ this.trigger = trigger;
1133
+ this.configuration = configuration;
1134
+ }
1135
+ client;
1136
+ connection;
1137
+ trigger;
1138
+ configuration;
1139
+ /** List every scheduled meeting and keep the listing as the baseline without delivering it. */
1140
+ async seedCursor(context) {
1141
+ const listing = await this.listAllMeetings(context);
1142
+ const diff = withMessagePrefix("Zoom meeting baseline", () => diffKeyedSnapshot(void 0, listing.meetings, MeetingSnapshotOptions));
1143
+ return { token: encodeMeetingListCursor({ version: meetingListCursorVersion, hostId: soleHostId(listing), sequence: 0 }), snapshot: diff.next };
1144
+ }
1145
+ /** Return up to MeetingChangesPerPage snapshot differences; a foreign or undecodable cursor reseeds. */
1146
+ async fetchChanges(context, cursor) {
1147
+ const position = decodeMeetingListCursor(cursor.token);
1148
+ if (!position || position.version !== meetingListCursorVersion || !cursor.snapshot) throw markCursorInvalid(new Error("Zoom meeting list cursor is not decodable"));
1149
+ const listing = await this.listAllMeetings(context);
1150
+ if (position.hostId && listing.meetings.length > 0 && !listing.hostIds.has(position.hostId)) {
1151
+ throw markCursorInvalid(new Error("Zoom meeting list belongs to another Zoom user than the stored snapshot"));
1152
+ }
1153
+ if (!position.hostId) position.hostId = soleHostId(listing);
1154
+ const stored = cursor.snapshot;
1155
+ const diff = withMessagePrefix("Zoom meeting snapshot", () => diffKeyedSnapshot(stored, listing.meetings, MeetingSnapshotOptions));
1156
+ let changes = orderedMeetingChanges(diff, listing);
1157
+ let next = diff.next, hasMorePages = false;
1158
+ const sequence = position.sequence;
1159
+ if (changes.length > 0) position.sequence++;
1160
+ if (changes.length > MeetingChangesPerPage) {
1161
+ changes = changes.slice(0, MeetingChangesPerPage);
1162
+ hasMorePages = true;
1163
+ next = applyMeetingChanges(stored, changes);
1164
+ }
1165
+ const observedAt = this.client.currentTime();
1166
+ const events = changes.filter((change) => deliversMeetingChange(this.configuration, change.kind)).map((change) => changeTriggerEvent(change, sequence, observedAt));
1167
+ return { changes: events, next: { token: encodeMeetingListCursor(position), snapshot: next }, hasMorePages };
1168
+ }
1169
+ // Zoom expires page tokens after 15 minutes, so a 400 on a later page restarts the listing once.
1170
+ async listAllMeetings(context) {
1171
+ try {
1172
+ return await this.doListAllMeetings(context);
1173
+ } catch (error) {
1174
+ if (!(error instanceof PageTokenRejectedError)) throw error;
1175
+ }
1176
+ try {
1177
+ return await this.doListAllMeetings(context);
1178
+ } catch (error) {
1179
+ if (error instanceof PageTokenRejectedError) throw new Error(error.message);
1180
+ throw error;
1181
+ }
1182
+ }
1183
+ async doListAllMeetings(context) {
1184
+ const listing = { meetings: [], byKey: /* @__PURE__ */ new Map(), hostIds: /* @__PURE__ */ new Set() };
1185
+ const requestedPageTokens = /* @__PURE__ */ new Set();
1186
+ let currentPageToken = "";
1187
+ for (let pageNumber = 0; pageNumber < maximumMeetingListPages; pageNumber++) {
1188
+ const listed = await this.listMeetingPage(context, currentPageToken);
1189
+ for (const summary of listed.meetings ?? []) {
1190
+ const meeting = new ListedMeeting(summary), key = meeting.snapshotKey();
1191
+ const existing = listing.byKey.get(key);
1192
+ if (!existing || meeting.listsBefore(existing)) listing.byKey.set(key, meeting);
1193
+ if (summary.hostId) listing.hostIds.add(summary.hostId);
1194
+ }
1195
+ if (!listed.nextPageToken) {
1196
+ listing.meetings = [...listing.byKey.keys()].sort(compareKeys).map((key) => listing.byKey.get(key));
1197
+ return listing;
1198
+ }
1199
+ if (requestedPageTokens.has(listed.nextPageToken)) throw new Error("Zoom meeting list repeated a page token");
1200
+ requestedPageTokens.add(listed.nextPageToken);
1201
+ currentPageToken = listed.nextPageToken;
1202
+ }
1203
+ throw new Error(`Zoom meeting list exceeded ${maximumMeetingListPages} pages`);
1204
+ }
1205
+ /** Send one List meetings request; a 400 to a page token rejects with PageTokenRejectedError. */
1206
+ async listMeetingPage(context, currentPageToken) {
1207
+ await waitForPollRequest(context);
1208
+ const call = newTriggerCredentialCall(this.connection, this.trigger, context.signal);
1209
+ const credentials = await this.resolveCredentials(call, context.signal);
1210
+ const query = new URLSearchParams({ type: "scheduled", page_size: String(maximumPageSize) });
1211
+ if (currentPageToken) query.set("next_page_token", currentPageToken);
1212
+ const exchange = await this.client.exchange(call, credentials, "GET", "/users/me/meetings", query, void 0, false, context.signal);
1213
+ if (context.signal.aborted) throw new TriggerDeliveryAbortedError();
1214
+ if ("error" in exchange) throw new Error("Zoom meeting list request could not reach Zoom");
1215
+ if (currentPageToken && exchange.response.status === 400) throw new PageTokenRejectedError("Zoom rejected the meeting list page token with HTTP 400");
1216
+ const classified = classify(this.client, "listMeetings", exchange);
1217
+ if (classified.outcome !== "usable") {
1218
+ const failure = new Error(`Zoom meeting list request: ${classified.failure?.message ?? "Zoom returned an unusable meeting page"}`);
1219
+ if (exchange.response.status === 429) throw markRateLimited(failure, this.client.retryAfter(exchange.response.headers));
1220
+ throw failure;
1221
+ }
1222
+ try {
1223
+ return decodeMeetingPage(exchange.response.body);
1224
+ } catch {
1225
+ throw new Error("Zoom returned an unusable meeting page");
1226
+ }
1227
+ }
1228
+ async resolveCredentials(call, signal) {
1229
+ let credentials;
1230
+ try {
1231
+ credentials = await resolveCredential2(this.client.credentials, call, this.client.refreshDriver, signal);
1232
+ } catch (error) {
1233
+ if (error instanceof ReauthorizationRequiredError2) throw new Error("Zoom connection requires reauthorization; reconnect the connection");
1234
+ throw new Error("Zoom Trigger credentials are unavailable");
1235
+ }
1236
+ if (!credentials.accessToken || !isHeaderSafeCredential2(credentials.accessToken.reveal())) throw new Error("Zoom Trigger credentials are unavailable");
1237
+ return credentials;
1238
+ }
1239
+ };
1240
+ function decodeMeetingPage(body) {
1241
+ const raw = responseObject(body), total = integer(raw.total_records), next = raw.next_page_token ?? "";
1242
+ if (total < 0 || typeof next !== "string" || raw.meetings !== void 0 && raw.meetings !== null && !Array.isArray(raw.meetings)) throw new TypeError("invalid page");
1243
+ pageToken(next);
1244
+ const meetings = (raw.meetings ?? []).map((item) => meetingSummary(decodeMeeting(item)));
1245
+ return { meetings, totalRecords: total, ...next ? { nextPageToken: next } : {} };
1246
+ }
1247
+ function withMessagePrefix(prefix, compute) {
1248
+ try {
1249
+ return compute();
1250
+ } catch (error) {
1251
+ if (error instanceof Error) error.message = `${prefix}: ${error.message}`;
1252
+ throw error;
1253
+ }
1254
+ }
1255
+ function orderedMeetingChanges(diff, listing) {
1256
+ const changes = [
1257
+ ...diff.added.map((added) => ({ kind: MeetingChangeScheduled, key: added.key, current: listing.byKey.get(added.key) })),
1258
+ ...diff.changed.map((changed) => ({ kind: MeetingChangeUpdated, key: changed.current.key, previous: changed.previous, current: listing.byKey.get(changed.current.key) })),
1259
+ ...diff.removed.map((removed) => ({ kind: MeetingChangeRemoved, key: removed.key, previous: removed }))
1260
+ ];
1261
+ return changes.sort((left, right) => compareKeys(left.key, right.key));
1262
+ }
1263
+ function applyMeetingChanges(previous, changes) {
1264
+ const upserted = changes.flatMap((change) => change.current ? [change.current] : []);
1265
+ const removedKeys = changes.filter((change) => change.kind === MeetingChangeRemoved).map((change) => change.key);
1266
+ return withMessagePrefix("Zoom meeting snapshot", () => applyKeyedSnapshotChanges(previous, upserted, removedKeys, MeetingSnapshotOptions));
1267
+ }
1268
+ function changeTriggerEvent(change, sequence, observedAt) {
1269
+ const payload = { changeKind: change.kind, meeting: change.current?.summary ?? { id: 0, topic: "" } };
1270
+ if (change.previous) {
1271
+ const previous = decodeTrackedMeeting(change.previous);
1272
+ if (change.kind === MeetingChangeRemoved) payload.meeting = previous;
1273
+ else payload.previousMeeting = previous;
1274
+ }
1275
+ return newMeetingChangedTriggerEvent(change.previous, change.current?.snapshotHash() ?? "", sequence, payload, observedAt);
1276
+ }
1277
+
1278
+ // src/trigger.ts
1279
+ var MeetingChangedTriggerDefinition = {
1280
+ trigger: { connectorId: ConnectorID, triggerName: "meetingChanged" },
1281
+ description: "Receive each meeting the authorized user schedules, changes, or that leaves Zoom's scheduled list, found by comparing each poll of List meetings with the last; the first run records a baseline and delivers no existing meetings."
1282
+ };
1283
+ function defineMeetingChangedTriggerBinding(config) {
1284
+ return mustTriggerBindingDefinition({ definition: MeetingChangedTriggerDefinition, ...config });
1285
+ }
1286
+ function newMeetingTriggerRunner(connection, routes, options = {}) {
1287
+ const client = zoomClientOf(connection);
1288
+ if (!routes?.length) throw new TypeError("Zoom meetingChanged routes are required");
1289
+ const pollers = routes.map((route) => {
1290
+ if (!route?.bindingName?.trim() || !route.target) throw new TypeError("Zoom meetingChanged binding name and target are required");
1291
+ const configuration = parseConfiguration(route.configuration ?? {});
1292
+ return newBindingPoller({
1293
+ definition: MeetingChangedTriggerDefinition,
1294
+ binding: { connection: connection.reference, trigger: MeetingChangedTriggerDefinition.trigger, name: route.bindingName },
1295
+ cursor: route.cursor ?? newMemoryCursorStore(),
1296
+ fetcher: new MeetingListFetcher(client, connection.reference, MeetingChangedTriggerDefinition.trigger, configuration),
1297
+ target: route.target,
1298
+ snapshot: MeetingSnapshotOptions
1299
+ });
1300
+ });
1301
+ return newRunner({ connection: connection.reference, schedule: pollSchedule(client), pollers, ...options.logger ? { logger: options.logger } : {} });
1302
+ }
1303
+ function newProjectMeetingTriggerRunner(project, connection, routes, options = {}) {
1304
+ if (!project) throw new TypeError("Zoom meetingChanged runner requires the loaded project configuration");
1305
+ const durableRoutes = (routes ?? []).map((route) => {
1306
+ if (!route?.target) throw new TypeError(`Zoom meetingChanged binding ${JSON.stringify(route?.bindingName)} target is required`);
1307
+ const key = { connectorId: ConnectorID, connectionName: connection.reference.name, triggerName: MeetingChangedTriggerDefinition.trigger.triggerName, bindingName: route.bindingName };
1308
+ let configuration = {};
1309
+ try {
1310
+ configuration = decodeTriggerConfiguration(project.configuration, key, MeetingChangedTriggerConfigurationSchema);
1311
+ } catch (error) {
1312
+ if (!(error instanceof ObjectNotFoundError)) throw new TypeError(`zoom meetingChanged binding ${JSON.stringify(route.bindingName)} configuration: ${error instanceof Error ? error.message : String(error)}`);
1313
+ }
1314
+ const target = newDurableTriggerTarget(project.triggerInbox(key), key, route.target, { decodePayload: decodeMeetingChangedEventPayload, ...options.logger ? { logger: options.logger } : {} });
1315
+ return { bindingName: route.bindingName, configuration, target, cursor: project.pollCursorStore(key) };
1316
+ });
1317
+ return newMeetingTriggerRunner(connection, durableRoutes, options);
1318
+ }
1319
+ function newMeetingChangedTrigger(config) {
1320
+ const client = zoomClientOf(config.connection);
1321
+ if (!config.bindingName?.trim() || !config.target) throw new TypeError("Zoom meetingChanged binding name and target are required");
1322
+ const configuration = parseConfiguration(config.configuration ?? {});
1323
+ const binding = { connection: config.connection.reference, trigger: MeetingChangedTriggerDefinition.trigger, name: config.bindingName };
1324
+ const source = newBindingTriggerSource({
1325
+ definition: MeetingChangedTriggerDefinition,
1326
+ binding,
1327
+ cursor: newMemoryCursorStore(),
1328
+ fetcher: new MeetingListFetcher(client, config.connection.reference, MeetingChangedTriggerDefinition.trigger, configuration),
1329
+ snapshot: MeetingSnapshotOptions
1330
+ }, pollSchedule(client), config.logger);
1331
+ return newTrigger({ definition: MeetingChangedTriggerDefinition, binding, source, target: config.target, ...config.logger ? { logger: config.logger } : {} });
1332
+ }
1333
+ function decodeMeetingChangedEventPayload(payloadJSON) {
1334
+ const parsed = MeetingChangedEventSchema.safeParse(JSON.parse(payloadJSON));
1335
+ if (!parsed.success) throw new TypeError("stored Zoom meetingChanged payload is invalid");
1336
+ return parsed.data;
1337
+ }
1338
+ function parseConfiguration(configuration) {
1339
+ const parsed = MeetingChangedTriggerConfigurationSchema.safeParse(configuration);
1340
+ if (!parsed.success) throw new TypeError(`zoom meetingChanged configuration: ${parsed.error.issues.map((issue) => issue.message).join("; ")}`);
1341
+ return parsed.data;
1342
+ }
1343
+ function zoomClientOf(connection) {
1344
+ if (!(connection?.operations instanceof ZoomClient2)) throw new TypeError("Zoom meetingChanged Trigger requires a connection from newProjectConnection or newConnection with a ZoomClient");
1345
+ return connection.operations;
1346
+ }
1347
+ function pollSchedule(client) {
1348
+ return { intervalMs: client.pollIntervalMs };
1349
+ }
1350
+ export {
1351
+ ConfigSchema,
1352
+ Connection,
1353
+ ConnectorID,
1354
+ CreateMeetingBranch,
1355
+ CreateMeetingBranchCreated,
1356
+ CreateMeetingBranchDefect,
1357
+ CreateMeetingBranchProviderRejected,
1358
+ CreateMeetingBranchUncertain,
1359
+ CreateMeetingDefinition,
1360
+ CreateMeetingInputSchema,
1361
+ CreateMeetingMetadata,
1362
+ CreateMeetingOperation,
1363
+ GetMeetingBranch,
1364
+ GetMeetingBranchDefect,
1365
+ GetMeetingBranchFound,
1366
+ GetMeetingBranchInvalidResponse,
1367
+ GetMeetingBranchNotFound,
1368
+ GetMeetingBranchProviderRejected,
1369
+ GetMeetingDefinition,
1370
+ GetMeetingInputSchema,
1371
+ GetMeetingMetadata,
1372
+ GetMeetingOperation,
1373
+ ListMeetingsBranch,
1374
+ ListMeetingsBranchDefect,
1375
+ ListMeetingsBranchInvalidResponse,
1376
+ ListMeetingsBranchListed,
1377
+ ListMeetingsBranchProviderRejected,
1378
+ ListMeetingsDefinition,
1379
+ ListMeetingsInputSchema,
1380
+ ListMeetingsMetadata,
1381
+ ListMeetingsOperation,
1382
+ ListPastMeetingParticipantsBranch,
1383
+ ListPastMeetingParticipantsBranchDefect,
1384
+ ListPastMeetingParticipantsBranchInvalidResponse,
1385
+ ListPastMeetingParticipantsBranchListed,
1386
+ ListPastMeetingParticipantsBranchNotFound,
1387
+ ListPastMeetingParticipantsBranchProviderRejected,
1388
+ ListPastMeetingParticipantsDefinition,
1389
+ ListPastMeetingParticipantsInputSchema,
1390
+ ListPastMeetingParticipantsMetadata,
1391
+ ListPastMeetingParticipantsOperation,
1392
+ MeetingChangeKindSchema,
1393
+ MeetingChangeRemoved,
1394
+ MeetingChangeScheduled,
1395
+ MeetingChangeUpdated,
1396
+ MeetingChangedEventSchema,
1397
+ MeetingChangedTriggerConfigurationSchema,
1398
+ MeetingChangedTriggerDefinition,
1399
+ MeetingPageSchema,
1400
+ MeetingParticipantSchema,
1401
+ MeetingSchema,
1402
+ MeetingSettingsInputSchema,
1403
+ MeetingSettingsSchema,
1404
+ MeetingSummarySchema,
1405
+ MinimumPollIntervalMs,
1406
+ ParticipantPageSchema,
1407
+ ProviderID,
1408
+ UpdateMeetingBranch,
1409
+ UpdateMeetingBranchDefect,
1410
+ UpdateMeetingBranchNotFound,
1411
+ UpdateMeetingBranchProviderRejected,
1412
+ UpdateMeetingBranchUpdated,
1413
+ UpdateMeetingDefinition,
1414
+ UpdateMeetingInputSchema,
1415
+ UpdateMeetingMetadata,
1416
+ UpdateMeetingOperation,
1417
+ UpdatedMeetingSchema,
1418
+ ZoomClient2 as ZoomClient,
1419
+ decodeCredentials,
1420
+ decodeMeetingChangedEventPayload,
1421
+ decodeSharedCredentials,
1422
+ defineMeetingChangedTriggerBinding,
1423
+ newConnection,
1424
+ newConnectionWithOperations,
1425
+ newCreateMeetingStep,
1426
+ newGetMeetingStep,
1427
+ newListMeetingsStep,
1428
+ newListPastMeetingParticipantsStep,
1429
+ newMeetingChangedTrigger,
1430
+ newMeetingTriggerRunner,
1431
+ newProjectConnection2 as newProjectConnection,
1432
+ newProjectMeetingTriggerRunner,
1433
+ newUpdateMeetingStep
1434
+ };