@superdurable/connector-atlassian-confluence 0.1.0 → 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 CHANGED
@@ -61,7 +61,7 @@ import {
61
61
  newConnectionWithOperations,
62
62
  newProjectConnection,
63
63
  newProjectCredentialProvider
64
- } from "./chunk-OAQFTUZS.js";
64
+ } from "./chunk-K4XYPHG4.js";
65
65
 
66
66
  // src/generated/steps.ts
67
67
  import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
@@ -181,7 +181,8 @@ var Authorization = {
181
181
  "invalid_grant",
182
182
  "invalid_client",
183
183
  "unauthorized_client"
184
- ]
184
+ ],
185
+ "tokenExchangeTimeout": "15s"
185
186
  },
186
187
  "scopes": [
187
188
  "search:confluence",
@@ -1118,6 +1119,128 @@ function daysInMonth(year, month) {
1118
1119
  return 31;
1119
1120
  }
1120
1121
 
1122
+ // src/go_url.ts
1123
+ var hexDigits = new Set(Buffer.from("0123456789abcdefABCDEF"));
1124
+ var userinfoBytes = new Set(Buffer.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._:~!$&'()*+,;=%@"));
1125
+ var hostBytes = new Set(Buffer.from(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:[]<>"`));
1126
+ var cursorPattern = /^[\x21-\x7e]{1,4096}$/;
1127
+ var GoURLError = class extends Error {
1128
+ };
1129
+ function readNextCursor(nextLink) {
1130
+ if (!nextLink) return "";
1131
+ const cursor = queryGet(parseRawQuery(Buffer.from(nextLink, "utf8")), "cursor").toString("latin1");
1132
+ if (!cursorPattern.test(cursor)) throw new TypeError("cursor is missing or invalid");
1133
+ return cursor;
1134
+ }
1135
+ function unescape(value, options = {}) {
1136
+ const decoded = [];
1137
+ for (let index = 0; index < value.length; ) {
1138
+ const byte = value[index];
1139
+ if (byte === 37) {
1140
+ if (index + 2 >= value.length || !hexDigits.has(value[index + 1]) || !hexDigits.has(value[index + 2])) throw new GoURLError("invalid URL escape");
1141
+ const high = Number.parseInt(String.fromCharCode(value[index + 1]), 16);
1142
+ if (options.isHost && high < 8 && value.subarray(index, index + 3).toString("latin1") !== "%25") throw new GoURLError("invalid URL escape in host");
1143
+ decoded.push(Number.parseInt(value.subarray(index + 1, index + 3).toString("latin1"), 16));
1144
+ index += 3;
1145
+ continue;
1146
+ }
1147
+ if (options.isHost && byte < 128 && !hostBytes.has(byte)) throw new GoURLError("invalid character in host name");
1148
+ decoded.push(options.isPlusSpace && byte === 43 ? 32 : byte);
1149
+ index++;
1150
+ }
1151
+ return Buffer.from(decoded);
1152
+ }
1153
+ function parseRawQuery(raw) {
1154
+ const hash = raw.indexOf(35);
1155
+ const link = hash < 0 ? raw : raw.subarray(0, hash);
1156
+ const fragment = hash < 0 ? Buffer.alloc(0) : raw.subarray(hash + 1);
1157
+ if (link.some((byte) => byte < 32 || byte === 127)) throw new GoURLError("invalid control character in URL");
1158
+ const [scheme, afterScheme] = splitScheme(link);
1159
+ let rest = afterScheme, query = Buffer.alloc(0);
1160
+ const questionMarks = rest.filter((byte) => byte === 63).length;
1161
+ if (rest.length > 0 && rest[rest.length - 1] === 63 && questionMarks === 1) rest = rest.subarray(0, -1);
1162
+ else if (questionMarks > 0) {
1163
+ const question = rest.indexOf(63);
1164
+ query = rest.subarray(question + 1);
1165
+ rest = rest.subarray(0, question);
1166
+ }
1167
+ if (rest[0] !== 47) {
1168
+ if (scheme.length > 0) {
1169
+ unescape(fragment);
1170
+ return query;
1171
+ }
1172
+ const slash = rest.indexOf(47);
1173
+ if ((slash < 0 ? rest : rest.subarray(0, slash)).includes(58)) throw new GoURLError("first path segment in URL cannot contain colon");
1174
+ }
1175
+ if (rest[0] === 47 && rest[1] === 47 && (scheme.length > 0 || rest[2] !== 47)) {
1176
+ const slash = rest.indexOf(47, 2);
1177
+ parseAuthority(slash < 0 ? rest.subarray(2) : rest.subarray(2, slash));
1178
+ rest = slash < 0 ? Buffer.alloc(0) : rest.subarray(slash);
1179
+ }
1180
+ unescape(rest);
1181
+ unescape(fragment);
1182
+ return query;
1183
+ }
1184
+ function splitScheme(link) {
1185
+ for (let index = 0; index < link.length; index++) {
1186
+ const byte = link[index];
1187
+ if (byte >= 97 && byte <= 122 || byte >= 65 && byte <= 90) continue;
1188
+ if (byte >= 48 && byte <= 57 || byte === 43 || byte === 45 || byte === 46) {
1189
+ if (index === 0) return [Buffer.alloc(0), link];
1190
+ continue;
1191
+ }
1192
+ if (byte === 58) {
1193
+ if (index === 0) throw new GoURLError("missing protocol scheme");
1194
+ return [link.subarray(0, index), link.subarray(index + 1)];
1195
+ }
1196
+ return [Buffer.alloc(0), link];
1197
+ }
1198
+ return [Buffer.alloc(0), link];
1199
+ }
1200
+ function parseAuthority(authority) {
1201
+ const at = authority.lastIndexOf(64);
1202
+ const host = at < 0 ? authority : authority.subarray(at + 1);
1203
+ if (at >= 0) {
1204
+ const userinfo = authority.subarray(0, at);
1205
+ if (userinfo.some((byte) => !userinfoBytes.has(byte))) throw new GoURLError("invalid userinfo");
1206
+ const colon2 = userinfo.indexOf(58);
1207
+ unescape(colon2 < 0 ? userinfo : userinfo.subarray(0, colon2));
1208
+ if (colon2 >= 0) unescape(userinfo.subarray(colon2 + 1));
1209
+ }
1210
+ if (host[0] === 91) {
1211
+ const close = host.lastIndexOf(93);
1212
+ if (close < 0) throw new GoURLError("missing ']' in host");
1213
+ checkPort(host.subarray(close + 1));
1214
+ unescape(host.subarray(0, close + 1), { isHost: true });
1215
+ return;
1216
+ }
1217
+ const colon = host.lastIndexOf(58);
1218
+ if (colon >= 0) checkPort(host.subarray(colon));
1219
+ unescape(host, { isHost: true });
1220
+ }
1221
+ function checkPort(port) {
1222
+ if (port.length === 0) return;
1223
+ if (port[0] !== 58 || port.subarray(1).some((byte) => byte < 48 || byte > 57)) throw new GoURLError("invalid port");
1224
+ }
1225
+ function queryGet(query, key) {
1226
+ let start = 0;
1227
+ while (start <= query.length) {
1228
+ const ampersand = query.indexOf(38, start);
1229
+ const pair = query.subarray(start, ampersand < 0 ? query.length : ampersand);
1230
+ start = ampersand < 0 ? query.length + 1 : ampersand + 1;
1231
+ if (pair.length === 0 || pair.includes(59)) continue;
1232
+ const equals = pair.indexOf(61);
1233
+ try {
1234
+ const name = unescape(equals < 0 ? pair : pair.subarray(0, equals), { isPlusSpace: true });
1235
+ const value = unescape(equals < 0 ? Buffer.alloc(0) : pair.subarray(equals + 1), { isPlusSpace: true });
1236
+ if (name.toString("latin1") === key) return value;
1237
+ } catch (error) {
1238
+ if (!(error instanceof GoURLError)) throw error;
1239
+ }
1240
+ }
1241
+ return Buffer.alloc(0);
1242
+ }
1243
+
1121
1244
  // src/operations.ts
1122
1245
  var emptyTime = "0001-01-01T00:00:00Z";
1123
1246
  var idPattern = /^[1-9][0-9]{0,18}$/;
@@ -1164,9 +1287,7 @@ var SearchPagesOperation = class {
1164
1287
  const nextLink = stringField(links, "next");
1165
1288
  if (nextLink) {
1166
1289
  try {
1167
- const nextCursor = new URL(nextLink, "https://confluence.invalid").searchParams.get("cursor") || "";
1168
- if (!isCursor(nextCursor)) throw new TypeError();
1169
- output.nextCursor = nextCursor;
1290
+ output.nextCursor = readNextCursor(nextLink);
1170
1291
  } catch {
1171
1292
  return newQueryBranch("invalidResponse", output, receipt, confluenceFailure(operation, "PROTOCOL", "Confluence returned an invalid search cursor"));
1172
1293
  }
@@ -1807,6 +1928,8 @@ var defaultEndpoint = "https://api.atlassian.com";
1807
1928
  var cloudIdPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1808
1929
  var confluenceScopes = /confluence/;
1809
1930
  var encoder = new TextEncoder();
1931
+ var defaultPollIntervalMs = 6e4;
1932
+ var minimumPollIntervalMs = 1e4;
1810
1933
  var ConfluenceClient = class {
1811
1934
  /** Validate connection settings and bind the host credential source. */
1812
1935
  constructor(config, credentials, options = {}) {
@@ -1817,6 +1940,9 @@ var ConfluenceClient = class {
1817
1940
  if (this.configuredCloudId && !cloudIdPattern.test(this.configuredCloudId)) throw new TypeError("Confluence cloudId must be a site UUID");
1818
1941
  this.maxResponseBytes = config.maxResponseBytes || 8388608;
1819
1942
  if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes < 1) throw new TypeError("Confluence maxResponseBytes must be positive");
1943
+ this.pollIntervalMs = config.pollIntervalMs || defaultPollIntervalMs;
1944
+ if (!Number.isFinite(this.pollIntervalMs) || this.pollIntervalMs < minimumPollIntervalMs) throw new TypeError("Confluence pollInterval must be at least 10s");
1945
+ this.triggerLogger = options.triggerLogger;
1820
1946
  this.send = options.send ?? sendProviderRequest;
1821
1947
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
1822
1948
  }
@@ -1824,6 +1950,10 @@ var ConfluenceClient = class {
1824
1950
  endpoint;
1825
1951
  configuredCloudId;
1826
1952
  maxResponseBytes;
1953
+ /** Delay between pageChanged polls, in milliseconds. */
1954
+ pollIntervalMs;
1955
+ /** Receives pageChanged Trigger records; undefined uses the SDK default logger. */
1956
+ triggerLogger;
1827
1957
  now;
1828
1958
  send;
1829
1959
  refreshDriver = new ManifestCredentialRefreshDriver({ providerName: "Atlassian", auth: Authorization, credentialFields: CredentialFields });
@@ -1848,6 +1978,10 @@ var ConfluenceClient = class {
1848
1978
  addComment() {
1849
1979
  return new AddCommentOperation(this);
1850
1980
  }
1981
+ /** Report that the next session sends the accessible-resources request. */
1982
+ needsSiteLookup() {
1983
+ return !this.configuredCloudId && !this.resolvedCloudId;
1984
+ }
1851
1985
  /** Resolve the OAuth token and the single selected Confluence Cloud site. */
1852
1986
  async startSession(call, operation) {
1853
1987
  let credentials;
@@ -2015,15 +2149,647 @@ function newProjectConnection2(project, connectionName, options = {}) {
2015
2149
  return newProjectConnection(project, connectionName, (loadedProject, name) => {
2016
2150
  const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "confluence" && entry.connectionName === name);
2017
2151
  if (!selected) throw new TypeError("Confluence project connection is not configured");
2018
- const settings = ConfigSchema.parse(selected.configuration);
2152
+ const { pollInterval, ...raw } = selected.configuration;
2153
+ const settings = ConfigSchema.parse({ ...raw, ...pollInterval !== void 0 ? { pollIntervalMs: pollIntervalMilliseconds(pollInterval) } : {} });
2019
2154
  const config = {
2020
2155
  ...settings.cloudId !== void 0 ? { cloudId: settings.cloudId } : {},
2021
2156
  ...settings.endpoint !== void 0 ? { endpoint: settings.endpoint } : {},
2022
- ...settings.maxResponseBytes !== void 0 ? { maxResponseBytes: settings.maxResponseBytes } : {}
2157
+ ...settings.maxResponseBytes !== void 0 ? { maxResponseBytes: settings.maxResponseBytes } : {},
2158
+ ...settings.pollIntervalMs !== void 0 ? { pollIntervalMs: settings.pollIntervalMs } : {}
2023
2159
  };
2024
2160
  return new ConfluenceClient(config, newProjectCredentialProvider(loadedProject, name, decodeCredentials, encodeCredentials, decodeSharedCredentials), options);
2025
2161
  });
2026
2162
  }
2163
+ function pollIntervalMilliseconds(value) {
2164
+ if (typeof value === "number" && Number.isSafeInteger(value)) return Math.floor(value / 1e6);
2165
+ if (typeof value !== "string") throw new TypeError("Confluence pollInterval must be a Go duration");
2166
+ const units = { ns: 1e-6, us: 1e-3, "\xB5s": 1e-3, "\u03BCs": 1e-3, ms: 1, s: 1e3, m: 6e4, h: 36e5 };
2167
+ let rest = value, total = 0;
2168
+ if (!rest) throw new TypeError("Confluence pollInterval must be a Go duration");
2169
+ while (rest) {
2170
+ const match = /^(\d+(?:\.\d*)?|\.\d+)(ns|us|µs|μs|ms|s|m|h)/.exec(rest);
2171
+ if (!match) throw new TypeError("Confluence pollInterval must be a Go duration");
2172
+ total += Number(match[1]) * units[match[2]];
2173
+ rest = rest.slice(match[0].length);
2174
+ }
2175
+ return Math.floor(total);
2176
+ }
2177
+
2178
+ // src/page_changed.ts
2179
+ import { mustTriggerBindingDefinition } from "@superdurable/connectors-sdk";
2180
+ import { z } from "zod";
2181
+ var PageChangeCreated = "created";
2182
+ var PageChangeUpdated = "updated";
2183
+ var UIUnitSpacePicker = "spacePicker";
2184
+ var UISpacePickerPortSpaceID = "spaceId";
2185
+ var UISpacePickerPortSpaceKey = "spaceKey";
2186
+ var UISpacePickerPortSpaceName = "spaceName";
2187
+ var spaceKeyPattern2 = /^~?[A-Za-z0-9_-]{1,255}$/;
2188
+ var PageChangedTriggerConfigurationSchema = z.strictObject({
2189
+ /** The picked space's numeric ID, kept for display only. */
2190
+ spaceId: z.string().optional(),
2191
+ /** Limits the Trigger to pages in this space, such as OPS; blank watches every space the connection can view. */
2192
+ spaceKey: z.string().optional(),
2193
+ /** The picked space's display name, kept for display only. */
2194
+ spaceName: z.string().optional()
2195
+ }).superRefine((configuration, context) => {
2196
+ if (configuration.spaceKey && !spaceKeyPattern2.test(configuration.spaceKey)) context.addIssue({ code: "custom", message: "pageChanged spaceKey must be a Confluence space key such as OPS, without surrounding whitespace" });
2197
+ });
2198
+ var PageChangedEventSchema = z.strictObject({
2199
+ /** The Confluence site the page belongs to. */
2200
+ cloudId: z.string(),
2201
+ /** The derived change kind. */
2202
+ changeKind: z.enum([PageChangeCreated, PageChangeUpdated]),
2203
+ /** The page and its delivered version; read its body with getPage. */
2204
+ page: PageSummarySchema
2205
+ });
2206
+ var PageChangedTriggerDefinition = {
2207
+ trigger: { connectorId: ConnectorID, triggerName: "pageChanged" },
2208
+ description: "Receive each page created or updated in one space, or in every space the connection can view, read through Confluence CQL search ordered by last modification; the first run records a baseline and delivers no existing pages."
2209
+ };
2210
+ function definePageChangedTriggerBinding(config) {
2211
+ return mustTriggerBindingDefinition({ definition: PageChangedTriggerDefinition, ...config });
2212
+ }
2213
+
2214
+ // src/page_change_cursor.ts
2215
+ import { createHash as createHash2 } from "crypto";
2216
+
2217
+ // src/go_time.ts
2218
+ var nanosecondsPerSecond = 1000000000n;
2219
+ var secondsPerDay = 86400n;
2220
+ var goZeroUnixNanoseconds = -62135596800n * nanosecondsPerSecond;
2221
+ var timestampPattern = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|([+-])(\d{2}):(\d{2}))$/;
2222
+ var GoInstant = class _GoInstant {
2223
+ /** Hold unixNanoseconds since the Unix epoch, written with offsetMinutes east of UTC. */
2224
+ constructor(unixNanoseconds, offsetMinutes) {
2225
+ this.unixNanoseconds = unixNanoseconds;
2226
+ this.offsetMinutes = offsetMinutes;
2227
+ }
2228
+ unixNanoseconds;
2229
+ offsetMinutes;
2230
+ /** Go's zero time, 0001-01-01T00:00:00Z. */
2231
+ static zero = new _GoInstant(goZeroUnixNanoseconds, 0);
2232
+ /** Return the UTC instant of a Date, at its millisecond precision. */
2233
+ static fromDate(date) {
2234
+ return new _GoInstant(BigInt(date.getTime()) * 1000000n, 0);
2235
+ }
2236
+ /** Report Go's IsZero: the instant is 0001-01-01T00:00:00Z in any offset. */
2237
+ isZero() {
2238
+ return this.unixNanoseconds === goZeroUnixNanoseconds;
2239
+ }
2240
+ /** Report Go's Before, which compares instants and ignores offsets. */
2241
+ isBefore(other) {
2242
+ return this.unixNanoseconds < other.unixNanoseconds;
2243
+ }
2244
+ /** The same instant written in UTC, as Go's UTC method returns it. */
2245
+ utc() {
2246
+ return new _GoInstant(this.unixNanoseconds, 0);
2247
+ }
2248
+ /** The instant nanoseconds later, keeping the offset, as Go's Add does. */
2249
+ addNanoseconds(nanoseconds) {
2250
+ return new _GoInstant(this.unixNanoseconds + nanoseconds, this.offsetMinutes);
2251
+ }
2252
+ /** The instant as a Date, truncated to milliseconds. */
2253
+ toDate() {
2254
+ return new Date(Number(floorDivide(this.unixNanoseconds, 1000000n)));
2255
+ }
2256
+ /** Format as Go's time.Time MarshalJSON does: RFC 3339 with trailing fraction zeros trimmed. */
2257
+ format() {
2258
+ const local = this.unixNanoseconds + BigInt(this.offsetMinutes) * 60n * nanosecondsPerSecond;
2259
+ const seconds = floorDivide(local, nanosecondsPerSecond), nanoseconds = local - seconds * nanosecondsPerSecond;
2260
+ const days = floorDivide(seconds, secondsPerDay), secondOfDay = Number(seconds - days * secondsPerDay);
2261
+ const [year, month, day] = civilFromDays(days);
2262
+ let text = `${pad(year, 4)}-${pad(month, 2)}-${pad(day, 2)}T${pad(Math.floor(secondOfDay / 3600), 2)}:${pad(Math.floor(secondOfDay / 60) % 60, 2)}:${pad(secondOfDay % 60, 2)}`;
2263
+ const fraction = nanoseconds.toString().padStart(9, "0").replace(/0+$/, "");
2264
+ if (fraction) text += "." + fraction;
2265
+ if (this.offsetMinutes === 0) return text + "Z";
2266
+ const offset = Math.abs(this.offsetMinutes);
2267
+ return `${text}${this.offsetMinutes > 0 ? "+" : "-"}${pad(Math.floor(offset / 60), 2)}:${pad(offset % 60, 2)}`;
2268
+ }
2269
+ /** Format the UTC instant as a CQL date, yyyy-MM-dd HH:mm, as Go's "2006-01-02 15:04" layout does. */
2270
+ formatCQLMinute() {
2271
+ return this.utc().format().slice(0, 16).replace("T", " ");
2272
+ }
2273
+ };
2274
+ function parseGoTime(text) {
2275
+ const match = timestampPattern.exec(text);
2276
+ if (!match) return void 0;
2277
+ const [year, month, day, hour, minute, second] = match.slice(1, 7).map(Number);
2278
+ const monthDays = [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
2279
+ if (month < 1 || month > 12 || day < 1 || day > monthDays[month - 1] || hour > 23 || minute > 59 || second > 59) return void 0;
2280
+ let offsetMinutes = 0;
2281
+ if (match[8] !== "Z") {
2282
+ const zoneHour = Number(match[10]), zoneMinute = Number(match[11]);
2283
+ if (zoneHour > 23 || zoneMinute > 59) return void 0;
2284
+ offsetMinutes = (zoneHour * 60 + zoneMinute) * (match[9] === "+" ? 1 : -1);
2285
+ }
2286
+ const seconds = daysFromCivil(year, month, day) * secondsPerDay + BigInt(hour * 3600 + minute * 60 + second);
2287
+ const nanoseconds = BigInt((match[7] ?? "").padEnd(9, "0"));
2288
+ return new GoInstant((seconds - BigInt(offsetMinutes * 60)) * nanosecondsPerSecond + nanoseconds, offsetMinutes);
2289
+ }
2290
+ function parseGoTimeLayout(text) {
2291
+ return parseGoTime(text.length > 11 && text[10] === "T" && text[12] === ":" ? text.slice(0, 11) + "0" + text.slice(11) : text);
2292
+ }
2293
+ function floorDivide(value, divisor) {
2294
+ const quotient = value / divisor;
2295
+ return value % divisor !== 0n && value < 0n !== divisor < 0n ? quotient - 1n : quotient;
2296
+ }
2297
+ function pad(value, width) {
2298
+ return String(value).padStart(width, "0");
2299
+ }
2300
+ function isLeapYear(year) {
2301
+ return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
2302
+ }
2303
+ function daysFromCivil(year, month, day) {
2304
+ const shiftedYear = month <= 2 ? year - 1 : year;
2305
+ const era = Math.floor(shiftedYear / 400), yearOfEra = shiftedYear - era * 400;
2306
+ const dayOfYear = Math.floor((153 * (month + (month > 2 ? -3 : 9)) + 2) / 5) + day - 1;
2307
+ const dayOfEra = yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear;
2308
+ return BigInt(era * 146097 + dayOfEra - 719468);
2309
+ }
2310
+ function civilFromDays(dayCount) {
2311
+ const days = Number(dayCount) + 719468;
2312
+ const era = Math.floor(days / 146097), dayOfEra = days - era * 146097;
2313
+ const yearOfEra = Math.floor((dayOfEra - Math.floor(dayOfEra / 1460) + Math.floor(dayOfEra / 36524) - Math.floor(dayOfEra / 146096)) / 365);
2314
+ const dayOfYear = dayOfEra - (365 * yearOfEra + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100));
2315
+ const monthIndex = Math.floor((5 * dayOfYear + 2) / 153);
2316
+ const day = dayOfYear - Math.floor((153 * monthIndex + 2) / 5) + 1;
2317
+ const month = monthIndex + (monthIndex < 10 ? 3 : -9);
2318
+ return [yearOfEra + era * 400 + (month <= 2 ? 1 : 0), month, day];
2319
+ }
2320
+
2321
+ // src/page_change_cursor.ts
2322
+ var int64Minimum = -(2n ** 63n);
2323
+ var int64Maximum = 2n ** 63n - 1n;
2324
+ var UndecodableError = class extends Error {
2325
+ };
2326
+ function wellFormed(value) {
2327
+ return value.replace(/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g, "\uFFFD");
2328
+ }
2329
+ function goJSONString(value) {
2330
+ return JSON.stringify(wellFormed(value)).replace(/[<>&\u2028\u2029]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
2331
+ }
2332
+ function encodePageChangeCursor(position) {
2333
+ const fields = [`"cloudId":${goJSONString(position.cloudId)}`];
2334
+ if (position.spaceKey) fields.push(`"spaceKey":${goJSONString(position.spaceKey)}`);
2335
+ fields.push(`"scannedThrough":"${position.scannedThrough.format()}"`);
2336
+ if (position.scan) {
2337
+ const scan = [`"startedAt":"${position.scan.startedAt.format()}"`, `"cql":${goJSONString(position.scan.cql)}`];
2338
+ if (position.scan.searchCursor) scan.push(`"searchCursor":${goJSONString(position.scan.searchCursor)}`);
2339
+ fields.push(`"scan":{${scan.join(",")}}`);
2340
+ }
2341
+ return `{${fields.join(",")}}`;
2342
+ }
2343
+ function decodePageChangeCursor(token) {
2344
+ try {
2345
+ const document = parseStrictJSON(token);
2346
+ const position = { cloudId: "", spaceKey: "", scannedThrough: GoInstant.zero, scan: void 0 };
2347
+ if (document === null) return position;
2348
+ const values = objectFields(document, ["cloudid", "spacekey", "scannedthrough", "scan"]);
2349
+ position.cloudId = stringField2(values.get("cloudid"));
2350
+ position.spaceKey = stringField2(values.get("spacekey"));
2351
+ position.scannedThrough = timeField(values.get("scannedthrough"));
2352
+ const scan = values.get("scan");
2353
+ if (scan !== void 0 && scan !== null) {
2354
+ const scanValues = objectFields(scan, ["startedat", "cql", "searchcursor"]);
2355
+ position.scan = { startedAt: timeField(scanValues.get("startedat")), cql: stringField2(scanValues.get("cql")), searchCursor: stringField2(scanValues.get("searchcursor")) };
2356
+ }
2357
+ return position;
2358
+ } catch {
2359
+ throw new TypeError("Confluence pageChanged cursor is not decodable");
2360
+ }
2361
+ }
2362
+ function encodeSeenPageVersion(seen) {
2363
+ return new TextEncoder().encode(`{"versionNumber":${seen.versionNumber},"lastModifiedAt":"${seen.lastModifiedAt.format()}"}`);
2364
+ }
2365
+ function decodeSeenPageVersion(value) {
2366
+ try {
2367
+ const document = parseStrictJSON(new TextDecoder("utf-8", { fatal: true }).decode(value ?? new Uint8Array()));
2368
+ if (document === null) return { versionNumber: 0, lastModifiedAt: GoInstant.zero };
2369
+ const values = objectFields(document, ["versionnumber", "lastmodifiedat"]);
2370
+ return { versionNumber: integerField(values.get("versionnumber")), lastModifiedAt: timeField(values.get("lastmodifiedat")) };
2371
+ } catch {
2372
+ throw new TypeError("Confluence seen page version is not decodable");
2373
+ }
2374
+ }
2375
+ function seenPageHash(pageId, versionNumber) {
2376
+ return createHash2("sha256").update(`${wellFormed(pageId)}\0${versionNumber}`, "utf8").digest().subarray(0, 8).toString("hex");
2377
+ }
2378
+ function pageChangeEventId(cloudId, pageId, versionNumber) {
2379
+ const joined = [wellFormed(cloudId), wellFormed(pageId), String(versionNumber)].join("\0");
2380
+ return "confluence-page-" + createHash2("sha256").update(joined, "utf8").digest().subarray(0, 16).toString("hex");
2381
+ }
2382
+ var IntegerLiteral = class {
2383
+ constructor(text) {
2384
+ this.text = text;
2385
+ }
2386
+ text;
2387
+ };
2388
+ var FractionLiteral = class {
2389
+ };
2390
+ function parseStrictJSON(text) {
2391
+ return JSON.parse(text, (_key, value, context) => {
2392
+ if (typeof value !== "number") return value;
2393
+ const source = context?.source ?? String(value);
2394
+ return /^-?\d+$/.test(source) ? new IntegerLiteral(source) : new FractionLiteral();
2395
+ });
2396
+ }
2397
+ function objectFields(document, names) {
2398
+ if (!document || typeof document !== "object" || Array.isArray(document) || document instanceof IntegerLiteral || document instanceof FractionLiteral) throw new UndecodableError();
2399
+ const values = /* @__PURE__ */ new Map();
2400
+ for (const [key, value] of Object.entries(document)) {
2401
+ const folded = [...key].every((character) => character.charCodeAt(0) < 128) ? key.toLowerCase() : key;
2402
+ if (names.includes(folded)) values.set(folded, value);
2403
+ }
2404
+ return values;
2405
+ }
2406
+ function stringField2(value) {
2407
+ if (value === void 0 || value === null) return "";
2408
+ if (typeof value !== "string") throw new UndecodableError();
2409
+ return value;
2410
+ }
2411
+ function integerField(value) {
2412
+ if (value === void 0 || value === null) return 0;
2413
+ if (!(value instanceof IntegerLiteral)) throw new UndecodableError();
2414
+ const integer = BigInt(value.text);
2415
+ if (integer < int64Minimum || integer > int64Maximum) throw new UndecodableError();
2416
+ return Number(integer);
2417
+ }
2418
+ function timeField(value) {
2419
+ if (value === void 0 || value === null) return GoInstant.zero;
2420
+ if (typeof value !== "string") throw new UndecodableError();
2421
+ const parsed = parseGoTime(value);
2422
+ if (!parsed) throw new UndecodableError();
2423
+ return parsed;
2424
+ }
2425
+
2426
+ // src/trigger.ts
2427
+ import { newTrigger } from "@superdurable/connectors-sdk";
2428
+ import { newBindingPoller, newBindingTriggerSource, newMemoryCursorStore, newRunner } from "@superdurable/connectors-sdk/pollingtrigger";
2429
+ import { ObjectNotFoundError, decodeTriggerConfiguration, newDurableTriggerTarget, parseTriggerPayloadJSON } from "@superdurable/connectors-sdk/projectconfig";
2430
+
2431
+ // src/page_change_fetcher.ts
2432
+ import { DefaultKeyedSnapshotEntries, applyKeyedSnapshotChanges, markCursorInvalid, newTriggerCredentialCall } from "@superdurable/connectors-sdk/pollingtrigger";
2433
+
2434
+ // src/page_change_search.ts
2435
+ import { MaxChangesPerPage, markRateLimited, waitForPollRequest } from "@superdurable/connectors-sdk/pollingtrigger";
2436
+ var pageChangedTriggerId = "pageChanged";
2437
+ var pageChangeSearchPageSize = 100;
2438
+ var contentIdPattern = /^[1-9][0-9]{0,18}$/;
2439
+ var jsonNumberPattern = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/;
2440
+ var goZeroTime = "0001-01-01T00:00:00Z";
2441
+ var SearchCursorRejectedError = class extends Error {
2442
+ };
2443
+ var NumberLiteral = class {
2444
+ constructor(text) {
2445
+ this.text = text;
2446
+ }
2447
+ text;
2448
+ };
2449
+ async function startTriggerSession(client, context, call) {
2450
+ if (client.needsSiteLookup()) await waitForPollRequest(context);
2451
+ const started = await client.startSession(call, pageChangedTriggerId);
2452
+ if ("session" in started) return started.session;
2453
+ const { failure, retryAfterMs } = started.error;
2454
+ if (failure.kind === "RATE_LIMIT") throw markRateLimited(new Error(failure.message), retryAfterMs);
2455
+ throw new Error(failure.kind === "AUTHENTICATION" ? "Confluence Trigger credentials are unavailable; reconnect the connection" : failure.message);
2456
+ }
2457
+ async function searchPageChanges(client, context, session, cql, searchCursor) {
2458
+ await waitForPollRequest(context);
2459
+ const query = { cql, limit: String(pageChangeSearchPageSize), expand: "space,version" };
2460
+ if (searchCursor) query.cursor = searchCursor;
2461
+ const response = await client.exchange(session, "GET", "search", "/content/search", query);
2462
+ if (response.error) throw new Error("Confluence page search is temporarily unavailable");
2463
+ const retryAfterMs = client.retryAfter(response);
2464
+ if (response.status === 429) throw markRateLimited(new Error("Confluence rate limited the page search (HTTP 429)"), retryAfterMs);
2465
+ if (response.status === 503 && retryAfterMs > 0) throw markRateLimited(new Error("Confluence page search is unavailable (HTTP 503)"), retryAfterMs);
2466
+ if (response.status === 400 && searchCursor) throw new SearchCursorRejectedError("Confluence rejected the stored search cursor");
2467
+ if (response.status < 200 || response.status >= 300) throw new Error(`Confluence rejected the page search with HTTP ${response.status}`);
2468
+ if (response.isTooLarge) throw new Error("Confluence page search response exceeds maxResponseBytes");
2469
+ if (response.reflectsSecret) throw new Error("Confluence page search response contains credential material");
2470
+ return decodePageChangeSearch(response.body);
2471
+ }
2472
+ function decodePageChangeSearch(body) {
2473
+ let decoded, base, nextLink;
2474
+ try {
2475
+ const document = JSON.parse(new TextDecoder().decode(body), (_key, value, context) => typeof value === "number" ? new NumberLiteral(context?.source ?? String(value)) : value);
2476
+ const page = optionalObject(document);
2477
+ const resources = page.results;
2478
+ if (resources !== void 0 && resources !== null && !Array.isArray(resources)) throw new TypeError("results is not a list");
2479
+ const links = optionalObject(page._links);
2480
+ base = stringValue(links.base);
2481
+ nextLink = stringValue(links.next);
2482
+ decoded = (resources ?? []).map(decodeResource);
2483
+ } catch {
2484
+ throw new Error("Confluence returned an invalid search page");
2485
+ }
2486
+ if (decoded.length > MaxChangesPerPage) throw new Error(`Confluence search page has ${decoded.length} results, more than ${MaxChangesPerPage}`);
2487
+ let searchCursor;
2488
+ try {
2489
+ searchCursor = readNextCursor(nextLink);
2490
+ } catch {
2491
+ throw new Error("Confluence returned an invalid search cursor");
2492
+ }
2493
+ const result = { pages: [], searchCursor };
2494
+ for (const resource of decoded) {
2495
+ if (resource.type !== "page") continue;
2496
+ if (!contentIdPattern.test(resource.id) || !resource.title) throw new Error("Confluence returned an invalid page in the search results: page ID or title is missing");
2497
+ const changed = changedPage(resource, base);
2498
+ if ((changed.summary.versionNumber ?? 0) < 1 || changed.lastModifiedAt.isZero()) throw new Error(`Confluence search result for page ${changed.summary.id} has no version number or time`);
2499
+ result.pages.push(changed);
2500
+ }
2501
+ return result;
2502
+ }
2503
+ function decodeResource(resource) {
2504
+ const value = optionalObject(resource);
2505
+ const decoded = {
2506
+ id: stringValue(value.id),
2507
+ type: stringValue(value.type),
2508
+ status: stringValue(value.status),
2509
+ title: stringValue(value.title),
2510
+ webui: stringValue(optionalObject(value._links).webui)
2511
+ };
2512
+ if (value.space !== void 0 && value.space !== null) {
2513
+ const space = optionalObject(value.space);
2514
+ decoded.space = [jsonNumberText(space.id), stringValue(space.key)];
2515
+ }
2516
+ if (value.version !== void 0 && value.version !== null) {
2517
+ const version = optionalObject(value.version);
2518
+ decoded.version = [integerValue(version.number), stringValue(version.when)];
2519
+ }
2520
+ return decoded;
2521
+ }
2522
+ function changedPage(resource, base) {
2523
+ const [spaceIdText, spaceKeyText] = resource.space ?? ["", ""];
2524
+ const [versionNumber, when] = resource.version ?? [0, ""];
2525
+ const lastModifiedAt = resource.version ? parseGoTimeLayout(when) ?? GoInstant.zero : GoInstant.zero;
2526
+ const spaceId = contentIdPattern.test(spaceIdText) ? spaceIdText : "";
2527
+ const spaceKey = spaceKeyPattern2.test(spaceKeyText) ? spaceKeyText : "";
2528
+ const webUrl = webURL(base, resource.webui);
2529
+ const summary = {
2530
+ id: resource.id,
2531
+ title: resource.title,
2532
+ ...resource.status ? { status: resource.status } : {},
2533
+ ...spaceId ? { spaceId } : {},
2534
+ ...spaceKey ? { spaceKey } : {},
2535
+ ...versionNumber ? { versionNumber } : {},
2536
+ lastModifiedAt: lastModifiedAt.isZero() ? goZeroTime : lastModifiedAt.format(),
2537
+ ...webUrl ? { webUrl } : {}
2538
+ };
2539
+ return { summary, lastModifiedAt };
2540
+ }
2541
+ function optionalObject(value) {
2542
+ if (value === void 0 || value === null) return {};
2543
+ if (typeof value !== "object" || Array.isArray(value) || value instanceof NumberLiteral) throw new TypeError("value is not an object");
2544
+ return value;
2545
+ }
2546
+ function stringValue(value) {
2547
+ if (value === void 0 || value === null) return "";
2548
+ if (typeof value !== "string") throw new TypeError("value is not a string");
2549
+ return value;
2550
+ }
2551
+ function integerValue(value) {
2552
+ if (value === void 0 || value === null) return 0;
2553
+ if (!(value instanceof NumberLiteral) || !/^-?\d+$/.test(value.text)) throw new TypeError("version number is not an integer");
2554
+ const integer = BigInt(value.text);
2555
+ if (integer < -(2n ** 63n) || integer >= 2n ** 63n) throw new TypeError("version number is out of range");
2556
+ return Number(integer);
2557
+ }
2558
+ function jsonNumberText(value) {
2559
+ if (value === void 0 || value === null) return "";
2560
+ if (value instanceof NumberLiteral) return value.text;
2561
+ if (typeof value === "string" && jsonNumberPattern.test(value)) return value;
2562
+ throw new TypeError("space ID is not a number");
2563
+ }
2564
+
2565
+ // src/page_change_fetcher.ts
2566
+ var pageChangeLookbackNanoseconds = 10n * 60n * 1000000000n;
2567
+ var maximumSeedSearchPages = 100;
2568
+ var pageChangeSnapshotOptions = { maxEntries: DefaultKeyedSnapshotEntries, keepValues: true, evictLeastRecentlySeen: true };
2569
+ var timeZoneMarginNanoseconds = 12n * 3600n * 1000000000n;
2570
+ var SeenPageItem = class {
2571
+ constructor(pageId, seen) {
2572
+ this.pageId = pageId;
2573
+ this.seen = seen;
2574
+ }
2575
+ pageId;
2576
+ seen;
2577
+ snapshotKey() {
2578
+ return this.pageId;
2579
+ }
2580
+ snapshotHash() {
2581
+ return seenPageHash(this.pageId, this.seen.versionNumber);
2582
+ }
2583
+ snapshotValue() {
2584
+ return encodeSeenPageVersion(this.seen);
2585
+ }
2586
+ };
2587
+ function buildPageChangeCQL(spaceKey, windowStart) {
2588
+ let clauses = "type = page";
2589
+ if (spaceKey) clauses += ` AND space = "${spaceKey.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
2590
+ const lowerBound = windowStart.utc().addNanoseconds(-timeZoneMarginNanoseconds).formatCQLMinute();
2591
+ return `${clauses} AND lastmodified >= "${lowerBound}" ORDER BY lastmodified DESC`;
2592
+ }
2593
+ function newPageChangedTriggerEvent(cloudId, page) {
2594
+ const versionNumber = page.summary.versionNumber ?? 0;
2595
+ return {
2596
+ id: pageChangeEventId(cloudId, page.summary.id, versionNumber),
2597
+ occurredAt: page.lastModifiedAt.toDate(),
2598
+ payload: { cloudId, changeKind: versionNumber === 1 ? PageChangeCreated : PageChangeUpdated, page: page.summary }
2599
+ };
2600
+ }
2601
+ var PageChangeFetcher = class {
2602
+ /** Bind the client, connection, and watched space; validate the configuration beforehand. */
2603
+ constructor(client, connection, configuration) {
2604
+ this.client = client;
2605
+ this.connection = connection;
2606
+ this.spaceKey = configuration.spaceKey ?? "";
2607
+ }
2608
+ client;
2609
+ connection;
2610
+ spaceKey;
2611
+ /** Record every page modified in the lookback window as seen, so the first scan delivers no existing page. */
2612
+ async seedCursor(context) {
2613
+ const session = await startTriggerSession(this.client, context, this.credentialCall(context));
2614
+ const startedAt = GoInstant.fromDate(this.client.now());
2615
+ const windowStart = startedAt.addNanoseconds(-pageChangeLookbackNanoseconds);
2616
+ const cql = buildPageChangeCQL(this.spaceKey, windowStart);
2617
+ const seen = [];
2618
+ let searchCursor = "";
2619
+ for (let page = 0; page < maximumSeedSearchPages; page++) {
2620
+ const result = await searchPageChanges(this.client, context, session, cql, searchCursor);
2621
+ for (const changed of result.pages) if (!changed.lastModifiedAt.isBefore(windowStart)) seen.push(seenItem(changed));
2622
+ if (!result.searchCursor || hasPageModifiedBefore(result, windowStart)) {
2623
+ const snapshot = applyKeyedSnapshotChanges(void 0, seen, [], pageChangeSnapshotOptions);
2624
+ return encodeCursor({ cloudId: session.cloudId, spaceKey: this.spaceKey, scannedThrough: startedAt, scan: void 0 }, snapshot);
2625
+ }
2626
+ searchCursor = result.searchCursor;
2627
+ }
2628
+ throw new Error(`Confluence pageChanged baseline exceeded ${maximumSeedSearchPages} search pages`);
2629
+ }
2630
+ /** Read one search page of the current scan; a cursor for another site or space, or an undecodable one, reseeds. */
2631
+ async fetchChanges(context, cursor) {
2632
+ let position;
2633
+ try {
2634
+ position = decodePageChangeCursor(cursor.token);
2635
+ } catch {
2636
+ position = { cloudId: "", spaceKey: "", scannedThrough: GoInstant.zero, scan: void 0 };
2637
+ }
2638
+ if (!position.cloudId || position.scannedThrough.isZero()) throw markCursorInvalid(new Error("Confluence pageChanged cursor is not decodable"));
2639
+ if (position.spaceKey !== this.spaceKey) throw markCursorInvalid(new Error("Confluence pageChanged cursor belongs to another space"));
2640
+ const session = await startTriggerSession(this.client, context, this.credentialCall(context));
2641
+ if (position.cloudId !== session.cloudId) throw markCursorInvalid(new Error("Confluence pageChanged cursor belongs to another site"));
2642
+ const windowStart = position.scannedThrough.addNanoseconds(-pageChangeLookbackNanoseconds);
2643
+ position.scan ??= { startedAt: GoInstant.fromDate(this.client.now()), cql: buildPageChangeCQL(this.spaceKey, windowStart), searchCursor: "" };
2644
+ let result;
2645
+ try {
2646
+ result = await searchPageChanges(this.client, context, session, position.scan.cql, position.scan.searchCursor);
2647
+ } catch (error) {
2648
+ if (!(error instanceof SearchCursorRejectedError)) throw error;
2649
+ position.scan.searchCursor = "";
2650
+ return { changes: [], next: encodeCursor(position, cursor.snapshot), hasMorePages: true };
2651
+ }
2652
+ return collectPageChanges(session.cloudId, position, cursor.snapshot, result, windowStart);
2653
+ }
2654
+ credentialCall(context) {
2655
+ return newTriggerCredentialCall(this.connection, PageChangedTriggerDefinition.trigger, context.signal);
2656
+ }
2657
+ };
2658
+ function collectPageChanges(cloudId, position, snapshot, result, windowStart) {
2659
+ const stored = new Map((snapshot?.entries ?? []).map((entry) => [entry.key, entry]));
2660
+ const changes = [];
2661
+ const upserted = [];
2662
+ for (const page of result.pages) {
2663
+ if (page.lastModifiedAt.isBefore(windowStart) || isSeenPageVersion(stored.get(page.summary.id), page)) continue;
2664
+ changes.push(newPageChangedTriggerEvent(cloudId, page));
2665
+ upserted.push(seenItem(page));
2666
+ }
2667
+ changes.reverse();
2668
+ const scan = position.scan;
2669
+ let removedKeys = [], hasMorePages = false;
2670
+ if (!result.searchCursor || hasPageModifiedBefore(result, windowStart)) {
2671
+ position.scannedThrough = scan.startedAt;
2672
+ position.scan = void 0;
2673
+ removedKeys = expiredSeenPageKeys(snapshot, position.scannedThrough.addNanoseconds(-pageChangeLookbackNanoseconds));
2674
+ } else {
2675
+ scan.searchCursor = result.searchCursor;
2676
+ hasMorePages = true;
2677
+ }
2678
+ const next = applyKeyedSnapshotChanges(snapshot, upserted, removedKeys, pageChangeSnapshotOptions);
2679
+ return { changes, next: encodeCursor(position, next), hasMorePages };
2680
+ }
2681
+ function encodeCursor(position, snapshot) {
2682
+ return { token: encodePageChangeCursor(position), snapshot: snapshot ?? { entries: [] } };
2683
+ }
2684
+ function seenItem(page) {
2685
+ return new SeenPageItem(page.summary.id, { versionNumber: page.summary.versionNumber ?? 0, lastModifiedAt: page.lastModifiedAt.utc() });
2686
+ }
2687
+ function hasPageModifiedBefore(result, windowStart) {
2688
+ return result.pages.some((page) => page.lastModifiedAt.isBefore(windowStart));
2689
+ }
2690
+ function isSeenPageVersion(entry, page) {
2691
+ if (!entry) return false;
2692
+ try {
2693
+ return decodeSeenPageVersion(entry.value).versionNumber >= (page.summary.versionNumber ?? 0);
2694
+ } catch {
2695
+ return false;
2696
+ }
2697
+ }
2698
+ function expiredSeenPageKeys(snapshot, nextWindowStart) {
2699
+ return (snapshot?.entries ?? []).filter((entry) => {
2700
+ try {
2701
+ return decodeSeenPageVersion(entry.value).lastModifiedAt.isBefore(nextWindowStart);
2702
+ } catch {
2703
+ return true;
2704
+ }
2705
+ }).map((entry) => entry.key);
2706
+ }
2707
+
2708
+ // src/trigger.ts
2709
+ function newPageTriggerRunner(config) {
2710
+ const client = confluenceClientOf(config.connection);
2711
+ if (!config.pageChangedRoutes?.length) throw new TypeError("Confluence pageChanged routes are required");
2712
+ const pollers = config.pageChangedRoutes.map((route) => {
2713
+ if (!route.bindingName?.trim() || !route.target) throw new TypeError("Confluence pageChanged binding name and target are required");
2714
+ const configuration = parseConfiguration(route.configuration);
2715
+ return newBindingPoller({
2716
+ definition: PageChangedTriggerDefinition,
2717
+ binding: { connection: config.connection.reference, trigger: PageChangedTriggerDefinition.trigger, name: route.bindingName },
2718
+ cursor: route.cursor ?? newMemoryCursorStore(),
2719
+ fetcher: new PageChangeFetcher(client, config.connection.reference, configuration),
2720
+ target: route.target,
2721
+ snapshot: pageChangeSnapshotOptions
2722
+ });
2723
+ });
2724
+ return newRunner({ connection: config.connection.reference, schedule: pollSchedule(client), pollers, logger: client.triggerLogger });
2725
+ }
2726
+ function newPageChangedTrigger(config) {
2727
+ const client = confluenceClientOf(config.connection);
2728
+ const configuration = parseConfiguration(config.configuration);
2729
+ const binding = { connection: config.connection.reference, trigger: PageChangedTriggerDefinition.trigger, name: config.bindingName };
2730
+ const source = newBindingTriggerSource({
2731
+ definition: PageChangedTriggerDefinition,
2732
+ binding,
2733
+ cursor: newMemoryCursorStore(),
2734
+ fetcher: new PageChangeFetcher(client, config.connection.reference, configuration),
2735
+ snapshot: pageChangeSnapshotOptions
2736
+ }, pollSchedule(client), client.triggerLogger);
2737
+ return newTrigger({ definition: PageChangedTriggerDefinition, binding, source, target: config.target, ...client.triggerLogger ? { logger: client.triggerLogger } : {} });
2738
+ }
2739
+ var PageTriggerRunner = class {
2740
+ /** @internal Use newProjectPageTriggerRunner. */
2741
+ constructor(runner) {
2742
+ this.runner = runner;
2743
+ }
2744
+ runner;
2745
+ /** Replay each binding's inbox, then poll until context.signal aborts; rejects with TriggerDeliveryAbortedError then. */
2746
+ run(context) {
2747
+ return this.runner.run(context);
2748
+ }
2749
+ /** Make the named binding poll now, without shortening a rate-limit pause. */
2750
+ wakePoller(bindingName) {
2751
+ this.runner.wakePoller(bindingName);
2752
+ }
2753
+ };
2754
+ function newProjectPageTriggerRunner(project, connectionName, routes, options = {}) {
2755
+ if (!routes?.length) throw new TypeError("Confluence pageChanged routes are required");
2756
+ const connection = newProjectConnection2(project, connectionName, options);
2757
+ const logger = confluenceClientOf(connection).triggerLogger;
2758
+ const triggerName = PageChangedTriggerDefinition.trigger.triggerName;
2759
+ const bindingNames = /* @__PURE__ */ new Set();
2760
+ const durableRoutes = routes.map((route) => {
2761
+ const bindingName = route.bindingName?.trim() ?? "";
2762
+ if (!bindingName || !route.target) throw new TypeError("Confluence pageChanged binding name and target are required");
2763
+ if (bindingNames.has(bindingName)) throw new TypeError(`Confluence pageChanged binding name "${bindingName}" is duplicated`);
2764
+ bindingNames.add(bindingName);
2765
+ const key = { connectorId: ConnectorID, connectionName, triggerName, bindingName };
2766
+ let configuration = {};
2767
+ try {
2768
+ configuration = decodeTriggerConfiguration(project.configuration, key, PageChangedTriggerConfigurationSchema);
2769
+ } catch (error) {
2770
+ if (!(error instanceof ObjectNotFoundError)) throw new Error(`confluence pageChanged binding "${bindingName}" configuration: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
2771
+ }
2772
+ const target = newDurableTriggerTarget(project.triggerInbox(key), key, route.target, { ...logger ? { logger } : {}, decodePayload: decodePageChangedEventPayload });
2773
+ return { bindingName, configuration, target, cursor: project.pollCursorStore(key) };
2774
+ });
2775
+ return new PageTriggerRunner(newPageTriggerRunner({ connection, pageChangedRoutes: durableRoutes }));
2776
+ }
2777
+ function decodePageChangedEventPayload(_payloadJSON, payloadBytes) {
2778
+ return PageChangedEventSchema.parse(parseTriggerPayloadJSON(payloadBytes));
2779
+ }
2780
+ function parseConfiguration(configuration) {
2781
+ const parsed = PageChangedTriggerConfigurationSchema.safeParse(configuration ?? {});
2782
+ if (!parsed.success) throw new TypeError(`confluence pageChanged configuration: ${parsed.error.issues.map((issue) => issue.message).join("; ")}`);
2783
+ return parsed.data;
2784
+ }
2785
+ function confluenceClientOf(connection) {
2786
+ const client = connection?.operations;
2787
+ if (!(client instanceof ConfluenceClient)) throw new TypeError("Confluence Triggers require a connection from newProjectConnection or newConnection with a ConfluenceClient");
2788
+ return client;
2789
+ }
2790
+ function pollSchedule(client) {
2791
+ return { intervalMs: client.pollIntervalMs };
2792
+ }
2027
2793
  export {
2028
2794
  AddCommentBranch,
2029
2795
  AddCommentBranchAdded,
@@ -2061,9 +2827,15 @@ export {
2061
2827
  GetPageInputSchema,
2062
2828
  GetPageMetadata,
2063
2829
  GetPageOperation,
2830
+ PageChangeCreated,
2831
+ PageChangeUpdated,
2832
+ PageChangedEventSchema,
2833
+ PageChangedTriggerConfigurationSchema,
2834
+ PageChangedTriggerDefinition,
2064
2835
  PageSchema,
2065
2836
  PageSearchFilterSchema,
2066
2837
  PageSummarySchema,
2838
+ PageTriggerRunner,
2067
2839
  PageVersionSchema,
2068
2840
  ProviderID,
2069
2841
  SearchPagesBranch,
@@ -2076,6 +2848,10 @@ export {
2076
2848
  SearchPagesMetadata,
2077
2849
  SearchPagesOperation,
2078
2850
  SearchPagesOutputSchema,
2851
+ UISpacePickerPortSpaceID,
2852
+ UISpacePickerPortSpaceKey,
2853
+ UISpacePickerPortSpaceName,
2854
+ UIUnitSpacePicker,
2079
2855
  UpdatePageBranch,
2080
2856
  UpdatePageBranchDefect,
2081
2857
  UpdatePageBranchNotFound,
@@ -2088,13 +2864,19 @@ export {
2088
2864
  UpdatePageOperation,
2089
2865
  UpdatePageOutputSchema,
2090
2866
  decodeCredentials,
2867
+ decodePageChangedEventPayload,
2091
2868
  decodeSharedCredentials,
2869
+ definePageChangedTriggerBinding,
2092
2870
  newAddCommentStep,
2093
2871
  newConnection,
2094
2872
  newConnectionWithOperations,
2095
2873
  newCreatePageStep,
2096
2874
  newGetPageStep,
2875
+ newPageChangedTrigger,
2876
+ newPageTriggerRunner,
2097
2877
  newProjectConnection2 as newProjectConnection,
2878
+ newProjectPageTriggerRunner,
2098
2879
  newSearchPagesStep,
2099
- newUpdatePageStep
2880
+ newUpdatePageStep,
2881
+ pageChangeEventId
2100
2882
  };