@superdurable/connector-atlassian-confluence 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,2882 @@
1
+ import {
2
+ AddCommentBranch,
3
+ AddCommentBranchAdded,
4
+ AddCommentBranchDefect,
5
+ AddCommentBranchNotFound,
6
+ AddCommentBranchProviderRejected,
7
+ AddCommentBranchUncertain,
8
+ AddCommentDefinition,
9
+ AddCommentInputSchema,
10
+ AddCommentMetadata,
11
+ AddCommentOutputSchema,
12
+ ConfigSchema,
13
+ Connection,
14
+ ConnectorID,
15
+ CreatePageBranch,
16
+ CreatePageBranchCreated,
17
+ CreatePageBranchDefect,
18
+ CreatePageBranchNotFound,
19
+ CreatePageBranchProviderRejected,
20
+ CreatePageBranchTitleConflict,
21
+ CreatePageDefinition,
22
+ CreatePageInputSchema,
23
+ CreatePageMetadata,
24
+ CreatePageOutputSchema,
25
+ GetPageBranch,
26
+ GetPageBranchDefect,
27
+ GetPageBranchFound,
28
+ GetPageBranchInvalidResponse,
29
+ GetPageBranchNotFound,
30
+ GetPageBranchProviderRejected,
31
+ GetPageDefinition,
32
+ GetPageInputSchema,
33
+ GetPageMetadata,
34
+ PageSchema,
35
+ PageSearchFilterSchema,
36
+ PageSummarySchema,
37
+ PageVersionSchema,
38
+ ProviderID,
39
+ SearchPagesBranch,
40
+ SearchPagesBranchDefect,
41
+ SearchPagesBranchInvalidResponse,
42
+ SearchPagesBranchProviderRejected,
43
+ SearchPagesBranchSearched,
44
+ SearchPagesDefinition,
45
+ SearchPagesInputSchema,
46
+ SearchPagesMetadata,
47
+ SearchPagesOutputSchema,
48
+ UpdatePageBranch,
49
+ UpdatePageBranchDefect,
50
+ UpdatePageBranchNotFound,
51
+ UpdatePageBranchProviderRejected,
52
+ UpdatePageBranchUpdated,
53
+ UpdatePageBranchVersionConflict,
54
+ UpdatePageDefinition,
55
+ UpdatePageInputSchema,
56
+ UpdatePageMetadata,
57
+ UpdatePageOutputSchema,
58
+ decodeCredentials,
59
+ decodeSharedCredentials,
60
+ newConnection,
61
+ newConnectionWithOperations,
62
+ newProjectConnection,
63
+ newProjectCredentialProvider
64
+ } from "./chunk-K4XYPHG4.js";
65
+
66
+ // src/generated/steps.ts
67
+ import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
68
+ function newSearchPagesStep(configuration) {
69
+ const { connection, connectionName, searched, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
70
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
71
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.searchPages(), connection: connection.reference, branches: [
72
+ goToBranch("searched", searched),
73
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
74
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
75
+ ...defect ? [goToBranch("defect", defect)] : []
76
+ ] });
77
+ }
78
+ function newGetPageStep(configuration) {
79
+ const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
80
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
81
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.getPage(), connection: connection.reference, branches: [
82
+ goToBranch("found", found),
83
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
84
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
85
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
86
+ ...defect ? [goToBranch("defect", defect)] : []
87
+ ] });
88
+ }
89
+ function newCreatePageStep(configuration) {
90
+ const { connection, connectionName, created, titleConflict, notFound, providerRejected, defect, ...stepConfiguration } = configuration;
91
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
92
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.createPage(), connection: connection.reference, branches: [
93
+ goToBranch("created", created),
94
+ ...titleConflict ? [goToBranch("titleConflict", titleConflict)] : [],
95
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
96
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
97
+ ...defect ? [goToBranch("defect", defect)] : []
98
+ ] });
99
+ }
100
+ function newUpdatePageStep(configuration) {
101
+ const { connection, connectionName, updated, versionConflict, notFound, providerRejected, defect, ...stepConfiguration } = configuration;
102
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
103
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.updatePage(), connection: connection.reference, branches: [
104
+ goToBranch("updated", updated),
105
+ ...versionConflict ? [goToBranch("versionConflict", versionConflict)] : [],
106
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
107
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
108
+ ...defect ? [goToBranch("defect", defect)] : []
109
+ ] });
110
+ }
111
+ function newAddCommentStep(configuration) {
112
+ const { connection, connectionName, added, notFound, providerRejected, uncertain, defect, ...stepConfiguration } = configuration;
113
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
114
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.addComment(), connection: connection.reference, branches: [
115
+ goToBranch("added", added),
116
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
117
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
118
+ ...uncertain ? [goToBranch("uncertain", uncertain)] : [],
119
+ ...defect ? [goToBranch("defect", defect)] : []
120
+ ] });
121
+ }
122
+
123
+ // src/client.ts
124
+ import { BodyTooLargeError, ProviderTransportError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
125
+ import { resolveCredential, resolveCredentialAfterRejection } from "@superdurable/connectors-sdk";
126
+ import { ManifestCredentialRefreshDriver } from "@superdurable/connectors-sdk/oauthtoken";
127
+
128
+ // src/generated/refresh.ts
129
+ var Authorization = {
130
+ "fields": [
131
+ {
132
+ "name": "oauth_client_id",
133
+ "required": true,
134
+ "type": "string"
135
+ },
136
+ {
137
+ "name": "oauth_client_secret",
138
+ "required": true,
139
+ "type": "secretString"
140
+ },
141
+ {
142
+ "name": "access_token",
143
+ "required": true,
144
+ "type": "secretString"
145
+ },
146
+ {
147
+ "name": "refresh_token",
148
+ "required": true,
149
+ "type": "secretString"
150
+ }
151
+ ],
152
+ "oauth2": {
153
+ "clientIDCredential": "oauth_client_id",
154
+ "clientSecretCredential": "oauth_client_secret",
155
+ "credentialMappings": [
156
+ {
157
+ "credential": "access_token",
158
+ "source": "access_token"
159
+ },
160
+ {
161
+ "credential": "refresh_token",
162
+ "source": "refresh_token"
163
+ }
164
+ ],
165
+ "refresh": {
166
+ "acceptedScopeSets": [
167
+ [
168
+ "search:confluence",
169
+ "read:page:confluence",
170
+ "write:page:confluence",
171
+ "read:space:confluence",
172
+ "read:comment:confluence",
173
+ "write:comment:confluence"
174
+ ]
175
+ ],
176
+ "acceptsMissingTokenType": true,
177
+ "missingExpiry": "reject",
178
+ "scopeSeparators": "whitespaceAndComma",
179
+ "storedMissingExpiry": "refresh",
180
+ "terminalErrorCodes": [
181
+ "invalid_grant",
182
+ "invalid_client",
183
+ "unauthorized_client"
184
+ ],
185
+ "tokenExchangeTimeout": "15s"
186
+ },
187
+ "scopes": [
188
+ "search:confluence",
189
+ "read:page:confluence",
190
+ "write:page:confluence",
191
+ "read:space:confluence",
192
+ "read:comment:confluence",
193
+ "write:comment:confluence",
194
+ "offline_access"
195
+ ],
196
+ "tokenEndpoint": "https://auth.atlassian.com/oauth/token",
197
+ "tokenRequestEncoding": "json"
198
+ },
199
+ "refreshable": true,
200
+ "type": "oauth2"
201
+ };
202
+ var CredentialFields = {
203
+ "access_token": "accessToken",
204
+ "oauth_client_id": "oauthClientId",
205
+ "oauth_client_secret": "oauthClientSecret",
206
+ "refresh_token": "refreshToken"
207
+ };
208
+
209
+ // src/operations.ts
210
+ import { newMutationBranch, newMutationRetry, newMutationUncertain, newQueryBranch, newQueryRetry, zeroReceipt } from "@superdurable/connectors-sdk";
211
+ import { createHash } from "crypto";
212
+
213
+ // src/document.ts
214
+ function renderDocumentText(blocks, format, maxCharacters) {
215
+ const text = renderBlocks(blocks, format === "markdown").trim();
216
+ const characters = [...text];
217
+ return maxCharacters > 0 && characters.length > maxCharacters ? { text: characters.slice(0, maxCharacters).join(""), isTruncated: true } : { text, isTruncated: false };
218
+ }
219
+ function documentComparisonText(blocks) {
220
+ return renderBlocks(blocks, false).split(/\s+/u).join("");
221
+ }
222
+ function renderBlocks(blocks, isMarkdown) {
223
+ return blocks.map((block) => renderBlock(block, isMarkdown)).filter((value) => value.trim()).join("\n\n");
224
+ }
225
+ function renderBlock(block, isMarkdown) {
226
+ switch (block.kind) {
227
+ case "paragraph": {
228
+ const text = renderInlines(block.inlines || [], isMarkdown);
229
+ return isMarkdown ? text.split("\n").map(escapeMarkdownLineStart).join("\n") : text;
230
+ }
231
+ case "heading": {
232
+ const text = renderInlines(block.inlines || [], isMarkdown).replace(/\n/g, " ");
233
+ return isMarkdown ? "#".repeat(Math.min(6, Math.max(1, block.headingLevel || 1))) + " " + text : text;
234
+ }
235
+ case "bulletList":
236
+ case "orderedList":
237
+ case "taskList":
238
+ return (block.listItems || []).map((item, index) => {
239
+ const marker = block.kind === "orderedList" ? `${Math.max(1, block.orderedStart || 1) + index}. ` : block.kind === "taskList" ? item.isTaskDone ? "- [x] " : "- [ ] " : "- ";
240
+ return marker + renderBlocks(item.blocks, isMarkdown).split("\n").map((line, lineIndex) => lineIndex && line ? " ".repeat(marker.length) + line : line).join("\n");
241
+ }).join("\n");
242
+ case "quote": {
243
+ const text = renderBlocks(block.children || [], isMarkdown);
244
+ return isMarkdown ? text.split("\n").map((line) => line ? "> " + line : ">").join("\n") : text;
245
+ }
246
+ case "code": {
247
+ if (!isMarkdown) return block.codeText || "";
248
+ let fence = "```";
249
+ while ((block.codeText || "").includes(fence)) fence += "`";
250
+ return `${fence}${block.codeLanguage || ""}
251
+ ${block.codeText || ""}
252
+ ${fence}`;
253
+ }
254
+ case "rule":
255
+ return "---";
256
+ case "table":
257
+ return (block.tableRows || []).flatMap((row, index) => {
258
+ const cells = row.cells.map((cell) => renderInlines(cell, isMarkdown).replace(/\n/g, " ").replace(isMarkdown ? /\|/g : /$^/, "\\|"));
259
+ if (!isMarkdown) return [cells.join(" | ")];
260
+ const line = `| ${cells.join(" | ")} |`;
261
+ return index === 0 ? [line, `| ${cells.map(() => "---").join(" | ")} |`] : [line];
262
+ }).join("\n");
263
+ }
264
+ }
265
+ function renderInlines(inlines, isMarkdown) {
266
+ return inlines.map((inline) => {
267
+ if (inline.isLineBreak) return "\n";
268
+ const original = inline.text || "";
269
+ if (!isMarkdown || !original.trim()) return original;
270
+ const leading = original.match(/^\s*/u)?.[0] || "";
271
+ const trailing = original.match(/\s*$/u)?.[0] || "";
272
+ const core = original.trim();
273
+ let text = escapeMarkdownText(core);
274
+ if (inline.isCode) {
275
+ let fence = "`";
276
+ while (core.includes(fence)) fence += "`";
277
+ text = fence + core + fence;
278
+ }
279
+ if (inline.isStrikethrough) text = `~~${text}~~`;
280
+ if (inline.isEmphasis) text = `*${text}*`;
281
+ if (inline.isStrong) text = `**${text}**`;
282
+ if (inline.linkHref) text = `[${text}](${inline.linkHref.replace(/\(/g, "%28").replace(/\)/g, "%29").replace(/ /g, "%20")})`;
283
+ return leading + text + trailing;
284
+ }).join("");
285
+ }
286
+ function escapeMarkdownText(value) {
287
+ const characters = [...value];
288
+ return characters.map((character, index) => {
289
+ if ("\\`*[]~".includes(character)) return "\\" + character;
290
+ if (character === "_" && !(isWord(characters[index - 1]) && isWord(characters[index + 1]))) return "\\_";
291
+ return character;
292
+ }).join("");
293
+ }
294
+ function isWord(value) {
295
+ return !!value && /[\p{L}\p{N}]/u.test(value);
296
+ }
297
+ function escapeMarkdownLineStart(line) {
298
+ const match = line.match(/^( *)(.*)$/);
299
+ if (!match) return line;
300
+ const indentation = match[1] || "", trimmed = match[2] || "";
301
+ if (/^[#>\-+=|]/.test(trimmed)) return indentation + "\\" + trimmed;
302
+ return indentation + trimmed.replace(/^([0-9]+)([.)])/, "$1\\$2");
303
+ }
304
+ function appendInline(inlines, span) {
305
+ if (span.isLineBreak) return [...inlines, span];
306
+ if (!span.text) return inlines;
307
+ const previous = inlines.at(-1);
308
+ if (previous && !previous.isLineBreak && !!previous.isStrong === !!span.isStrong && !!previous.isEmphasis === !!span.isEmphasis && !!previous.isCode === !!span.isCode && !!previous.isStrikethrough === !!span.isStrikethrough && (previous.linkHref || "") === (span.linkHref || "")) {
309
+ previous.text = (previous.text || "") + span.text;
310
+ return inlines;
311
+ }
312
+ return [...inlines, span];
313
+ }
314
+ function trimInlineEdges(inlines) {
315
+ const trimmed = [...inlines];
316
+ while (trimmed.length && (trimmed[0].isLineBreak || !(trimmed[0].text || "").trim())) trimmed.shift();
317
+ while (trimmed.length && (trimmed.at(-1).isLineBreak || !(trimmed.at(-1).text || "").trim())) trimmed.pop();
318
+ if (!trimmed.length) return [];
319
+ trimmed[0] = { ...trimmed[0], text: (trimmed[0].text || "").trimStart() };
320
+ trimmed[trimmed.length - 1] = { ...trimmed.at(-1), text: (trimmed.at(-1).text || "").trimEnd() };
321
+ return trimmed;
322
+ }
323
+ function appendParagraphBlock(blocks, inlines) {
324
+ const trimmed = trimInlineEdges(inlines);
325
+ return trimmed.some((inline) => !inline.isLineBreak && (inline.text || "").trim()) ? [...blocks, { kind: "paragraph", inlines: trimmed }] : blocks;
326
+ }
327
+ function flattenBlocksToInlines(blocks) {
328
+ let inlines = [];
329
+ for (const block of blocks) {
330
+ if (inlines.length) inlines = appendInline(inlines, { isLineBreak: true });
331
+ if (block.kind === "paragraph" || block.kind === "heading") for (const inline of block.inlines || []) inlines = appendInline(inlines, inline);
332
+ else inlines = appendInline(inlines, { text: renderBlock(block, false) });
333
+ }
334
+ return inlines;
335
+ }
336
+ function safeLinkHref(value) {
337
+ const href = value.trim();
338
+ if (href.length > 2048 || /[\s<>"]/u.test(href)) return "";
339
+ return /^(https?:\/\/|mailto:)/i.test(href) ? href : "";
340
+ }
341
+ function markdownFenceLanguage(value) {
342
+ const language = value.trim().toLowerCase();
343
+ return language.length <= 32 && /^[a-z0-9+#._-]*$/.test(language) ? language : "";
344
+ }
345
+ function renderStorageDocument(blocks) {
346
+ return blocks.map(renderStorageBlock).join("");
347
+ }
348
+ function renderStorageBlock(block) {
349
+ switch (block.kind) {
350
+ case "paragraph":
351
+ return `<p>${renderStorageInlines(block.inlines || [])}</p>`;
352
+ case "heading": {
353
+ const tag = "h" + Math.min(6, Math.max(1, block.headingLevel || 1));
354
+ return `<${tag}>${renderStorageInlines(block.inlines || [])}</${tag}>`;
355
+ }
356
+ case "bulletList":
357
+ case "orderedList": {
358
+ const tag = block.kind === "orderedList" ? "ol" : "ul";
359
+ const start = tag === "ol" && (block.orderedStart || 0) > 1 ? ` start="${block.orderedStart}"` : "";
360
+ return `<${tag}${start}>${(block.listItems || []).map((item) => `<li>${renderStorageListItem(item.blocks)}</li>`).join("")}</${tag}>`;
361
+ }
362
+ case "taskList":
363
+ return `<ac:task-list>${(block.listItems || []).map((item) => `<ac:task><ac:task-status>${item.isTaskDone ? "complete" : "incomplete"}</ac:task-status><ac:task-body>${renderStorageListItem(item.blocks)}</ac:task-body></ac:task>`).join("")}</ac:task-list>`;
364
+ case "quote":
365
+ return `<blockquote>${renderStorageDocument(block.children || [])}</blockquote>`;
366
+ case "code":
367
+ return `<pre>${escapeStorageText(block.codeText || "")}</pre>`;
368
+ case "rule":
369
+ return "<hr />";
370
+ case "table":
371
+ return `<table><tbody>${(block.tableRows || []).map((row) => `<tr>${row.cells.map((cell) => `<${row.isHeader ? "th" : "td"}>${renderStorageInlines(cell)}</${row.isHeader ? "th" : "td"}>`).join("")}</tr>`).join("")}</tbody></table>`;
372
+ }
373
+ }
374
+ function renderStorageListItem(blocks) {
375
+ return blocks.length && blocks[0].kind === "paragraph" ? renderStorageInlines(blocks[0].inlines || []) + renderStorageDocument(blocks.slice(1)) : renderStorageDocument(blocks);
376
+ }
377
+ function renderStorageInlines(inlines) {
378
+ return inlines.map((inline) => {
379
+ if (inline.isLineBreak) return "<br />";
380
+ let opening = "", closing = "";
381
+ if (inline.linkHref) {
382
+ opening += `<a href="${escapeStorageAttribute(inline.linkHref)}">`;
383
+ closing = "</a>" + closing;
384
+ }
385
+ for (const [isSet, open, close] of [
386
+ [inline.isStrong, "<strong>", "</strong>"],
387
+ [inline.isEmphasis, "<em>", "</em>"],
388
+ [inline.isStrikethrough, '<span style="text-decoration: line-through;">', "</span>"],
389
+ [inline.isCode, "<code>", "</code>"]
390
+ ]) if (isSet) {
391
+ opening += open;
392
+ closing = close + closing;
393
+ }
394
+ return opening + escapeStorageText(inline.text || "") + closing;
395
+ }).join("");
396
+ }
397
+ function escapeStorageText(value) {
398
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
399
+ }
400
+ function escapeStorageAttribute(value) {
401
+ return escapeStorageText(value).replace(/"/g, "&quot;").replace(/'/g, "&#39;");
402
+ }
403
+
404
+ // src/markdown.ts
405
+ var headingPattern = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/;
406
+ var thematicBreakPattern = /^ {0,3}(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,})$/;
407
+ var fenceOpeningPattern = /^( {0,3})(`{3,}|~{3,})[ \t]*([^`]*?)[ \t]*$/;
408
+ var listMarkerPattern = /^( {0,3})([-*+]|[0-9]{1,9}[.)])([ \t]+|$)/;
409
+ var tableSeparatorPattern = /^ {0,3}\|?[ \t]*:?-+:?[ \t]*(\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/;
410
+ var taskMarkerPattern = /^\[([ xX])\][ \t]+/;
411
+ function convertWrittenBody(body, format, fieldName) {
412
+ if (!body.trim()) throw new TypeError(`${fieldName} is required`);
413
+ if ([...body].length > 262144) throw new TypeError(`${fieldName} cannot exceed 262144 characters`);
414
+ if ([...body].some((character) => {
415
+ const code = character.codePointAt(0);
416
+ return code === 127 || code < 32 && code !== 9 && code !== 10 && code !== 13;
417
+ })) throw new TypeError(`${fieldName} cannot contain control characters`);
418
+ const normalized = body.replace(/\r\n?/g, "\n");
419
+ const blocks = !format || format === "markdown" ? readMarkdownBlocks(normalized.replace(/^\n+|\n+$/g, "").split("\n"), 0) : format === "plainText" ? readPlainText(normalized) : void 0;
420
+ if (!blocks) throw new TypeError(`${fieldName}Format must be markdown or plainText`);
421
+ return { storage: renderStorageDocument(blocks), comparisonText: documentComparisonText(blocks) };
422
+ }
423
+ function readPlainText(text) {
424
+ return text.replace(/^\n+|\n+$/g, "").split(/\n[ \t]*\n+/).reduce((blocks, paragraph) => {
425
+ let inlines = [];
426
+ for (const [index, line] of paragraph.split("\n").entries()) {
427
+ if (index) inlines = appendInline(inlines, { isLineBreak: true });
428
+ inlines = appendInline(inlines, { text: line });
429
+ }
430
+ return appendParagraphBlock(blocks, inlines);
431
+ }, []);
432
+ }
433
+ function readMarkdownBlocks(lines, depth) {
434
+ const blocks = [];
435
+ for (let index = 0; index < lines.length; ) {
436
+ const line = lines[index];
437
+ if (depth > 64) {
438
+ blocks.push({ kind: "paragraph", inlines: [{ text: lines.slice(index).join(" ") }] });
439
+ break;
440
+ }
441
+ if (!line.trim()) {
442
+ index++;
443
+ continue;
444
+ }
445
+ const fence = line.match(fenceOpeningPattern);
446
+ if (fence) {
447
+ const marker = fence[2], indentation = fence[1].length;
448
+ const language = markdownFenceLanguage((fence[3] || "").trim().split(" ")[0] || "");
449
+ const code = [];
450
+ index++;
451
+ while (index < lines.length) {
452
+ const candidate = lines[index].trim();
453
+ if (candidate.startsWith(marker[0]) && [...candidate].every((character) => character === marker[0]) && candidate.length >= marker.length) {
454
+ index++;
455
+ break;
456
+ }
457
+ code.push(removeIndentation(lines[index], indentation));
458
+ index++;
459
+ }
460
+ blocks.push({ kind: "code", codeText: code.join("\n"), codeLanguage: language });
461
+ continue;
462
+ }
463
+ const heading = line.match(headingPattern);
464
+ if (heading) {
465
+ blocks.push({ kind: "heading", headingLevel: heading[1].length, inlines: readMarkdownInlines(heading[2] || "", {}, 0) });
466
+ index++;
467
+ continue;
468
+ }
469
+ if (thematicBreakPattern.test(line)) {
470
+ blocks.push({ kind: "rule" });
471
+ index++;
472
+ continue;
473
+ }
474
+ if (isBlockQuoteLine(line)) {
475
+ const quoted = [];
476
+ while (index < lines.length && isBlockQuoteLine(lines[index])) quoted.push(lines[index++].trimStart().replace(/^> ?/, ""));
477
+ blocks.push({ kind: "quote", children: readMarkdownBlocks(quoted, depth + 1) });
478
+ continue;
479
+ }
480
+ if (listMarkerPattern.test(line)) {
481
+ const [block, next] = readList(lines, index, depth);
482
+ blocks.push(block);
483
+ index = next;
484
+ continue;
485
+ }
486
+ if (index + 1 < lines.length && line.includes("|") && lines[index + 1].includes("|") && tableSeparatorPattern.test(lines[index + 1])) {
487
+ const rows = [{ isHeader: true, cells: readTableCells(line) }];
488
+ index += 2;
489
+ while (index < lines.length && lines[index].includes("|") && lines[index].trim()) rows.push({ isHeader: false, cells: readTableCells(lines[index++]) });
490
+ blocks.push({ kind: "table", tableRows: rows });
491
+ continue;
492
+ }
493
+ const paragraphLines = [];
494
+ while (index < lines.length && lines[index].trim() && (!paragraphLines.length || !startsMarkdownBlock(lines[index]))) paragraphLines.push(lines[index++].trim());
495
+ const paragraph = appendParagraphBlock([], readMarkdownInlines(paragraphLines.join("\n"), {}, 0));
496
+ blocks.push(...paragraph);
497
+ }
498
+ return blocks;
499
+ }
500
+ function readList(lines, start, depth) {
501
+ const first = lines[start].match(listMarkerPattern);
502
+ const isOrdered = /^[0-9]/.test(first[2]);
503
+ const block = { kind: isOrdered ? "orderedList" : "bulletList", orderedStart: isOrdered ? Number.parseInt(first[2], 10) : 0, listItems: [] };
504
+ let index = start;
505
+ const groups = [];
506
+ while (index < lines.length) {
507
+ const marker = lines[index].match(listMarkerPattern);
508
+ if (!marker || /^[0-9]/.test(marker[2]) !== isOrdered || !isOrdered && marker[2] !== first[2]) break;
509
+ let indentation = marker[0].length;
510
+ if (!marker[3].trim() && marker[3].length > 4) indentation = marker[1].length + marker[2].length + 1;
511
+ const itemLines = [lines[index].slice(marker[0].length)];
512
+ index++;
513
+ while (index < lines.length) {
514
+ const next = lines[index];
515
+ if (!next.trim()) {
516
+ if (index + 1 < lines.length && leadingSpaces(lines[index + 1]) >= indentation) {
517
+ itemLines.push("");
518
+ index++;
519
+ continue;
520
+ }
521
+ break;
522
+ }
523
+ if (leadingSpaces(next) < indentation) break;
524
+ itemLines.push(removeIndentation(next, indentation));
525
+ index++;
526
+ }
527
+ groups.push(itemLines);
528
+ while (index < lines.length && !lines[index].trim() && index + 1 < lines.length && listMarkerPattern.test(lines[index + 1])) index++;
529
+ }
530
+ const isTask = !isOrdered && groups.every((group) => taskMarkerPattern.test(group[0]));
531
+ block.listItems = groups.map((group) => {
532
+ let isTaskDone = false;
533
+ if (isTask) {
534
+ const match = group[0].match(taskMarkerPattern);
535
+ isTaskDone = match[1] !== " ";
536
+ group[0] = group[0].slice(match[0].length);
537
+ }
538
+ return { blocks: readMarkdownBlocks(group, depth + 1), isTaskDone };
539
+ });
540
+ if (isTask) block.kind = "taskList";
541
+ return [block, index];
542
+ }
543
+ function readTableCells(line) {
544
+ let value = line.trim().replace(/^\|/, "");
545
+ if (value.endsWith("|") && !value.endsWith("\\|")) value = value.slice(0, -1);
546
+ const cells = [];
547
+ let cell = "", escaped = false;
548
+ for (const character of value) {
549
+ if (escaped) {
550
+ cell += (character === "|" ? "" : "\\") + character;
551
+ escaped = false;
552
+ } else if (character === "\\") escaped = true;
553
+ else if (character === "|") {
554
+ cells.push(readMarkdownInlines(cell.trim(), {}, 0));
555
+ cell = "";
556
+ } else cell += character;
557
+ }
558
+ cells.push(readMarkdownInlines(cell.trim(), {}, 0));
559
+ return cells;
560
+ }
561
+ function readMarkdownInlines(value, style, depth) {
562
+ const characters = [...value];
563
+ let inlines = [], pending = "";
564
+ const flush = () => {
565
+ inlines = appendInline(inlines, { ...style, text: pending });
566
+ pending = "";
567
+ };
568
+ for (let index = 0; index < characters.length; ) {
569
+ const character = characters[index];
570
+ if (depth >= 32) {
571
+ pending += character;
572
+ index++;
573
+ continue;
574
+ }
575
+ if (character === "\\" && index + 1 < characters.length && isMarkdownPunctuation(characters[index + 1])) {
576
+ pending += characters[index + 1];
577
+ index += 2;
578
+ continue;
579
+ }
580
+ if (character === "\n") {
581
+ flush();
582
+ inlines = appendInline(inlines, { isLineBreak: true });
583
+ index++;
584
+ continue;
585
+ }
586
+ if (character === "`") {
587
+ const code = readCodeSpan(characters, index);
588
+ if (code) {
589
+ flush();
590
+ inlines = appendInline(inlines, { ...style, text: code.text, isCode: true });
591
+ index = code.end;
592
+ continue;
593
+ }
594
+ const length = delimiterRunLength(characters, index, character);
595
+ pending += character.repeat(length);
596
+ index += length;
597
+ continue;
598
+ }
599
+ if (character === "[") {
600
+ const link = readMarkdownLink(characters, index);
601
+ if (link) {
602
+ flush();
603
+ for (const span of readMarkdownInlines(link.label, { ...style, linkHref: safeLinkHref(link.href) }, depth + 1)) inlines = appendInline(inlines, span);
604
+ index = link.end;
605
+ continue;
606
+ }
607
+ }
608
+ if (character === "<") {
609
+ const end = characters.indexOf(">", index + 1);
610
+ if (end >= 0) {
611
+ const href = characters.slice(index + 1, end).join("");
612
+ if (href && safeLinkHref(href) === href) {
613
+ flush();
614
+ inlines = appendInline(inlines, { ...style, text: href, linkHref: href });
615
+ index = end + 1;
616
+ continue;
617
+ }
618
+ }
619
+ }
620
+ if ("*_~".includes(character)) {
621
+ const emphasis = readEmphasis(characters, index, style);
622
+ if (emphasis) {
623
+ flush();
624
+ for (const span of readMarkdownInlines(emphasis.inner, emphasis.style, depth + 1)) inlines = appendInline(inlines, span);
625
+ index = emphasis.end;
626
+ continue;
627
+ }
628
+ const length = delimiterRunLength(characters, index, character);
629
+ pending += character.repeat(length);
630
+ index += length;
631
+ continue;
632
+ }
633
+ pending += character;
634
+ index++;
635
+ }
636
+ flush();
637
+ return trimInlineEdges(inlines);
638
+ }
639
+ function readCodeSpan(characters, start) {
640
+ const length = delimiterRunLength(characters, start, "`");
641
+ for (let index = start + length; index < characters.length; ) {
642
+ if (characters[index] !== "`") {
643
+ index++;
644
+ continue;
645
+ }
646
+ const closing = delimiterRunLength(characters, index, "`");
647
+ if (closing === length) {
648
+ let text = characters.slice(start + length, index).join("");
649
+ if (text.length >= 2 && text.startsWith(" ") && text.endsWith(" ") && text.trim()) text = text.slice(1, -1);
650
+ return { text: text.replace(/\n/g, " "), end: index + closing };
651
+ }
652
+ index += closing;
653
+ }
654
+ return void 0;
655
+ }
656
+ function readMarkdownLink(characters, start) {
657
+ let depth = 0;
658
+ for (let index = start; index < characters.length; index++) {
659
+ if (characters[index] === "\\") {
660
+ index++;
661
+ continue;
662
+ }
663
+ if (characters[index] === "[") depth++;
664
+ if (characters[index] !== "]") continue;
665
+ depth--;
666
+ if (depth > 0) continue;
667
+ if (characters[index + 1] !== "(") return void 0;
668
+ const closing = balancedClosing(characters, index + 2);
669
+ if (closing < 0) return void 0;
670
+ const href = characters.slice(index + 2, closing).join("").trim().replace(/^</, "").replace(/>$/, "");
671
+ if (!href || /[ \t\n]/.test(href)) return void 0;
672
+ return { label: characters.slice(start + 1, index).join(""), href, end: closing + 1 };
673
+ }
674
+ return void 0;
675
+ }
676
+ function balancedClosing(characters, start) {
677
+ let depth = 0;
678
+ for (let index = start; index < characters.length; index++) {
679
+ const character = characters[index];
680
+ if (character === "\\") {
681
+ index++;
682
+ continue;
683
+ }
684
+ if (character === "(") depth++;
685
+ if (character === ")") {
686
+ if (!depth) return index;
687
+ depth--;
688
+ }
689
+ if (character === "\n") return -1;
690
+ }
691
+ return -1;
692
+ }
693
+ function readEmphasis(characters, start, style) {
694
+ const character = characters[start], runLength = delimiterRunLength(characters, start, character);
695
+ if (character === "~" && runLength < 2) return void 0;
696
+ const length = Math.min(runLength, 2), contentStart = start + length;
697
+ if (contentStart >= characters.length || /\s/u.test(characters[contentStart])) return void 0;
698
+ if (character === "_" && start > 0 && isWord2(characters[start - 1])) return void 0;
699
+ for (let index = contentStart + 1; index < characters.length; index++) {
700
+ if (characters[index] === "\\") {
701
+ index++;
702
+ continue;
703
+ }
704
+ if (characters[index] !== character) continue;
705
+ const closingRun = delimiterRunLength(characters, index, character);
706
+ if (closingRun < length || /\s/u.test(characters[index - 1])) {
707
+ index += closingRun - 1;
708
+ continue;
709
+ }
710
+ const closing = index + closingRun - length, end = closing + length;
711
+ if (character === "_" && end < characters.length && isWord2(characters[end])) {
712
+ index += closingRun - 1;
713
+ continue;
714
+ }
715
+ const nextStyle = { ...style, ...character === "~" ? { isStrikethrough: true } : length === 2 ? { isStrong: true } : { isEmphasis: true } };
716
+ return { inner: characters.slice(contentStart, closing).join(""), style: nextStyle, end };
717
+ }
718
+ return void 0;
719
+ }
720
+ function isWord2(character) {
721
+ return /[\p{L}\p{N}]/u.test(character);
722
+ }
723
+ function isMarkdownPunctuation(character) {
724
+ return /^[!-/:-@[-`{-~]$/.test(character) || "`$^+<=>|~".includes(character);
725
+ }
726
+ function delimiterRunLength(characters, start, character) {
727
+ let length = 0;
728
+ while (characters[start + length] === character) length++;
729
+ return length;
730
+ }
731
+ function isBlockQuoteLine(line) {
732
+ return line.trimStart().startsWith(">") && leadingSpaces(line) <= 3;
733
+ }
734
+ function startsMarkdownBlock(line) {
735
+ return fenceOpeningPattern.test(line) || headingPattern.test(line) || thematicBreakPattern.test(line) || isBlockQuoteLine(line) || listMarkerPattern.test(line);
736
+ }
737
+ function leadingSpaces(line) {
738
+ return line.match(/^ */)?.[0].length || 0;
739
+ }
740
+ function removeIndentation(line, amount) {
741
+ return line.slice(Math.min(leadingSpaces(line), amount));
742
+ }
743
+
744
+ // src/storage.ts
745
+ import { parseDocument } from "htmlparser2";
746
+ var blockElements = /* @__PURE__ */ new Set(["p", "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "ac:task-list", "blockquote", "pre", "hr", "table", "div", "section", "ac:layout", "ac:layout-section", "ac:layout-cell", "ac:rich-text-body", "ac:adf-extension"]);
747
+ function parseStorageDocument(storage) {
748
+ if (Buffer.byteLength(storage) > 16e6) throw new TypeError("body is not readable Confluence storage format");
749
+ if (storage.includes("<![CDATA[") && !/<!\[CDATA\[[\s\S]*?\]\]>/.test(storage)) throw new TypeError("body is not readable Confluence storage format");
750
+ const html = storage.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, (_match, contents) => contents.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"));
751
+ const parsed = parseDocument(`<storage-root>${html}</storage-root>`, { decodeEntities: true, recognizeSelfClosing: true, lowerCaseTags: true });
752
+ const root = (parsed.children || []).find((node) => node.name === "storage-root");
753
+ if (!root) throw new TypeError("body is not readable Confluence storage format");
754
+ let count = 0;
755
+ const pending = [root];
756
+ while (pending.length) {
757
+ const node = pending.pop();
758
+ if (++count > 2e5) throw new TypeError("body is not readable Confluence storage format");
759
+ pending.push(...node.children || []);
760
+ }
761
+ return readBlocks(root.children || [], 0);
762
+ }
763
+ function readBlocks(nodes, depth) {
764
+ let blocks = [], inlines = [];
765
+ for (const node of nodes) {
766
+ if (isBlockElement(node)) {
767
+ blocks = appendParagraphBlock(blocks, inlines);
768
+ inlines = [];
769
+ blocks.push(...readBlock(node, depth + 1));
770
+ } else inlines = appendInlines(inlines, node, {}, depth + 1);
771
+ }
772
+ return appendParagraphBlock(blocks, inlines);
773
+ }
774
+ function readBlock(node, depth) {
775
+ if (depth > 64) return [];
776
+ const children = node.children || [];
777
+ switch (node.name) {
778
+ case "p":
779
+ return appendParagraphBlock([], readInlines(children, {}, depth));
780
+ case "h1":
781
+ case "h2":
782
+ case "h3":
783
+ case "h4":
784
+ case "h5":
785
+ case "h6":
786
+ return [{ kind: "heading", headingLevel: Number(node.name[1]), inlines: trimInlineEdges(readInlines(children, {}, depth)) }];
787
+ case "ul":
788
+ case "ol": {
789
+ const isOrdered = node.name === "ol";
790
+ return [{ kind: isOrdered ? "orderedList" : "bulletList", orderedStart: Number(node.attribs?.start || 0), listItems: children.filter((child) => child.name === "li").map((child) => ({ blocks: readBlocks(child.children || [], depth) })) }];
791
+ }
792
+ case "ac:task-list":
793
+ return [{ kind: "taskList", listItems: children.filter((child) => child.name === "ac:task").map((task) => ({
794
+ isTaskDone: (task.children || []).some((part) => part.name === "ac:task-status" && storageText(part).trim() === "complete"),
795
+ blocks: readBlocks((task.children || []).find((part) => part.name === "ac:task-body")?.children || [], depth)
796
+ })) }];
797
+ case "blockquote":
798
+ return [{ kind: "quote", children: readBlocks(children, depth) }];
799
+ case "pre":
800
+ return [{ kind: "code", codeText: storageText(node).replace(/^\n+|\n+$/g, "") }];
801
+ case "hr":
802
+ return [{ kind: "rule" }];
803
+ case "table":
804
+ return [{ kind: "table", tableRows: readTableRows(node, depth) }];
805
+ case "ac:structured-macro":
806
+ case "ac:macro":
807
+ return readMacro(node, depth);
808
+ case "ac:adf-extension":
809
+ return readBlocks(children.find((child) => child.name === "ac:adf-fallback")?.children || [], depth);
810
+ default:
811
+ return readBlocks(children, depth);
812
+ }
813
+ }
814
+ function readTableRows(node, depth) {
815
+ const rows = (node.children || []).flatMap((child) => child.name === "tr" ? [child] : ["thead", "tbody", "tfoot"].includes(child.name || "") ? (child.children || []).filter((row) => row.name === "tr") : []);
816
+ return rows.map((row) => {
817
+ const cells = (row.children || []).filter((child) => child.name === "th" || child.name === "td");
818
+ return { isHeader: !!cells.length && cells.every((cell) => cell.name === "th"), cells: cells.map((cell) => flattenBlocksToInlines(readBlocks(cell.children || [], depth))) };
819
+ });
820
+ }
821
+ function readMacro(node, depth) {
822
+ const name = node.attribs?.["ac:name"] || "";
823
+ const children = node.children || [];
824
+ const parameters = new Map(children.filter((child) => child.name === "ac:parameter").map((child) => [child.attribs?.["ac:name"] || "", storageText(child).trim()]));
825
+ const rich = children.find((child) => child.name === "ac:rich-text-body");
826
+ const plain = children.find((child) => child.name === "ac:plain-text-body");
827
+ if (name === "code" || name === "noformat") return [{ kind: "code", codeLanguage: markdownFenceLanguage(parameters.get("language") || ""), codeText: storageText(plain).replace(/^\n+|\n+$/g, "") }];
828
+ if (rich && ["info", "note", "warning", "tip", "panel"].includes(name)) return [{ kind: "quote", children: readBlocks(rich.children || [], depth) }];
829
+ if (rich) return readBlocks(rich.children || [], depth);
830
+ if (plain) return [{ kind: "paragraph", inlines: [{ text: storageText(plain).trim() }] }];
831
+ return [];
832
+ }
833
+ function readInlines(nodes, style, depth) {
834
+ let inlines = [];
835
+ for (const node of nodes) inlines = appendInlines(inlines, node, style, depth + 1);
836
+ return inlines;
837
+ }
838
+ function appendInlines(inlines, node, style, depth) {
839
+ if (depth > 64) return inlines;
840
+ if (node.type === "text") return appendInline(inlines, { ...style, text: collapseWhitespace(node.data || "") });
841
+ let nextStyle = style;
842
+ switch (node.name) {
843
+ case "br":
844
+ return appendInline(inlines, { isLineBreak: true });
845
+ case "strong":
846
+ case "b":
847
+ nextStyle = { ...style, isStrong: true };
848
+ break;
849
+ case "em":
850
+ case "i":
851
+ nextStyle = { ...style, isEmphasis: true };
852
+ break;
853
+ case "code":
854
+ case "tt":
855
+ nextStyle = { ...style, isCode: true };
856
+ break;
857
+ case "s":
858
+ case "del":
859
+ case "strike":
860
+ nextStyle = { ...style, isStrikethrough: true };
861
+ break;
862
+ case "span":
863
+ if ((node.attribs?.style || "").toLowerCase().includes("line-through")) nextStyle = { ...style, isStrikethrough: true };
864
+ break;
865
+ case "a":
866
+ nextStyle = { ...style, linkHref: safeLinkHref(node.attribs?.href || "") };
867
+ break;
868
+ case "ac:link":
869
+ return appendLinkInlines(inlines, node, style, depth);
870
+ case "ac:emoticon":
871
+ return appendInline(inlines, { ...style, text: node.attribs?.["ac:emoji-fallback"] || "" });
872
+ case "time":
873
+ return appendInline(inlines, { ...style, text: node.attribs?.datetime || "" });
874
+ case "ac:structured-macro":
875
+ return appendInlineMacro(inlines, node, style);
876
+ case "ac:image":
877
+ case "ac:placeholder":
878
+ case "ac:parameter":
879
+ case "ac:adf-attribute":
880
+ case "ri:user":
881
+ case "ri:attachment":
882
+ case "ri:page":
883
+ return inlines;
884
+ case "p":
885
+ case "div":
886
+ case "li":
887
+ case "h1":
888
+ case "h2":
889
+ case "h3":
890
+ case "h4":
891
+ case "h5":
892
+ case "h6":
893
+ case "tr":
894
+ case "blockquote":
895
+ case "pre":
896
+ if (inlines.length) inlines = appendInline(inlines, { isLineBreak: true });
897
+ break;
898
+ }
899
+ for (const child of node.children || []) inlines = appendInlines(inlines, child, nextStyle, depth + 1);
900
+ return inlines;
901
+ }
902
+ function appendLinkInlines(inlines, node, style, depth) {
903
+ let fallback = "", body, nextStyle = style;
904
+ for (const child of node.children || []) {
905
+ switch (child.name) {
906
+ case "ac:link-body":
907
+ body = child;
908
+ break;
909
+ case "ac:plain-text-link-body":
910
+ fallback = storageText(child).trim();
911
+ break;
912
+ case "ri:page":
913
+ if (!fallback) fallback = child.attribs?.["ri:content-title"] || "";
914
+ break;
915
+ case "ri:attachment":
916
+ if (!fallback) fallback = child.attribs?.["ri:filename"] || "";
917
+ break;
918
+ case "ri:url":
919
+ nextStyle = { ...style, linkHref: safeLinkHref(child.attribs?.["ri:value"] || "") };
920
+ if (!fallback) fallback = child.attribs?.["ri:value"] || "";
921
+ break;
922
+ }
923
+ }
924
+ if (body) for (const child of body.children || []) inlines = appendInlines(inlines, child, nextStyle, depth + 1);
925
+ else inlines = appendInline(inlines, { ...nextStyle, text: fallback });
926
+ return inlines;
927
+ }
928
+ function appendInlineMacro(inlines, node, style) {
929
+ if (node.attribs?.["ac:name"] !== "status") return inlines;
930
+ const title = (node.children || []).find((child) => child.name === "ac:parameter" && child.attribs?.["ac:name"] === "title");
931
+ return title ? appendInline(inlines, { ...style, text: storageText(title).trim() }) : inlines;
932
+ }
933
+ function isBlockElement(node) {
934
+ return blockElements.has(node.name || "") || ["ac:structured-macro", "ac:macro"].includes(node.name || "") && node.attribs?.["ac:name"] !== "status";
935
+ }
936
+ function storageText(node, depth = 0) {
937
+ if (!node || depth > 64) return "";
938
+ return node.type === "text" ? node.data || "" : (node.children || []).map((child) => storageText(child, depth + 1)).join("");
939
+ }
940
+ function collapseWhitespace(value) {
941
+ return value.replace(/[ \t\n\r\u00a0]+/g, " ");
942
+ }
943
+
944
+ // src/adf.ts
945
+ function parseADFDocument(value) {
946
+ if (!value.trim()) return [];
947
+ let document;
948
+ try {
949
+ document = JSON.parse(value);
950
+ } catch {
951
+ throw new TypeError("body is not readable Atlassian Document Format");
952
+ }
953
+ if (!isADFNode(document) || document.type !== "doc") throw new TypeError("body is not readable Atlassian Document Format");
954
+ return readBlocks2(document.content || [], 0);
955
+ }
956
+ function isADFNode(value) {
957
+ return !!value && typeof value === "object" && !Array.isArray(value);
958
+ }
959
+ function readBlocks2(nodes, depth) {
960
+ let blocks = [], inlines = [];
961
+ for (const node of nodes) {
962
+ if (["text", "hardBreak", "mention", "status", "emoji", "inlineCard", "date", "placeholder", "inlineExtension", "mediaInline"].includes(node.type || "")) {
963
+ inlines = appendADFInline(inlines, node);
964
+ continue;
965
+ }
966
+ blocks = appendParagraphBlock(blocks, inlines);
967
+ inlines = [];
968
+ blocks.push(...readBlock2(node, depth + 1));
969
+ }
970
+ return appendParagraphBlock(blocks, inlines);
971
+ }
972
+ function readBlock2(node, depth) {
973
+ if (depth > 64) return [];
974
+ const content = Array.isArray(node.content) ? node.content : [];
975
+ switch (node.type) {
976
+ case "paragraph":
977
+ return appendParagraphBlock([], readInlines2(content));
978
+ case "heading":
979
+ return [{ kind: "heading", headingLevel: numberAttribute(node.attrs, "level"), inlines: trimInlineEdges(readInlines2(content)) }];
980
+ case "bulletList":
981
+ case "orderedList":
982
+ case "taskList":
983
+ case "decisionList":
984
+ return [readList2(node, depth)];
985
+ case "blockquote":
986
+ case "panel":
987
+ return [{ kind: "quote", children: readBlocks2(content, depth) }];
988
+ case "codeBlock":
989
+ return [{ kind: "code", codeLanguage: markdownFenceLanguage(stringAttribute(node.attrs, "language")), codeText: content.map((child) => child.text || "").join("") }];
990
+ case "rule":
991
+ return [{ kind: "rule" }];
992
+ case "table":
993
+ return [{ kind: "table", tableRows: readTableRows2(node, depth) }];
994
+ case "expand":
995
+ case "nestedExpand": {
996
+ const title = stringAttribute(node.attrs, "title").trim();
997
+ const prefix = title ? [{ kind: "paragraph", inlines: [{ text: title, isStrong: true }] }] : [];
998
+ return [...prefix, ...readBlocks2(content, depth)];
999
+ }
1000
+ case "blockCard":
1001
+ case "embedCard": {
1002
+ const href = safeLinkHref(stringAttribute(node.attrs, "url"));
1003
+ return href ? [{ kind: "paragraph", inlines: [{ text: href, linkHref: href }] }] : [];
1004
+ }
1005
+ case "mediaSingle":
1006
+ case "mediaGroup":
1007
+ case "media":
1008
+ case "extension":
1009
+ return [];
1010
+ default:
1011
+ return readBlocks2(content, depth);
1012
+ }
1013
+ }
1014
+ function readList2(node, depth) {
1015
+ const kind = node.type === "orderedList" ? "orderedList" : node.type === "taskList" ? "taskList" : "bulletList";
1016
+ return { kind, orderedStart: numberAttribute(node.attrs, "order"), listItems: (node.content || []).map((item) => ({
1017
+ isTaskDone: stringAttribute(item.attrs, "state") === "DONE",
1018
+ blocks: item.type === "taskItem" || item.type === "decisionItem" ? appendParagraphBlock([], readInlines2(item.content || [])) : readBlocks2(item.content || [], depth)
1019
+ })) };
1020
+ }
1021
+ function readTableRows2(node, depth) {
1022
+ return (node.content || []).filter((row) => row.type === "tableRow").map((row) => ({
1023
+ isHeader: !!row.content?.length && row.content.every((cell) => cell.type === "tableHeader"),
1024
+ cells: (row.content || []).map((cell) => flattenBlocksToInlines(readBlocks2(cell.content || [], depth)))
1025
+ }));
1026
+ }
1027
+ function readInlines2(nodes) {
1028
+ let inlines = [];
1029
+ for (const node of nodes) inlines = appendADFInline(inlines, node);
1030
+ return inlines;
1031
+ }
1032
+ function appendADFInline(inlines, node) {
1033
+ const span = {};
1034
+ for (const mark of node.marks || []) {
1035
+ if (mark.type === "strong") span.isStrong = true;
1036
+ if (mark.type === "em") span.isEmphasis = true;
1037
+ if (mark.type === "code") span.isCode = true;
1038
+ if (mark.type === "strike") span.isStrikethrough = true;
1039
+ if (mark.type === "link") span.linkHref = safeLinkHref(stringAttribute(mark.attrs, "href"));
1040
+ }
1041
+ switch (node.type) {
1042
+ case "text":
1043
+ span.text = node.text || "";
1044
+ break;
1045
+ case "hardBreak":
1046
+ return appendInline(inlines, { isLineBreak: true });
1047
+ case "mention":
1048
+ case "status":
1049
+ span.text = stringAttribute(node.attrs, "text");
1050
+ break;
1051
+ case "emoji":
1052
+ span.text = stringAttribute(node.attrs, "text") || stringAttribute(node.attrs, "shortName");
1053
+ break;
1054
+ case "inlineCard":
1055
+ span.linkHref = safeLinkHref(stringAttribute(node.attrs, "url"));
1056
+ span.text = span.linkHref;
1057
+ break;
1058
+ case "date": {
1059
+ const timestamp = stringAttribute(node.attrs, "timestamp");
1060
+ span.text = formatADFDate(timestamp);
1061
+ break;
1062
+ }
1063
+ }
1064
+ return appendInline(inlines, span);
1065
+ }
1066
+ function stringAttribute(attributes, key) {
1067
+ const value = attributes?.[key];
1068
+ return typeof value === "string" ? value : "";
1069
+ }
1070
+ function numberAttribute(attributes, key) {
1071
+ const value = attributes?.[key];
1072
+ return typeof value === "number" ? value : 0;
1073
+ }
1074
+ function formatADFDate(timestamp) {
1075
+ if (!/^[+-]?\d+$/.test(timestamp)) return "";
1076
+ const milliseconds = BigInt(timestamp);
1077
+ if (milliseconds < -(1n << 63n) || milliseconds > (1n << 63n) - 1n) return "";
1078
+ let days = milliseconds / 86400000n;
1079
+ if (milliseconds < 0n && milliseconds % 86400000n !== 0n) days--;
1080
+ const eraDays = days + 719468n;
1081
+ const era = eraDays >= 0n ? eraDays / 146097n : (eraDays - 146096n) / 146097n;
1082
+ const dayOfEra = eraDays - era * 146097n;
1083
+ const yearOfEra = (dayOfEra - dayOfEra / 1460n + dayOfEra / 36524n - dayOfEra / 146096n) / 365n;
1084
+ let year = yearOfEra + era * 400n;
1085
+ const dayOfYear = dayOfEra - (365n * yearOfEra + yearOfEra / 4n - yearOfEra / 100n);
1086
+ const monthPosition = (5n * dayOfYear + 2n) / 153n;
1087
+ const day = dayOfYear - (153n * monthPosition + 2n) / 5n + 1n;
1088
+ const month = monthPosition + (monthPosition < 10n ? 3n : -9n);
1089
+ if (month <= 2n) year++;
1090
+ return `${year.toString().padStart(4, "0")}-${month.toString().padStart(2, "0")}-${day.toString().padStart(2, "0")}`;
1091
+ }
1092
+
1093
+ // src/time.ts
1094
+ function parseGoRFC3339(value) {
1095
+ const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:[.,](\d+))?(Z|[+-]\d{2}:\d{2})$/.exec(value);
1096
+ if (!match) return void 0;
1097
+ const year = Number(match[1]), month = Number(match[2]), day = Number(match[3]);
1098
+ const hour = Number(match[4]), minute = Number(match[5]), second = Number(match[6]);
1099
+ if (month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month) || hour > 23 || minute > 59 || second > 59) return void 0;
1100
+ const zone = match[8];
1101
+ const zoneHours = zone === "Z" ? 0 : Number(zone.slice(1, 3));
1102
+ const zoneMinutes = zone === "Z" ? 0 : Number(zone.slice(4, 6));
1103
+ if (zoneMinutes > 59) return void 0;
1104
+ const offsetMinutes = (zone.startsWith("-") ? -1 : 1) * (zoneHours * 60 + zoneMinutes);
1105
+ const fraction = (match[7] || "").slice(0, 9).padEnd(9, "0");
1106
+ const calendar = /* @__PURE__ */ new Date(0);
1107
+ calendar.setUTCFullYear(year, month - 1, day);
1108
+ calendar.setUTCHours(hour, minute, second, Number(fraction.slice(0, 3)));
1109
+ const epochMs = calendar.getTime() - offsetMinutes * 6e4;
1110
+ if (!Number.isFinite(epochMs)) return void 0;
1111
+ const canonicalFraction = fraction.replace(/0+$/, "");
1112
+ const canonicalZone = zone === "Z" || offsetMinutes === 0 ? "Z" : zone;
1113
+ const canonical = value.slice(0, 19) + (canonicalFraction ? `.${canonicalFraction}` : "") + canonicalZone;
1114
+ return { canonical, epochMs };
1115
+ }
1116
+ function daysInMonth(year, month) {
1117
+ if ([4, 6, 9, 11].includes(month)) return 30;
1118
+ if (month === 2) return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28;
1119
+ return 31;
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
+
1244
+ // src/operations.ts
1245
+ var emptyTime = "0001-01-01T00:00:00Z";
1246
+ var idPattern = /^[1-9][0-9]{0,18}$/;
1247
+ var spaceKeyPattern = /^~?[A-Za-z0-9_-]{1,255}$/;
1248
+ var SearchPagesOperation = class {
1249
+ /** Bind the client. */
1250
+ constructor(client) {
1251
+ this.client = client;
1252
+ }
1253
+ client;
1254
+ /** Return the stable definition. */
1255
+ definition() {
1256
+ return SearchPagesDefinition;
1257
+ }
1258
+ /** Execute one authenticated search. */
1259
+ async invoke(call, input) {
1260
+ const operation = "searchPages";
1261
+ let cql;
1262
+ try {
1263
+ cql = buildCql(input.filter);
1264
+ } catch (error) {
1265
+ return newQueryBranch("defect", { cql: "", pages: [] }, zeroReceipt(), confluenceFailure(operation, "VALIDATION", errorMessage(error)));
1266
+ }
1267
+ const pageSize = input.pageSize || 25;
1268
+ if (!Number.isInteger(pageSize) || pageSize < 1 || pageSize > 100) return newQueryBranch("defect", { cql: "", pages: [] }, zeroReceipt(), confluenceFailure(operation, "VALIDATION", "pageSize must be between 1 and 100"));
1269
+ const cursor = (input.cursor || "").trim();
1270
+ if (cursor && !isCursor(cursor)) return newQueryBranch("defect", { cql: "", pages: [] }, zeroReceipt(), confluenceFailure(operation, "VALIDATION", "cursor must be the printable cursor from a previous search page"));
1271
+ const output = { cql, pages: [] };
1272
+ const started = await this.client.startSession(call, operation);
1273
+ if ("error" in started) return started.error.isRetryable ? newQueryRetry(started.error.failure, started.error.retryAfterMs) : newQueryBranch("defect", output, zeroReceipt(), started.error.failure);
1274
+ const session = started.session;
1275
+ const response = await this.client.exchange(session, "GET", "search", "/content/search", { cql, limit: String(pageSize), expand: "space,version", ...cursor ? { cursor } : {} });
1276
+ const classification = this.client.classifyRead(operation, "page search", response);
1277
+ const receipt = this.client.receipt(session, response);
1278
+ if (classification.outcome === "retry") return newQueryRetry(classification.failure, classification.retryAfterMs);
1279
+ if (classification.outcome !== "accepted") return newQueryBranch(classification.outcome === "invalid" ? "invalidResponse" : classification.outcome === "defect" ? "defect" : "providerRejected", output, receipt, classification.failure);
1280
+ let decoded;
1281
+ try {
1282
+ decoded = decodeObject(response);
1283
+ } catch {
1284
+ return newQueryBranch("invalidResponse", output, receipt, confluenceFailure(operation, "PROTOCOL", "Confluence returned an invalid search page"));
1285
+ }
1286
+ const links = objectField(decoded, "_links");
1287
+ const nextLink = stringField(links, "next");
1288
+ if (nextLink) {
1289
+ try {
1290
+ output.nextCursor = readNextCursor(nextLink);
1291
+ } catch {
1292
+ return newQueryBranch("invalidResponse", output, receipt, confluenceFailure(operation, "PROTOCOL", "Confluence returned an invalid search cursor"));
1293
+ }
1294
+ }
1295
+ const results = decoded.results;
1296
+ if (results !== void 0 && !Array.isArray(results)) return newQueryBranch("invalidResponse", { cql, pages: [] }, receipt, confluenceFailure(operation, "PROTOCOL", "Confluence returned an invalid search page"));
1297
+ for (const resource of results || []) {
1298
+ try {
1299
+ const summary = decodePageSummary(resource, stringField(links, "base"));
1300
+ if (summary && (!input.filter.modifiedSince || summary.lastModifiedAt === emptyTime || parseGoRFC3339(summary.lastModifiedAt).epochMs >= parseGoRFC3339(input.filter.modifiedSince).epochMs)) output.pages.push(summary);
1301
+ } catch (error) {
1302
+ return newQueryBranch("invalidResponse", { cql, pages: [] }, receipt, confluenceFailure(operation, "PROTOCOL", "Confluence returned an invalid page in the search results: " + errorMessage(error)));
1303
+ }
1304
+ }
1305
+ return newQueryBranch("searched", output, receipt);
1306
+ }
1307
+ };
1308
+ var GetPageOperation = class {
1309
+ /** Bind the client. */
1310
+ constructor(client) {
1311
+ this.client = client;
1312
+ }
1313
+ client;
1314
+ /** Return the stable definition. */
1315
+ definition() {
1316
+ return GetPageDefinition;
1317
+ }
1318
+ /** Execute one page read. */
1319
+ async invoke(call, input) {
1320
+ const operation = "getPage";
1321
+ let pageId;
1322
+ try {
1323
+ pageId = validateId(input.pageId, "pageId");
1324
+ } catch (error) {
1325
+ return newQueryBranch("defect", emptyPage(), zeroReceipt(), confluenceFailure(operation, "VALIDATION", errorMessage(error)));
1326
+ }
1327
+ const representation = input.bodyRepresentation || "storage";
1328
+ if (representation !== "storage" && representation !== "atlas_doc_format") return newQueryBranch("defect", emptyPage(), zeroReceipt(), confluenceFailure(operation, "VALIDATION", "bodyRepresentation must be storage or atlas_doc_format"));
1329
+ const format = input.bodyFormat || "markdown";
1330
+ if (format !== "markdown" && format !== "plainText") return newQueryBranch("defect", emptyPage(), zeroReceipt(), confluenceFailure(operation, "VALIDATION", "bodyFormat must be markdown or plainText"));
1331
+ const maxCharacters = input.maxBodyCharacters || 32768;
1332
+ if (!Number.isInteger(maxCharacters) || maxCharacters < 1 || maxCharacters > 131072) return newQueryBranch("defect", emptyPage(), zeroReceipt(), confluenceFailure(operation, "VALIDATION", "maxBodyCharacters must be between 1 and 131072"));
1333
+ const started = await this.client.startSession(call, operation);
1334
+ if ("error" in started) return started.error.isRetryable ? newQueryRetry(started.error.failure, started.error.retryAfterMs) : newQueryBranch("defect", emptyPage(), zeroReceipt(), started.error.failure);
1335
+ const session = started.session;
1336
+ const response = await this.client.exchange(session, "GET", "content", `/pages/${pathEscape(pageId)}`, { "body-format": representation });
1337
+ const classification = this.client.classifyRead(operation, "page read", response);
1338
+ const receipt = this.client.receipt(session, response, pageId);
1339
+ if (classification.outcome === "retry") return newQueryRetry(classification.failure, classification.retryAfterMs);
1340
+ if (classification.outcome !== "accepted") return newQueryBranch(classification.outcome === "notFound" ? "notFound" : classification.outcome === "invalid" ? "invalidResponse" : classification.outcome === "defect" ? "defect" : "providerRejected", emptyPage(), receipt, classification.failure);
1341
+ let decoded;
1342
+ try {
1343
+ decoded = decodeObject(response);
1344
+ } catch {
1345
+ return newQueryBranch("invalidResponse", emptyPage(), receipt, confluenceFailure(operation, "PROTOCOL", "Confluence returned an invalid page"));
1346
+ }
1347
+ try {
1348
+ return newQueryBranch("found", decodePage(decoded, representation, format, maxCharacters), receipt);
1349
+ } catch (error) {
1350
+ return newQueryBranch("invalidResponse", emptyPage(), receipt, confluenceFailure(operation, "PROTOCOL", "Confluence returned an unreadable page: " + errorMessage(error)));
1351
+ }
1352
+ }
1353
+ };
1354
+ var CreatePageOperation = class {
1355
+ /** Bind the client. */
1356
+ constructor(client) {
1357
+ this.client = client;
1358
+ }
1359
+ client;
1360
+ /** Return the stable definition. */
1361
+ definition() {
1362
+ return CreatePageDefinition;
1363
+ }
1364
+ /** Derive the stable Dex idempotency key. */
1365
+ idempotencyKey(callId) {
1366
+ return callId;
1367
+ }
1368
+ /** Execute one create with read-back reconciliation. */
1369
+ async invoke(call, input) {
1370
+ const operation = "createPage";
1371
+ const requested = { title: (input.title || "").trim() };
1372
+ const spaceId = (input.spaceId || "").trim(), spaceKey = (input.spaceKey || "").trim(), parentId = (input.parentPageId || "").trim();
1373
+ if (spaceId) requested.spaceId = spaceId;
1374
+ if (spaceKey) requested.spaceKey = spaceKey;
1375
+ if (parentId) requested.parentPageId = parentId;
1376
+ let storage, comparisonText;
1377
+ try {
1378
+ if (!!spaceId === !!spaceKey) throw new TypeError("set exactly one of spaceId and spaceKey");
1379
+ if (spaceId && !idPattern.test(spaceId)) throw new TypeError("spaceId must be a numeric Confluence space ID");
1380
+ if (spaceKey && !spaceKeyPattern.test(spaceKey)) throw new TypeError("spaceKey must be a space key such as OPS");
1381
+ if (parentId && !idPattern.test(parentId)) throw new TypeError("parentPageId must be a numeric Confluence page ID");
1382
+ requested.title = validateTitle(input.title);
1383
+ ({ storage, comparisonText } = convertWrittenBody(input.body, input.bodyFormat, "body"));
1384
+ } catch (error) {
1385
+ return newMutationBranch("defect", requested, zeroReceipt(), confluenceFailure(operation, "VALIDATION", errorMessage(error)));
1386
+ }
1387
+ const started = await this.client.startSession(call, operation);
1388
+ if ("error" in started) return started.error.isRetryable ? newMutationRetry(started.error.failure, started.error.retryAfterMs) : newMutationBranch("defect", requested, zeroReceipt(), started.error.failure);
1389
+ const session = started.session;
1390
+ if (!spaceId) {
1391
+ const resolved = await resolveSpaceId(this.client, session, operation, spaceKey);
1392
+ if ("classification" in resolved) {
1393
+ const state2 = resolved.classification;
1394
+ if (state2.outcome === "retry") return newMutationRetry(state2.failure, state2.retryAfterMs);
1395
+ const branch = state2.outcome === "notFound" ? "notFound" : state2.outcome === "defect" ? "defect" : "providerRejected";
1396
+ return newMutationBranch(branch, requested, this.client.receipt(session, emptyResponse()), state2.failure);
1397
+ }
1398
+ requested.spaceId = resolved.spaceId;
1399
+ }
1400
+ const body = { spaceId: requested.spaceId, status: "current", title: requested.title, ...parentId ? { parentId } : {}, body: { representation: "storage", value: storage } };
1401
+ const earliestSendAt = earliestDispatchTime(call, this.client.now());
1402
+ const checkpoint = readDispatchCheckpoint(call);
1403
+ const firstSendAt = checkpoint ? Math.min(earliestSendAt, checkpoint.dispatchedAt || earliestSendAt) : earliestSendAt;
1404
+ if (checkpoint) {
1405
+ const lookup2 = await findPageByTitle(this.client, session, operation, body.spaceId, body.title);
1406
+ const decided = this.reconcileByTitle(session, requested, comparisonText, parentId, firstSendAt, lookup2);
1407
+ if (decided) return decided;
1408
+ }
1409
+ try {
1410
+ await call.context.recordHeartbeat({ dispatchedAtUnixMilli: firstSendAt });
1411
+ } catch {
1412
+ return newMutationRetry(confluenceFailure(operation, "AVAILABILITY", "the create checkpoint could not be recorded, so nothing was sent to Confluence"));
1413
+ }
1414
+ const response = await this.client.exchange(session, "POST", "content", "/pages", void 0, body);
1415
+ let state = this.client.classifyWrite(operation, "page", response);
1416
+ const receipt = this.client.receipt(session, response);
1417
+ if (state.outcome === "accepted") {
1418
+ try {
1419
+ const resource = decodeObject(response);
1420
+ validatePageResource(resource);
1421
+ return newMutationBranch("created", createdOutput(requested, resource, "", false), this.client.receipt(session, response, stringField(resource, "id")));
1422
+ } catch {
1423
+ state = { outcome: "ambiguous", failure: confluenceFailure(operation, "PROTOCOL", "Confluence accepted the page but returned an unusable page"), retryAfterMs: 0 };
1424
+ }
1425
+ }
1426
+ if (state.outcome === "notApplied") {
1427
+ clearDispatchCheckpoint(call);
1428
+ return newMutationRetry(state.failure, state.retryAfterMs);
1429
+ }
1430
+ if (state.outcome === "notFound") return newMutationBranch("notFound", requested, receipt, state.failure);
1431
+ if (state.outcome === "defect") {
1432
+ clearDispatchCheckpoint(call);
1433
+ return newMutationBranch("defect", requested, receipt, state.failure);
1434
+ }
1435
+ if (state.outcome === "rejected") {
1436
+ if (response.status !== 400 && response.status !== 409) return newMutationBranch("providerRejected", requested, receipt, state.failure);
1437
+ const lookup2 = await findPageByTitle(this.client, session, operation, body.spaceId, body.title);
1438
+ const decided = this.reconcileByTitle(session, requested, comparisonText, parentId, firstSendAt, lookup2);
1439
+ return decided || newMutationBranch("providerRejected", requested, receipt, state.failure);
1440
+ }
1441
+ const lookup = await findPageByTitle(this.client, session, operation, body.spaceId, body.title);
1442
+ if (lookup.page) {
1443
+ const decided = this.reconcileByTitle(session, requested, comparisonText, parentId, firstSendAt, lookup);
1444
+ if (decided) return decided;
1445
+ }
1446
+ return newMutationRetry(state.failure, Math.max(state.retryAfterMs, 5e3));
1447
+ }
1448
+ reconcileByTitle(session, requested, comparisonText, parentId, earliestSendAt, lookup) {
1449
+ const operation = "createPage";
1450
+ const state = lookup.classification;
1451
+ if (state.outcome === "notFound") return newMutationBranch("notFound", requested, this.client.receipt(session, lookup.response), state.failure);
1452
+ if (state.outcome === "rejected") return void 0;
1453
+ if (state.outcome !== "accepted") return newMutationRetry({ ...state.failure, message: "an earlier create may have reached Confluence and its page could not be looked up: " + state.failure.message }, Math.max(state.retryAfterMs, 5e3));
1454
+ if (!lookup.page) return void 0;
1455
+ const page = lookup.page;
1456
+ const output = createdOutput(requested, page, lookup.siteBase, false);
1457
+ const receipt = this.client.receipt(session, lookup.response, stringField(page, "id"));
1458
+ const createdAt = parseGoRFC3339(stringField(page, "createdAt"))?.epochMs;
1459
+ const body = objectField(objectField(page, "body"), "storage");
1460
+ const matches = createdAt !== void 0 && createdAt >= earliestSendAt - 6e4 && (!parentId || stringField(page, "parentId") === parentId) && storageComparisonText(stringField(body, "value")) === comparisonText;
1461
+ if (matches) return newMutationBranch("created", { ...output, isConfirmedByTitleLookup: true }, receipt);
1462
+ return newMutationBranch("titleConflict", output, receipt, confluenceFailure(operation, "CONFLICT", "another page in the space already has this title, so nothing was created"));
1463
+ }
1464
+ };
1465
+ var UpdatePageOperation = class {
1466
+ /** Bind the client. */
1467
+ constructor(client) {
1468
+ this.client = client;
1469
+ }
1470
+ client;
1471
+ /** Return the stable definition. */
1472
+ definition() {
1473
+ return UpdatePageDefinition;
1474
+ }
1475
+ /** Derive the stable Dex idempotency key. */
1476
+ idempotencyKey(callId) {
1477
+ return callId;
1478
+ }
1479
+ /** Execute one update with version reconciliation. */
1480
+ async invoke(call, input) {
1481
+ const operation = "updatePage";
1482
+ const requested = { pageId: (input.pageId || "").trim(), title: (input.title || "").trim() };
1483
+ let pageId, marker, body;
1484
+ try {
1485
+ pageId = validateId(input.pageId, "pageId");
1486
+ requested.title = validateTitle(input.title);
1487
+ if (!Number.isInteger(input.nextVersionNumber) || input.nextVersionNumber < 2) throw new TypeError("nextVersionNumber must be the page's current version number plus one, at least 2");
1488
+ const message = (input.versionMessage || "").trim();
1489
+ if ([...message].length > 200) throw new TypeError("versionMessage cannot exceed 200 characters");
1490
+ if (hasControlCharacter(message)) throw new TypeError("versionMessage must be one line without control characters");
1491
+ const { storage } = convertWrittenBody(input.body, input.bodyFormat, "body");
1492
+ marker = "dex:" + createHash("sha256").update(call.idempotencyKey || call.id).digest("hex").slice(0, 16);
1493
+ body = { id: pageId, status: "current", title: requested.title, body: { representation: "storage", value: storage }, version: { number: input.nextVersionNumber, message: (message ? message + " " : "") + `[${marker}]` } };
1494
+ } catch (error) {
1495
+ return newMutationBranch("defect", requested, zeroReceipt(), confluenceFailure(operation, "VALIDATION", errorMessage(error)));
1496
+ }
1497
+ const started = await this.client.startSession(call, operation);
1498
+ if ("error" in started) return started.error.isRetryable ? newMutationRetry(started.error.failure, started.error.retryAfterMs) : newMutationBranch("defect", requested, zeroReceipt(), started.error.failure);
1499
+ const session = started.session;
1500
+ const response = await this.client.exchange(session, "PUT", "content", `/pages/${pathEscape(pageId)}`, void 0, body);
1501
+ let classification = this.client.classifyWrite(operation, "page update", response);
1502
+ const receipt = this.client.receipt(session, response, pageId);
1503
+ if (classification.outcome === "accepted") {
1504
+ try {
1505
+ const page = decodeObject(response);
1506
+ validatePageResource(page);
1507
+ if (numberField(objectField(page, "version"), "number") !== input.nextVersionNumber) throw new TypeError();
1508
+ return newMutationBranch("updated", updatedOutput(requested, page, "", false), receipt);
1509
+ } catch {
1510
+ classification = { outcome: "ambiguous", failure: confluenceFailure(operation, "PROTOCOL", "Confluence accepted the update but returned an unusable page"), retryAfterMs: 0 };
1511
+ }
1512
+ }
1513
+ if (classification.outcome === "notApplied") return newMutationRetry(classification.failure, classification.retryAfterMs);
1514
+ if (classification.outcome === "notFound") return newMutationBranch("notFound", requested, receipt, classification.failure);
1515
+ if (classification.outcome === "defect") return newMutationBranch("defect", requested, receipt, classification.failure);
1516
+ if (classification.outcome === "rejected" && response.status !== 400 && response.status !== 409) return newMutationBranch("providerRejected", requested, receipt, classification.failure);
1517
+ const lookup = await readPage(this.client, session, operation, pageId);
1518
+ const readBack = await this.reportReadBack(session, requested, input.nextVersionNumber, marker, lookup);
1519
+ if (readBack) return readBack;
1520
+ if (classification.outcome === "rejected") return newMutationBranch("providerRejected", requested, this.client.receipt(session, lookup.response, pageId), classification.failure);
1521
+ return newMutationRetry(classification.failure, Math.max(classification.retryAfterMs, 5e3));
1522
+ }
1523
+ async reportReadBack(session, requested, nextVersion, marker, lookup) {
1524
+ const operation = "updatePage";
1525
+ const receipt = this.client.receipt(session, lookup.response, requested.pageId);
1526
+ const classification = lookup.classification;
1527
+ if (classification.outcome === "notFound") return newMutationBranch("notFound", requested, receipt, classification.failure);
1528
+ if (classification.outcome !== "accepted") return newMutationRetry({ ...classification.failure, message: "the update outcome is unknown and the page could not be read back: " + classification.failure.message }, Math.max(classification.retryAfterMs, 5e3));
1529
+ const page = lookup.page;
1530
+ const version = objectField(page, "version"), current = numberField(version, "number");
1531
+ if (current === nextVersion && stringField(version, "message").includes(marker)) return newMutationBranch("updated", updatedOutput(requested, page, lookup.siteBase, true), receipt);
1532
+ if (current === nextVersion - 1) return void 0;
1533
+ if (current > nextVersion) {
1534
+ const response = await this.client.exchange(session, "GET", "content", `/pages/${pathEscape(requested.pageId)}/versions/${nextVersion}`);
1535
+ const state = this.client.classifyRead(operation, "page version", response);
1536
+ if (state.outcome === "retry") return newMutationRetry(state.failure, state.retryAfterMs);
1537
+ if (state.outcome === "accepted") {
1538
+ try {
1539
+ const oldVersion = decodeObject(response);
1540
+ if (numberField(oldVersion, "number") === nextVersion && stringField(oldVersion, "message").includes(marker)) return newMutationBranch("updated", { ...updatedOutput(requested, page, lookup.siteBase, true), versionNumber: nextVersion }, receipt);
1541
+ } catch {
1542
+ }
1543
+ }
1544
+ }
1545
+ return newMutationBranch("versionConflict", updatedOutput(requested, page, lookup.siteBase, false), receipt, confluenceFailure(operation, "CONFLICT", "the page is no longer at the version before nextVersionNumber, so nothing was changed"));
1546
+ }
1547
+ };
1548
+ var AddCommentOperation = class {
1549
+ /** Bind the client. */
1550
+ constructor(client) {
1551
+ this.client = client;
1552
+ }
1553
+ client;
1554
+ /** Return the stable definition. */
1555
+ definition() {
1556
+ return AddCommentDefinition;
1557
+ }
1558
+ /** Derive the stable Dex idempotency key. */
1559
+ idempotencyKey(callId) {
1560
+ return callId;
1561
+ }
1562
+ /** Execute one comment send or read-back. */
1563
+ async invoke(call, input) {
1564
+ const operation = "addComment";
1565
+ const requested = { pageId: (input.pageId || "").trim(), createdAt: emptyTime };
1566
+ let pageId, storage, comparisonText;
1567
+ try {
1568
+ pageId = validateId(input.pageId, "pageId");
1569
+ ({ storage, comparisonText } = convertWrittenBody(input.body, input.bodyFormat, "body"));
1570
+ } catch (error) {
1571
+ return newMutationBranch("defect", requested, zeroReceipt(), confluenceFailure(operation, "VALIDATION", errorMessage(error)));
1572
+ }
1573
+ const started = await this.client.startSession(call, operation);
1574
+ if ("error" in started) return started.error.isRetryable ? newMutationRetry(started.error.failure, started.error.retryAfterMs) : newMutationBranch("defect", requested, zeroReceipt(), started.error.failure);
1575
+ const session = started.session;
1576
+ const checkpoint = readDispatchCheckpoint(call);
1577
+ const earliestSendAt = earliestDispatchTime(call, this.client.now());
1578
+ if (checkpoint) return this.reconcileEarlierDispatch(session, requested, comparisonText, Math.min(earliestSendAt, checkpoint.dispatchedAt || earliestSendAt));
1579
+ try {
1580
+ await call.context.recordHeartbeat({ dispatchedAtUnixMilli: earliestSendAt });
1581
+ } catch {
1582
+ return newMutationRetry(confluenceFailure(operation, "AVAILABILITY", "the comment checkpoint could not be recorded, so nothing was sent to Confluence"));
1583
+ }
1584
+ const response = await this.client.exchange(session, "POST", "content", "/footer-comments", void 0, { pageId, body: { representation: "storage", value: storage } });
1585
+ let classification = this.client.classifyWrite(operation, "comment", response);
1586
+ const receipt = this.client.receipt(session, response);
1587
+ if (classification.outcome === "accepted") {
1588
+ try {
1589
+ const comment = decodeObject(response);
1590
+ const id = stringField(comment, "id");
1591
+ if (idPattern.test(id)) return newMutationBranch("added", addedCommentOutput(requested, comment, false), this.client.receipt(session, response, id));
1592
+ } catch {
1593
+ }
1594
+ classification = { outcome: "ambiguous", failure: confluenceFailure(operation, "PROTOCOL", "Confluence accepted the comment but returned an unusable comment"), retryAfterMs: 0 };
1595
+ }
1596
+ if (classification.outcome === "notApplied") {
1597
+ clearDispatchCheckpoint(call);
1598
+ return newMutationRetry(classification.failure, classification.retryAfterMs);
1599
+ }
1600
+ if (classification.outcome === "notFound") return newMutationBranch("notFound", requested, receipt, classification.failure);
1601
+ if (classification.outcome === "rejected") return newMutationBranch("providerRejected", requested, receipt, classification.failure);
1602
+ if (classification.outcome === "defect") {
1603
+ clearDispatchCheckpoint(call);
1604
+ return newMutationBranch("defect", requested, receipt, classification.failure);
1605
+ }
1606
+ return newMutationRetry(classification.failure, Math.max(classification.retryAfterMs, 5e3));
1607
+ }
1608
+ async reconcileEarlierDispatch(session, requested, comparisonText, earliestSendAt) {
1609
+ const operation = "addComment";
1610
+ const response = await this.client.exchange(session, "GET", "content", `/pages/${pathEscape(requested.pageId)}/footer-comments`, { "body-format": "storage", sort: "-created-date", limit: "25" });
1611
+ const classification = this.client.classifyRead(operation, "page comments", response);
1612
+ const receipt = this.client.receipt(session, response);
1613
+ if (classification.outcome === "retry") return newMutationRetry(classification.failure, classification.retryAfterMs);
1614
+ if (classification.outcome === "notFound") return newMutationBranch("notFound", requested, receipt, classification.failure);
1615
+ if (classification.outcome !== "accepted") return newMutationUncertain(requested, { ...classification.failure, message: "an earlier attempt of this Step sent the comment, and the page's comments could not be read back: " + classification.failure.message }, receipt);
1616
+ let results;
1617
+ try {
1618
+ const decoded = decodeObject(response);
1619
+ if (!Array.isArray(decoded.results)) throw new TypeError();
1620
+ results = decoded.results;
1621
+ } catch {
1622
+ return newMutationUncertain(requested, confluenceFailure(operation, "PROTOCOL", "an earlier attempt of this Step sent the comment, and the page's comments read back are invalid"), receipt);
1623
+ }
1624
+ for (const value of results) {
1625
+ if (!value || typeof value !== "object" || Array.isArray(value)) continue;
1626
+ const comment = value;
1627
+ try {
1628
+ const id = stringField(comment, "id"), version = objectField(comment, "version"), body = objectField(objectField(comment, "body"), "storage");
1629
+ const createdAt = parseGoRFC3339(stringField(version, "createdAt"))?.epochMs;
1630
+ if (idPattern.test(id) && createdAt !== void 0 && createdAt >= earliestSendAt - 6e4 && storageComparisonText(stringField(body, "value")) === comparisonText) return newMutationBranch("added", addedCommentOutput(requested, comment, true), this.client.receipt(session, response, id));
1631
+ } catch {
1632
+ }
1633
+ }
1634
+ return newMutationUncertain(requested, confluenceFailure(operation, "TRANSPORT", "an earlier attempt of this Step sent the comment without a confirmed outcome, and the page shows no matching comment, so it is not sent again"), receipt);
1635
+ }
1636
+ };
1637
+ function errorMessage(error) {
1638
+ return error instanceof Error ? error.message : "invalid input";
1639
+ }
1640
+ function objectField(object, key) {
1641
+ const value = object[key];
1642
+ if (value == null) return {};
1643
+ if (typeof value !== "object" || Array.isArray(value)) throw new TypeError(`${key} has an invalid type`);
1644
+ return value;
1645
+ }
1646
+ function stringField(object, key) {
1647
+ const value = object[key];
1648
+ if (value !== void 0 && typeof value !== "string") throw new TypeError(`${key} has an invalid type`);
1649
+ return value || "";
1650
+ }
1651
+ function numberField(object, key) {
1652
+ const value = object[key];
1653
+ if (value !== void 0 && (typeof value !== "number" || !Number.isInteger(value))) throw new TypeError(`${key} has an invalid type`);
1654
+ return value || 0;
1655
+ }
1656
+ function isCursor(value) {
1657
+ return !!value && Buffer.byteLength(value) <= 4096 && /^[\x21-\x7e]+$/.test(value);
1658
+ }
1659
+ function validateId(value, field) {
1660
+ const trimmed = value.trim();
1661
+ if (!idPattern.test(trimmed)) throw new TypeError(`${field} must be a numeric Confluence content ID`);
1662
+ return trimmed;
1663
+ }
1664
+ function emptyPage() {
1665
+ return { id: "", title: "", status: "", spaceId: "", createdAt: emptyTime, version: { number: 0, createdAt: emptyTime }, body: "", bodyFormat: "" };
1666
+ }
1667
+ function webURL(base, path) {
1668
+ if (!base.startsWith("https://") || !/^\/[\x21-\x7e]*$/.test(path)) return "";
1669
+ try {
1670
+ const parsed = new URL(base);
1671
+ if (parsed.username || parsed.password || parsed.search || parsed.hash) return "";
1672
+ } catch {
1673
+ return "";
1674
+ }
1675
+ const url = base.replace(/\/+$/, "") + path;
1676
+ return Buffer.byteLength(url) <= 2048 ? url : "";
1677
+ }
1678
+ function decodePageSummary(value, base) {
1679
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("page resource is invalid");
1680
+ const resource = value;
1681
+ if (stringField(resource, "type") !== "page") return void 0;
1682
+ const id = stringField(resource, "id");
1683
+ const title = stringField(resource, "title");
1684
+ if (!idPattern.test(id) || !title) throw new TypeError("page ID or title is missing");
1685
+ const summary = { id, title, lastModifiedAt: emptyTime };
1686
+ const status = stringField(resource, "status");
1687
+ if (status) summary.status = status;
1688
+ const links = objectField(resource, "_links");
1689
+ const url = webURL(base, stringField(links, "webui"));
1690
+ if (url) summary.webUrl = url;
1691
+ const space = objectField(resource, "space");
1692
+ if (space.id !== void 0) {
1693
+ const spaceId = typeof space.id === "number" ? String(space.id) : stringField(space, "id");
1694
+ if (idPattern.test(spaceId)) summary.spaceId = spaceId;
1695
+ }
1696
+ const spaceKey = stringField(space, "key");
1697
+ if (spaceKeyPattern.test(spaceKey)) summary.spaceKey = spaceKey;
1698
+ const version = objectField(resource, "version");
1699
+ if (version.number !== void 0) summary.versionNumber = numberField(version, "number");
1700
+ const when = parseGoRFC3339(stringField(version, "when"));
1701
+ if (when) summary.lastModifiedAt = when.canonical;
1702
+ return summary;
1703
+ }
1704
+ function decodePage(resource, representation, format, maxCharacters) {
1705
+ const id = stringField(resource, "id"), title = stringField(resource, "title"), status = stringField(resource, "status"), spaceId = stringField(resource, "spaceId");
1706
+ if (!idPattern.test(id) || !title || !status || !idPattern.test(spaceId)) throw new TypeError("page identity is invalid");
1707
+ const versionRecord = objectField(resource, "version");
1708
+ const versionNumber = numberField(versionRecord, "number");
1709
+ if (versionNumber < 1) throw new TypeError("page version is invalid");
1710
+ const bodyRecord = objectField(resource, "body");
1711
+ const body = objectField(bodyRecord, representation);
1712
+ const rawBody = stringField(body, "value");
1713
+ const rendered = renderDocumentText(representation === "storage" ? parseStorageDocument(rawBody) : parseADFDocument(rawBody), format, maxCharacters);
1714
+ const page = {
1715
+ id,
1716
+ title,
1717
+ status,
1718
+ spaceId,
1719
+ createdAt: normalizedTime(stringField(resource, "createdAt")),
1720
+ version: { number: versionNumber, createdAt: normalizedTime(stringField(versionRecord, "createdAt")) },
1721
+ body: rendered.text,
1722
+ bodyFormat: format
1723
+ };
1724
+ const parentId = stringField(resource, "parentId");
1725
+ if (idPattern.test(parentId)) page.parentPageId = parentId;
1726
+ const authorId = stringField(resource, "authorId");
1727
+ if (authorId) page.authorAccountId = authorId;
1728
+ const versionAuthorId = stringField(versionRecord, "authorId");
1729
+ if (versionAuthorId) page.version.authorAccountId = versionAuthorId;
1730
+ if (versionRecord.minorEdit === true) page.version.isMinorEdit = true;
1731
+ if (rendered.isTruncated) page.isBodyTruncated = true;
1732
+ const links = objectField(resource, "_links");
1733
+ const url = webURL(stringField(links, "base"), stringField(links, "webui"));
1734
+ if (url) page.webUrl = url;
1735
+ return page;
1736
+ }
1737
+ function normalizedTime(value) {
1738
+ return parseGoRFC3339(value)?.canonical || emptyTime;
1739
+ }
1740
+ function buildCql(filter) {
1741
+ const clauses = ["type = page"];
1742
+ for (const [field, values, valid, description] of [
1743
+ ["space", filter.spaceKeys || [], spaceKeyPattern, "a space key such as OPS"],
1744
+ ["label", filter.labels || [], /^[^ \t\r\n,]+$/, "a label without whitespace"]
1745
+ ]) {
1746
+ if (values.length > 50) throw new TypeError(`filter accepts at most 50 ${field} values`);
1747
+ if (values.length) {
1748
+ const quoted = values.map((value) => {
1749
+ const trimmed = value.trim();
1750
+ if (!valid.test(trimmed) || field === "label" && [...trimmed].length > 255) throw new TypeError(`filter ${field} values must each be ${description}`);
1751
+ return quoteCqlString(trimmed);
1752
+ });
1753
+ clauses.push(`${field} in (${quoted.join(", ")})`);
1754
+ }
1755
+ }
1756
+ const phrase = (filter.titlePhrase || "").trim();
1757
+ if (phrase) clauses.push("title ~ " + quoteCqlString(quoteCqlString(phrase)));
1758
+ if (filter.modifiedSince) {
1759
+ const timestamp = parseGoRFC3339(filter.modifiedSince);
1760
+ if (!timestamp || filter.modifiedSince.startsWith("0001-01-01T00:00:00")) throw new TypeError("filter modifiedSince must be a time");
1761
+ clauses.push('lastmodified >= "' + new Date(timestamp.epochMs - 12 * 60 * 60 * 1e3).toISOString().slice(0, 10) + '"');
1762
+ }
1763
+ const additional = (filter.additionalCql || "").trim();
1764
+ if (additional) {
1765
+ validateAdditionalCql(additional);
1766
+ clauses.push(`(${additional})`);
1767
+ }
1768
+ const order = filter.order || "lastModifiedDescending";
1769
+ const suffix = order === "lastModifiedDescending" ? "ORDER BY lastmodified DESC" : order === "createdDescending" ? "ORDER BY created DESC" : order === "titleAscending" ? "ORDER BY title ASC" : "";
1770
+ if (!suffix) throw new TypeError("filter order must be lastModifiedDescending, createdDescending, or titleAscending");
1771
+ return clauses.join(" AND ") + " " + suffix;
1772
+ }
1773
+ function quoteCqlString(value) {
1774
+ if ([...value].length > 1024 || hasControlCharacter(value)) throw new TypeError("CQL value cannot contain control characters");
1775
+ return '"' + value.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + '"';
1776
+ }
1777
+ function hasControlCharacter(value) {
1778
+ return [...value].some((character) => {
1779
+ const code = character.codePointAt(0);
1780
+ return code < 32 || code === 127;
1781
+ });
1782
+ }
1783
+ function validateAdditionalCql(clause) {
1784
+ if ([...clause].length > 4096) throw new TypeError("filter additionalCql cannot exceed 4096 characters");
1785
+ let depth = 0, quote = "", escaped = false, unquoted = "";
1786
+ for (const character of clause) {
1787
+ if (hasControlCharacter(character)) throw new TypeError("filter additionalCql cannot contain control characters");
1788
+ if (escaped) escaped = false;
1789
+ else if (quote && character === "\\") escaped = true;
1790
+ else if (quote && character === quote) quote = "";
1791
+ else if (!quote && (character === '"' || character === "'")) quote = character;
1792
+ else if (!quote && character === "(") depth++;
1793
+ else if (!quote && character === ")") {
1794
+ if (--depth < 0) throw new TypeError("filter additionalCql closes a parenthesis it did not open");
1795
+ }
1796
+ unquoted += quote ? " " : character;
1797
+ }
1798
+ if (quote) throw new TypeError("filter additionalCql has an unterminated string");
1799
+ if (depth) throw new TypeError("filter additionalCql has an unclosed parenthesis");
1800
+ if (/\border\s+by\b/i.test(unquoted)) throw new TypeError("filter additionalCql cannot contain ORDER BY; use order instead");
1801
+ }
1802
+ function emptyResponse() {
1803
+ return { status: 0, headers: {}, body: new Uint8Array(), isTooLarge: false, isDispatched: false };
1804
+ }
1805
+ function validatePageResource(resource) {
1806
+ if (!idPattern.test(stringField(resource, "id"))) throw new TypeError("page ID is not numeric");
1807
+ if (!idPattern.test(stringField(resource, "spaceId"))) throw new TypeError("space ID is not numeric");
1808
+ const title = stringField(resource, "title");
1809
+ if (!title || [...title].length > 1020) throw new TypeError("page title is missing or invalid");
1810
+ if (numberField(objectField(resource, "version"), "number") < 1) throw new TypeError("page version is missing");
1811
+ }
1812
+ function validateTitle(value) {
1813
+ const title = value.trim();
1814
+ if (!title) throw new TypeError("title is required");
1815
+ if ([...title].length > 255) throw new TypeError("title cannot exceed 255 characters");
1816
+ if (hasControlCharacter(title)) throw new TypeError("title must be one line without control characters");
1817
+ return title;
1818
+ }
1819
+ function createdOutput(requested, resource, siteBase, isConfirmed) {
1820
+ const output = { ...requested, pageId: stringField(resource, "id"), spaceId: stringField(resource, "spaceId"), versionNumber: numberField(objectField(resource, "version"), "number") };
1821
+ delete output.parentPageId;
1822
+ const parent = stringField(resource, "parentId");
1823
+ if (idPattern.test(parent)) output.parentPageId = parent;
1824
+ const links = objectField(resource, "_links");
1825
+ const url = webURL(stringField(links, "base") || siteBase, stringField(links, "webui"));
1826
+ if (url) output.webUrl = url;
1827
+ if (isConfirmed) output.isConfirmedByTitleLookup = true;
1828
+ return output;
1829
+ }
1830
+ function updatedOutput(requested, resource, siteBase, isConfirmed) {
1831
+ const output = { ...requested, versionNumber: numberField(objectField(resource, "version"), "number") };
1832
+ const links = objectField(resource, "_links");
1833
+ const url = webURL(stringField(links, "base") || siteBase, stringField(links, "webui"));
1834
+ if (url) output.webUrl = url;
1835
+ if (isConfirmed) output.isConfirmedByReadBack = true;
1836
+ return output;
1837
+ }
1838
+ function addedCommentOutput(requested, comment, isConfirmed) {
1839
+ const output = { ...requested, commentId: stringField(comment, "id") };
1840
+ const timestamp = stringField(objectField(comment, "version"), "createdAt");
1841
+ if (parseGoRFC3339(timestamp)) output.createdAt = normalizedTime(timestamp);
1842
+ if (isConfirmed) output.isConfirmedByReadBack = true;
1843
+ return output;
1844
+ }
1845
+ function storageComparisonText(storage) {
1846
+ try {
1847
+ return documentComparisonText(parseStorageDocument(storage));
1848
+ } catch {
1849
+ return "";
1850
+ }
1851
+ }
1852
+ function earliestDispatchTime(call, now) {
1853
+ const first = call.context.firstAttemptAt.getTime();
1854
+ return first > 0 ? Math.min(now.getTime(), first) : now.getTime();
1855
+ }
1856
+ function readDispatchCheckpoint(call) {
1857
+ if (!call.context.hasLastHeartbeatValue()) return void 0;
1858
+ try {
1859
+ const value = call.context.getLastHeartbeatValue();
1860
+ if (value && typeof value === "object" && "dispatchedAtUnixMilli" in value && typeof value.dispatchedAtUnixMilli === "number" && value.dispatchedAtUnixMilli > 0) return { dispatchedAt: value.dispatchedAtUnixMilli };
1861
+ } catch {
1862
+ }
1863
+ return { dispatchedAt: 0 };
1864
+ }
1865
+ function clearDispatchCheckpoint(call) {
1866
+ void call.context.recordHeartbeat(void 0).catch(() => {
1867
+ });
1868
+ }
1869
+ async function findPageByTitle(client, session, operation, spaceId, title) {
1870
+ const response = await client.exchange(session, "GET", "content", "/pages", { "space-id": spaceId, title, "body-format": "storage", limit: "5" });
1871
+ let classification = client.classifyRead(operation, "page lookup", response);
1872
+ const lookup = { classification, response, siteBase: "" };
1873
+ if (classification.outcome !== "accepted") return lookup;
1874
+ try {
1875
+ const list = decodeObject(response);
1876
+ const results = list.results;
1877
+ if (!Array.isArray(results) || results.length > 5) throw new TypeError("invalid page list");
1878
+ lookup.siteBase = stringField(objectField(list, "_links"), "base");
1879
+ for (const value of results) {
1880
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("invalid page");
1881
+ const page = value;
1882
+ validatePageResource(page);
1883
+ if (stringField(page, "title") === title && stringField(page, "spaceId") === spaceId) {
1884
+ lookup.page = page;
1885
+ break;
1886
+ }
1887
+ }
1888
+ } catch {
1889
+ classification = { outcome: "invalid", failure: confluenceFailure(operation, "PROTOCOL", "Confluence returned an invalid page list"), retryAfterMs: 0 };
1890
+ lookup.classification = classification;
1891
+ }
1892
+ return lookup;
1893
+ }
1894
+ async function readPage(client, session, operation, pageId) {
1895
+ const response = await client.exchange(session, "GET", "content", `/pages/${pathEscape(pageId)}`, { "body-format": "storage" });
1896
+ const lookup = { classification: client.classifyRead(operation, "page", response), response, siteBase: "" };
1897
+ if (lookup.classification.outcome !== "accepted") return lookup;
1898
+ try {
1899
+ const page = decodeObject(response);
1900
+ validatePageResource(page);
1901
+ lookup.page = page;
1902
+ lookup.siteBase = stringField(objectField(page, "_links"), "base");
1903
+ } catch {
1904
+ lookup.classification = { outcome: "invalid", failure: confluenceFailure(operation, "PROTOCOL", "Confluence returned an invalid page"), retryAfterMs: 0 };
1905
+ }
1906
+ return lookup;
1907
+ }
1908
+ async function resolveSpaceId(client, session, operation, spaceKey) {
1909
+ const response = await client.exchange(session, "GET", "content", "/spaces", { keys: spaceKey, limit: "1" });
1910
+ const classification = client.classifyRead(operation, "space", response);
1911
+ if (classification.outcome !== "accepted") return { classification };
1912
+ try {
1913
+ const results = decodeObject(response).results;
1914
+ if (!Array.isArray(results)) throw new TypeError();
1915
+ for (const value of results) {
1916
+ if (!value || typeof value !== "object" || Array.isArray(value)) continue;
1917
+ const resource = value, id = stringField(resource, "id");
1918
+ if (stringField(resource, "key").toLowerCase() === spaceKey.toLowerCase() && idPattern.test(id)) return { spaceId: id };
1919
+ }
1920
+ } catch {
1921
+ return { classification: { outcome: "invalid", failure: confluenceFailure(operation, "PROTOCOL", "Confluence returned an invalid space list"), retryAfterMs: 0 } };
1922
+ }
1923
+ return { classification: { outcome: "notFound", failure: confluenceFailure(operation, "NOT_FOUND", `Confluence space ${spaceKey} was not found or is not visible to the connection`), retryAfterMs: 0 } };
1924
+ }
1925
+
1926
+ // src/client.ts
1927
+ var defaultEndpoint = "https://api.atlassian.com";
1928
+ var cloudIdPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1929
+ var confluenceScopes = /confluence/;
1930
+ var encoder = new TextEncoder();
1931
+ var defaultPollIntervalMs = 6e4;
1932
+ var minimumPollIntervalMs = 1e4;
1933
+ var ConfluenceClient = class {
1934
+ /** Validate connection settings and bind the host credential source. */
1935
+ constructor(config, credentials, options = {}) {
1936
+ this.credentials = credentials;
1937
+ if (!credentials) throw new TypeError("Confluence credential provider is required");
1938
+ this.endpoint = validateBaseURL(config.endpoint || defaultEndpoint);
1939
+ this.configuredCloudId = (config.cloudId || "").trim().toLowerCase();
1940
+ if (this.configuredCloudId && !cloudIdPattern.test(this.configuredCloudId)) throw new TypeError("Confluence cloudId must be a site UUID");
1941
+ this.maxResponseBytes = config.maxResponseBytes || 8388608;
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;
1946
+ this.send = options.send ?? sendProviderRequest;
1947
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
1948
+ }
1949
+ credentials;
1950
+ endpoint;
1951
+ configuredCloudId;
1952
+ maxResponseBytes;
1953
+ /** Delay between pageChanged polls, in milliseconds. */
1954
+ pollIntervalMs;
1955
+ /** Receives pageChanged Trigger records; undefined uses the SDK default logger. */
1956
+ triggerLogger;
1957
+ now;
1958
+ send;
1959
+ refreshDriver = new ManifestCredentialRefreshDriver({ providerName: "Atlassian", auth: Authorization, credentialFields: CredentialFields });
1960
+ resolvedCloudId = "";
1961
+ /** Bind the page search Query. */
1962
+ searchPages() {
1963
+ return new SearchPagesOperation(this);
1964
+ }
1965
+ /** Bind the page read Query. */
1966
+ getPage() {
1967
+ return new GetPageOperation(this);
1968
+ }
1969
+ /** Bind the page create Mutation. */
1970
+ createPage() {
1971
+ return new CreatePageOperation(this);
1972
+ }
1973
+ /** Bind the page update Mutation. */
1974
+ updatePage() {
1975
+ return new UpdatePageOperation(this);
1976
+ }
1977
+ /** Bind the footer comment Mutation. */
1978
+ addComment() {
1979
+ return new AddCommentOperation(this);
1980
+ }
1981
+ /** Report that the next session sends the accessible-resources request. */
1982
+ needsSiteLookup() {
1983
+ return !this.configuredCloudId && !this.resolvedCloudId;
1984
+ }
1985
+ /** Resolve the OAuth token and the single selected Confluence Cloud site. */
1986
+ async startSession(call, operation) {
1987
+ let credentials;
1988
+ try {
1989
+ credentials = await resolveCredential(this.credentials, call, this.refreshDriver, call.context.cancellationSignal);
1990
+ const token = credentials.accessToken.reveal();
1991
+ if (!isHeaderSafeCredential(token)) throw new TypeError("invalid access token");
1992
+ } catch {
1993
+ return { error: { failure: confluenceFailure(operation, "AUTHENTICATION", "Confluence connection credentials are unavailable; reconnect the connection"), isRetryable: false, retryAfterMs: 0 } };
1994
+ }
1995
+ const session = { call, cloudId: this.configuredCloudId || this.resolvedCloudId, token: credentials.accessToken.reveal() };
1996
+ if (session.cloudId) return { session };
1997
+ const response = await this.exchange(session, "GET", "gateway", "/oauth/token/accessible-resources");
1998
+ if (response.error) return { error: { failure: confluenceFailure(operation, "TRANSPORT", "Atlassian accessible resources are temporarily unavailable"), isRetryable: true, retryAfterMs: 0 } };
1999
+ if (response.status === 429) return { error: { failure: confluenceFailure(operation, "RATE_LIMIT", "Atlassian rate limited the accessible resources lookup"), isRetryable: true, retryAfterMs: this.retryAfter(response) } };
2000
+ if (response.status === 408 || response.status >= 500) return { error: { failure: confluenceFailure(operation, "AVAILABILITY", "Atlassian accessible resources are temporarily unavailable"), isRetryable: true, retryAfterMs: 0 } };
2001
+ if (response.status < 200 || response.status >= 300) return { error: { failure: confluenceFailure(operation, statusFailureKind(response.status), `Atlassian rejected the accessible resources lookup with HTTP ${response.status}; reconnect the connection or set cloudId`), isRetryable: false, retryAfterMs: 0 } };
2002
+ let sites;
2003
+ try {
2004
+ const resources = JSON.parse(new TextDecoder().decode(response.body), (key, value, context) => {
2005
+ if (typeof value === "number" && ["number", "size", "total", "start", "limit"].includes(key) && !/^-?\d+$/.test(context?.source ?? "")) throw new TypeError("invalid Confluence integer");
2006
+ return value;
2007
+ });
2008
+ if (!Array.isArray(resources)) throw new TypeError();
2009
+ sites = [...new Set(resources.filter((resource) => resource && typeof resource === "object" && typeof resource.id === "string" && Array.isArray(resource.scopes) && resource.scopes.some((scope) => typeof scope === "string" && confluenceScopes.test(scope))).map((resource) => resource.id.toLowerCase()).filter((id) => cloudIdPattern.test(id)))].sort();
2010
+ } catch {
2011
+ return { error: { failure: confluenceFailure(operation, "PROTOCOL", "Atlassian returned an invalid accessible resources list; set cloudId"), isRetryable: false, retryAfterMs: 0 } };
2012
+ }
2013
+ if (!sites.length) return { error: { failure: confluenceFailure(operation, "AUTHORIZATION", "the authorization grants no Confluence site; reconnect and pick a Confluence site on the consent screen"), isRetryable: false, retryAfterMs: 0 } };
2014
+ if (sites.length !== 1) return { error: { failure: confluenceFailure(operation, "VALIDATION", `the authorization grants ${sites.length} Confluence sites; choose one with the Confluence site picker or set cloudId`), isRetryable: false, retryAfterMs: 0 } };
2015
+ session.cloudId = sites[0];
2016
+ this.resolvedCloudId = session.cloudId;
2017
+ return { session };
2018
+ }
2019
+ /** Exchange one request and refresh a rejected credential once. */
2020
+ async exchange(session, method, api, path, query, payload) {
2021
+ const prefix = api === "gateway" ? "" : `/ex/confluence/${session.cloudId}/wiki/${api === "content" ? "api/v2" : "rest/api"}`;
2022
+ const search = query ? "?" + encodeGoQuery(query) : "";
2023
+ const url = this.endpoint + prefix + path + search;
2024
+ let body;
2025
+ try {
2026
+ if (payload !== void 0) body = encoder.encode(JSON.stringify(payload));
2027
+ } catch {
2028
+ return { status: 0, headers: {}, body: new Uint8Array(), isTooLarge: false, isDispatched: false, error: "request" };
2029
+ }
2030
+ for (let attempt = 0; attempt < 2; attempt++) {
2031
+ let response;
2032
+ const request = {
2033
+ url,
2034
+ method,
2035
+ headers: { Authorization: `Bearer ${session.token}`, Accept: "application/json", ...body ? { "Content-Type": "application/json" } : {} },
2036
+ ...body ? { body } : {},
2037
+ maxResponseBytes: this.maxResponseBytes,
2038
+ timeoutMs: 2e4,
2039
+ addressPolicy: this.endpoint === defaultEndpoint ? "publicHTTPS" : "privateNetworkHTTP",
2040
+ signal: session.call.context.cancellationSignal
2041
+ };
2042
+ try {
2043
+ const received = await this.send(request);
2044
+ response = {
2045
+ ...received,
2046
+ isTooLarge: false,
2047
+ isDispatched: true,
2048
+ reflectsSecret: Buffer.from(received.body).includes(Buffer.from(session.token))
2049
+ };
2050
+ } catch (error) {
2051
+ if (error instanceof BodyTooLargeError && error.status !== void 0 && error.headers !== void 0) response = { status: error.status, headers: error.headers, body: new Uint8Array(), isTooLarge: true, isDispatched: true };
2052
+ else return { status: 0, headers: {}, body: new Uint8Array(), isTooLarge: false, isDispatched: !(error instanceof ProviderTransportError && error.isProvablyNotSent), error: "transport" };
2053
+ }
2054
+ if (response.status !== 401 || attempt === 1 || !("resolveAfterRejection" in this.credentials)) return response;
2055
+ try {
2056
+ const replacement = await resolveCredentialAfterRejection(this.credentials, session.call, this.refreshDriver, session.call.context.cancellationSignal);
2057
+ session.token = replacement.accessToken.reveal();
2058
+ if (!isHeaderSafeCredential(session.token)) return response;
2059
+ } catch {
2060
+ return response;
2061
+ }
2062
+ }
2063
+ throw new Error("Confluence credential rejection retry exhausted");
2064
+ }
2065
+ /** Classify a read without inspecting an error response body. */
2066
+ classifyRead(operation, subject, response) {
2067
+ if (response.error === "request") return classified("defect", confluenceFailure(operation, "LOCAL_DEFECT", "Confluence request could not be built"));
2068
+ if (response.error) return classified("retry", confluenceFailure(operation, "TRANSPORT", `Confluence ${subject} is temporarily unavailable`));
2069
+ if (response.status === 404) return classified("notFound", confluenceFailure(operation, "NOT_FOUND", `Confluence ${subject} was not found or is not visible to the connection`));
2070
+ if (response.status === 429) return classified("retry", confluenceFailure(operation, "RATE_LIMIT", `Confluence rate limited the ${subject}`), this.retryAfter(response));
2071
+ if (response.status === 408 || response.status >= 500) return classified("retry", confluenceFailure(operation, "AVAILABILITY", `Confluence ${subject} is temporarily unavailable`), this.retryAfter(response));
2072
+ if (response.status >= 400 && response.status < 500) return classified("rejected", confluenceFailure(operation, statusFailureKind(response.status), `Confluence rejected the ${subject} with HTTP ${response.status}`));
2073
+ if (response.status < 200 || response.status >= 300) return classified("invalid", confluenceFailure(operation, "PROTOCOL", `Confluence returned unexpected HTTP ${response.status} for the ${subject}`));
2074
+ if (response.isTooLarge) return classified("invalid", confluenceFailure(operation, "RESPONSE_TOO_LARGE", `Confluence ${subject} response exceeds the configured size limit`));
2075
+ if (response.reflectsSecret) return classified("invalid", confluenceFailure(operation, "PROTOCOL", `Confluence ${subject} response contains credential material`));
2076
+ return classified("accepted");
2077
+ }
2078
+ /** Classify a write before any read-back or business reconciliation. */
2079
+ classifyWrite(operation, subject, response) {
2080
+ if (response.error === "request") return classified("defect", confluenceFailure(operation, "LOCAL_DEFECT", "Confluence request could not be built"));
2081
+ if (response.error && !response.isDispatched) return classified("notApplied", confluenceFailure(operation, "TRANSPORT", `Confluence could not be reached, so no ${subject} was written`));
2082
+ if (response.error) return classified("ambiguous", confluenceFailure(operation, "TRANSPORT", `Confluence ${subject} outcome is unknown`));
2083
+ if (response.status >= 200 && response.status < 300) {
2084
+ if (response.isTooLarge) return classified("ambiguous", confluenceFailure(operation, "RESPONSE_TOO_LARGE", `Confluence accepted the ${subject} but its response exceeds the configured size limit`));
2085
+ if (response.reflectsSecret) return classified("ambiguous", confluenceFailure(operation, "PROTOCOL", `Confluence accepted the ${subject} but its response contains credential material`));
2086
+ return classified("accepted");
2087
+ }
2088
+ if (response.status === 429) return classified("notApplied", confluenceFailure(operation, "RATE_LIMIT", `Confluence rate limited the ${subject} before writing it`), this.retryAfter(response));
2089
+ if (response.status === 404) return classified("notFound", confluenceFailure(operation, "NOT_FOUND", `Confluence rejected the ${subject} with HTTP 404`));
2090
+ if (response.status >= 400 && response.status < 500 && response.status !== 408) return classified("rejected", confluenceFailure(operation, statusFailureKind(response.status), `Confluence rejected the ${subject} with HTTP ${response.status}`));
2091
+ return classified("ambiguous", confluenceFailure(operation, "AVAILABILITY", `Confluence ${subject} outcome is unknown after HTTP ${response.status}`), this.retryAfter(response));
2092
+ }
2093
+ /** Produce a safe request receipt with the exact provider object identifier. */
2094
+ receipt(session, response, objectId = "") {
2095
+ const traceId = response.headers["atl-traceid"];
2096
+ const safeTrace = typeof traceId === "string" && /^[\x21-\x7e]{1,128}$/.test(traceId) ? traceId : "";
2097
+ return {
2098
+ callId: session.call.id,
2099
+ provider: "confluence",
2100
+ observedAt: this.now().toISOString(),
2101
+ ...session.call.idempotencyKey ? { idempotencyKey: session.call.idempotencyKey } : {},
2102
+ ...objectId ? { providerObjectId: objectId } : {},
2103
+ ...safeTrace ? { providerRequestId: safeTrace } : {}
2104
+ };
2105
+ }
2106
+ /** Parse Retry-After against the injected clock. */
2107
+ retryAfter(response) {
2108
+ const header = response.headers["retry-after"];
2109
+ return parseRetryAfter(typeof header === "string" ? header : "", this.now());
2110
+ }
2111
+ };
2112
+ function classified(outcome, failure, retryAfterMs = 0) {
2113
+ return { outcome, ...failure ? { failure } : {}, retryAfterMs };
2114
+ }
2115
+ function confluenceFailure(operation, kind, message) {
2116
+ return { provider: "confluence", operation, kind, message };
2117
+ }
2118
+ function statusFailureKind(status) {
2119
+ return status === 400 ? "VALIDATION" : status === 401 ? "AUTHENTICATION" : status === 403 ? "AUTHORIZATION" : status === 404 ? "NOT_FOUND" : status === 409 ? "CONFLICT" : status === 429 ? "RATE_LIMIT" : "PROVIDER_REJECTION";
2120
+ }
2121
+ function queryEscape(value) {
2122
+ return encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g, "+");
2123
+ }
2124
+ function decodeObject(response) {
2125
+ const decoded = JSON.parse(new TextDecoder().decode(response.body), (key, value, context) => {
2126
+ if (typeof value === "number" && ["number", "size", "total", "start", "limit"].includes(key) && !/^-?\d+$/.test(context?.source ?? "")) throw new TypeError("invalid Confluence integer");
2127
+ return value;
2128
+ });
2129
+ if (!decoded || typeof decoded !== "object" || Array.isArray(decoded)) throw new TypeError("invalid response object");
2130
+ return decoded;
2131
+ }
2132
+ function pathEscape(value) {
2133
+ return encodeURIComponent(value).replace(/[!'()*]/g, (character) => "%" + character.charCodeAt(0).toString(16).toUpperCase()).replace(/%24/g, "$").replace(/%26/g, "&").replace(/%2B/g, "+").replace(/%3D/g, "=").replace(/%3A/g, ":").replace(/%40/g, "@");
2134
+ }
2135
+ function encodeGoQuery(values) {
2136
+ return Object.keys(values).sort((left, right) => Buffer.compare(Buffer.from(left), Buffer.from(right))).flatMap((key) => (Array.isArray(values[key]) ? values[key] : [values[key]]).map((value) => `${queryEscape(key)}=${queryEscape(value)}`)).join("&");
2137
+ }
2138
+
2139
+ // src/project.ts
2140
+ function encodeCredentials(credentials) {
2141
+ return {
2142
+ oauth_client_id: credentials.oauthClientId,
2143
+ oauth_client_secret: credentials.oauthClientSecret.reveal(),
2144
+ access_token: credentials.accessToken.reveal(),
2145
+ refresh_token: credentials.refreshToken.reveal()
2146
+ };
2147
+ }
2148
+ function newProjectConnection2(project, connectionName, options = {}) {
2149
+ return newProjectConnection(project, connectionName, (loadedProject, name) => {
2150
+ const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "confluence" && entry.connectionName === name);
2151
+ if (!selected) throw new TypeError("Confluence project connection is not configured");
2152
+ const { pollInterval, ...raw } = selected.configuration;
2153
+ const settings = ConfigSchema.parse({ ...raw, ...pollInterval !== void 0 ? { pollIntervalMs: pollIntervalMilliseconds(pollInterval) } : {} });
2154
+ const config = {
2155
+ ...settings.cloudId !== void 0 ? { cloudId: settings.cloudId } : {},
2156
+ ...settings.endpoint !== void 0 ? { endpoint: settings.endpoint } : {},
2157
+ ...settings.maxResponseBytes !== void 0 ? { maxResponseBytes: settings.maxResponseBytes } : {},
2158
+ ...settings.pollIntervalMs !== void 0 ? { pollIntervalMs: settings.pollIntervalMs } : {}
2159
+ };
2160
+ return new ConfluenceClient(config, newProjectCredentialProvider(loadedProject, name, decodeCredentials, encodeCredentials, decodeSharedCredentials), options);
2161
+ });
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
+ }
2793
+ export {
2794
+ AddCommentBranch,
2795
+ AddCommentBranchAdded,
2796
+ AddCommentBranchDefect,
2797
+ AddCommentBranchNotFound,
2798
+ AddCommentBranchProviderRejected,
2799
+ AddCommentBranchUncertain,
2800
+ AddCommentDefinition,
2801
+ AddCommentInputSchema,
2802
+ AddCommentMetadata,
2803
+ AddCommentOperation,
2804
+ AddCommentOutputSchema,
2805
+ ConfigSchema,
2806
+ ConfluenceClient,
2807
+ Connection,
2808
+ ConnectorID,
2809
+ CreatePageBranch,
2810
+ CreatePageBranchCreated,
2811
+ CreatePageBranchDefect,
2812
+ CreatePageBranchNotFound,
2813
+ CreatePageBranchProviderRejected,
2814
+ CreatePageBranchTitleConflict,
2815
+ CreatePageDefinition,
2816
+ CreatePageInputSchema,
2817
+ CreatePageMetadata,
2818
+ CreatePageOperation,
2819
+ CreatePageOutputSchema,
2820
+ GetPageBranch,
2821
+ GetPageBranchDefect,
2822
+ GetPageBranchFound,
2823
+ GetPageBranchInvalidResponse,
2824
+ GetPageBranchNotFound,
2825
+ GetPageBranchProviderRejected,
2826
+ GetPageDefinition,
2827
+ GetPageInputSchema,
2828
+ GetPageMetadata,
2829
+ GetPageOperation,
2830
+ PageChangeCreated,
2831
+ PageChangeUpdated,
2832
+ PageChangedEventSchema,
2833
+ PageChangedTriggerConfigurationSchema,
2834
+ PageChangedTriggerDefinition,
2835
+ PageSchema,
2836
+ PageSearchFilterSchema,
2837
+ PageSummarySchema,
2838
+ PageTriggerRunner,
2839
+ PageVersionSchema,
2840
+ ProviderID,
2841
+ SearchPagesBranch,
2842
+ SearchPagesBranchDefect,
2843
+ SearchPagesBranchInvalidResponse,
2844
+ SearchPagesBranchProviderRejected,
2845
+ SearchPagesBranchSearched,
2846
+ SearchPagesDefinition,
2847
+ SearchPagesInputSchema,
2848
+ SearchPagesMetadata,
2849
+ SearchPagesOperation,
2850
+ SearchPagesOutputSchema,
2851
+ UISpacePickerPortSpaceID,
2852
+ UISpacePickerPortSpaceKey,
2853
+ UISpacePickerPortSpaceName,
2854
+ UIUnitSpacePicker,
2855
+ UpdatePageBranch,
2856
+ UpdatePageBranchDefect,
2857
+ UpdatePageBranchNotFound,
2858
+ UpdatePageBranchProviderRejected,
2859
+ UpdatePageBranchUpdated,
2860
+ UpdatePageBranchVersionConflict,
2861
+ UpdatePageDefinition,
2862
+ UpdatePageInputSchema,
2863
+ UpdatePageMetadata,
2864
+ UpdatePageOperation,
2865
+ UpdatePageOutputSchema,
2866
+ decodeCredentials,
2867
+ decodePageChangedEventPayload,
2868
+ decodeSharedCredentials,
2869
+ definePageChangedTriggerBinding,
2870
+ newAddCommentStep,
2871
+ newConnection,
2872
+ newConnectionWithOperations,
2873
+ newCreatePageStep,
2874
+ newGetPageStep,
2875
+ newPageChangedTrigger,
2876
+ newPageTriggerRunner,
2877
+ newProjectConnection2 as newProjectConnection,
2878
+ newProjectPageTriggerRunner,
2879
+ newSearchPagesStep,
2880
+ newUpdatePageStep,
2881
+ pageChangeEventId
2882
+ };