@artifactshare/cli 0.16.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,13 +2,14 @@
2
2
  import { C as defaultPreviewNotificationRegistration, D as isPreviewAnchor, O as isPreviewAnnotation, S as createPreviewNotificationCoordinator, T as PREVIEW_MUTATION_HEADER, _ as resolveLiveSession, a as annotationsFilePath, b as updateSessionNotificationRegistration, c as isSessionId, d as previewsDir, f as probeSession, g as removeSessionFile, h as releaseStaleClaim, i as cursorNotificationRegistration, k as isPreviewDoneItemInput, l as previewIdentityPath, m as readSessionFile, n as CURSOR_ACP_NOTIFICATION_TIMEOUT_MS, o as claimSessionStart, p as processAlive, r as createCursorAcpAdapter, s as isConnectionRefused, u as previewRealpath, v as sessionIdForPath, w as samePreviewNotificationRegistration, x as writeSessionFile, y as tokenFingerprint } from "./cursor-notification-Hz6fuACK.js";
3
3
  import { cli, define, lazy } from "gunshi";
4
4
  import { generate } from "gunshi/generator";
5
- import { chmodSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, statSync, watch, writeFileSync } from "node:fs";
5
+ import { chmodSync, constants, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, statSync, watch, writeFileSync } from "node:fs";
6
6
  import { pathToFileURL } from "node:url";
7
7
  import { z } from "zod";
8
8
  import { execFile, spawn } from "node:child_process";
9
- import { appendFile, chmod, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
9
+ import * as fs from "node:fs/promises";
10
+ import { chmod, lstat, mkdir, readFile, realpath, rm, rmdir, stat, writeFile } from "node:fs/promises";
10
11
  import { arch, homedir, platform } from "node:os";
11
- import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
12
+ import path, { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
12
13
  import { createHash, randomUUID } from "node:crypto";
13
14
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
14
15
  import { Blob, Buffer as Buffer$1 } from "node:buffer";
@@ -18,6 +19,9 @@ import { promisify } from "node:util";
18
19
  //#region ../contract/dist/index.js
19
20
  const CLI_DEVICE_CLIENT_ID = "artifactshare-cli";
20
21
  const stringId = z.string().min(1);
22
+ const artifactIdPattern = /^[a-z0-9]{10}$/;
23
+ const ArtifactIdSchema = z.string().regex(artifactIdPattern);
24
+ const isArtifactId = (value) => typeof value === "string" && artifactIdPattern.test(value);
21
25
  const timestamp = z.string().min(1);
22
26
  const url = z.string().url();
23
27
  const nullableTimestamp = timestamp.nullable();
@@ -400,7 +404,7 @@ const DownloadManifestFileSchema = z.object({
400
404
  sha256: z.string()
401
405
  });
402
406
  const DownloadManifestResponseSchema = z.object({
403
- id: stringId,
407
+ id: ArtifactIdSchema,
404
408
  share_url: url,
405
409
  version_id: stringId,
406
410
  artifact_kind: UploadArtifactKindSchema,
@@ -409,7 +413,7 @@ const DownloadManifestResponseSchema = z.object({
409
413
  project_id: stringId.nullable().optional()
410
414
  });
411
415
  const ArtifactsListEntrySchema = z.object({
412
- id: stringId,
416
+ id: ArtifactIdSchema,
413
417
  title: z.string(),
414
418
  share_url: url,
415
419
  visibility: VisibilitySchema,
@@ -1676,6 +1680,16 @@ function resolveArtifactId(input) {
1676
1680
  } catch {
1677
1681
  return null;
1678
1682
  }
1683
+ const contentHostMatch = url.hostname.match(/^[al]-([a-z0-9]{10})--v-((?:[a-f0-9]{2})+)\.(?:artifactshareusercontent\.com|usercontent\.localhost)$/);
1684
+ const artifactId = contentHostMatch?.[1];
1685
+ const encodedVersion = contentHostMatch?.[2];
1686
+ if (artifactId && encodedVersion && url.hostname.indexOf(".") <= 63) try {
1687
+ const bytes = Uint8Array.from(encodedVersion.match(/../g), (byte) => Number.parseInt(byte, 16));
1688
+ const version = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
1689
+ if (version && Buffer.from(version).toString("hex") === encodedVersion) return artifactId;
1690
+ } catch {
1691
+ return null;
1692
+ }
1679
1693
  const linkHostMatch = url.hostname.match(/^([A-Za-z0-9]{10})(?:--v-[a-f0-9]+)?\.artifactshare\.link$/);
1680
1694
  if (linkHostMatch?.[1]) return linkHostMatch[1];
1681
1695
  const sandboxMatch = url.hostname.match(/^([A-Za-z0-9]+)(?:--v-[a-f0-9]+)?\.sandbox\./);
@@ -1705,7 +1719,7 @@ function targetResolutionError(input, command) {
1705
1719
  code: "target_not_found",
1706
1720
  message: "Artifact target could not be resolved.",
1707
1721
  why: `${TARGET_COMMAND_LABELS[command]} only accepts an artifact ID, share URL, or sandbox URL.`,
1708
- hint: "Retry with an artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL. If you only have a title, resolve it to an ID first.",
1722
+ hint: "Retry with an artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL. If you only have a title, resolve it to an ID first.",
1709
1723
  agentRecoverable: true,
1710
1724
  requiresHuman: false,
1711
1725
  recovery: { kind: "change_input" },
@@ -1976,6 +1990,10 @@ function humanSuccess(command, data) {
1976
1990
  const withWarnings = warnings.length ? `${output}${warnings.map((message) => `Warning: ${message}`).join("\n")}\n` : output;
1977
1991
  return suffix ? `${withWarnings}${suffix}` : withWarnings;
1978
1992
  }
1993
+ if (command === "download" && isRecord$1(data) && Array.isArray(data.backup_paths)) {
1994
+ const recovery = data.backup_paths.map((path) => `Original data retained at ${String(path)}; inspect it before manual cleanup.`).join("\n");
1995
+ return `${JSON.stringify(data, null, 2)}\n${recovery ? `${recovery}\n` : ""}`;
1996
+ }
1979
1997
  if (command === "doctor") return doctorHumanOutput(data);
1980
1998
  if (command === "open") return openHumanOutput(data);
1981
1999
  if (command === "init") return initHumanOutput(data);
@@ -2570,9 +2588,6 @@ async function resolveDefaultVisibility(key, repositoryConfig) {
2570
2588
  async function readProjectConfigAtDirectory(directory, kind) {
2571
2589
  return await readJsonFile(join(directory, kind === "local" ? PROJECT_CONFIG_LOCAL_PATH : PROJECT_CONFIG_PATH));
2572
2590
  }
2573
- async function readRawLocalProjectConfig(cwd = process.cwd()) {
2574
- return await readJsonFile(projectConfigLocalPath(cwd));
2575
- }
2576
2591
  function configString(value) {
2577
2592
  return nonEmpty(typeof value === "string" ? value : void 0) ?? null;
2578
2593
  }
@@ -5053,6 +5068,17 @@ function createPreviewStore(annotationsPath) {
5053
5068
  };
5054
5069
  }
5055
5070
  //#endregion
5071
+ //#region src/preview/request-origin.ts
5072
+ /** Browser mutations must come from the serving shell/dialog, never an
5073
+ * opaque artifact frame. CORS controls response access, not server effects.
5074
+ * CLI clients omit Origin; this guard does not authenticate local clients. */
5075
+ function mutationOriginAllowed(origin, host, fetchSite) {
5076
+ if (fetchSite !== void 0 && typeof fetchSite !== "string") return false;
5077
+ if (fetchSite === "cross-site" || fetchSite === "same-site") return false;
5078
+ if (origin === "null") return fetchSite === "same-origin";
5079
+ return origin === void 0 || host !== void 0 && origin === `http://${host}`;
5080
+ }
5081
+ //#endregion
5056
5082
  //#region src/command-runners/projects.ts
5057
5083
  async function fetchProjects(token, options, init, errorOptions = {}) {
5058
5084
  const result = await apiGet("/api/cli/projects", token, options, init, errorOptions);
@@ -5277,6 +5303,7 @@ async function postShareUpload(args, baseUrl, fallbackKind) {
5277
5303
  //#region src/preview/messages.generated.ts
5278
5304
  const PREVIEW_MESSAGES = {
5279
5305
  en: {
5306
+ "preview.isolationNotice": "Preview runs scripts in an isolated frame. localStorage, IndexedDB and other same-origin features are unavailable. Preview isolation cannot be disabled.",
5280
5307
  "preview.localBadge": "Local preview",
5281
5308
  "preview.watching": "Watching for changes",
5282
5309
  "preview.share": "Share",
@@ -5365,6 +5392,7 @@ const PREVIEW_MESSAGES = {
5365
5392
  "preview.shareDialog.snapshotFailed": "The file could not be read, so sharing is disabled. Reopen this dialog once it is available."
5366
5393
  },
5367
5394
  ja: {
5395
+ "preview.isolationNotice": "プレビューのスクリプトは隔離されたフレームで実行されます。localStorage、IndexedDB など、同一オリジンを必要とする機能は使えません。この隔離は解除できません。",
5368
5396
  "preview.localBadge": "ローカルプレビュー",
5369
5397
  "preview.watching": "変更を監視中",
5370
5398
  "preview.share": "共有する",
@@ -5477,6 +5505,7 @@ function createShareDialogHandler(options) {
5477
5505
  if (route === "GET /api/context") return await handleContext(options, response);
5478
5506
  if (route === "GET /api/auth-status") return await handleAuthStatus(url, response);
5479
5507
  if (request.method === "POST") {
5508
+ if (!mutationOriginAllowed(request.headers.origin, request.headers.host, request.headers["sec-fetch-site"])) return sendJson$1(response, 403, { error: "forbidden_origin" });
5480
5509
  if (!mutationHeadersValid$1(request)) return sendJson$1(response, 403, { error: "forbidden" });
5481
5510
  const body = await readBody(request);
5482
5511
  if (body === null) return sendJson$1(response, 413, { error: "body_too_large" });
@@ -6289,7 +6318,7 @@ function pickShareMessages(locale) {
6289
6318
  }
6290
6319
  //#endregion
6291
6320
  //#region ../viewer-kit/src/reporter.generated.ts
6292
- const VIOLATION_REPORTER_SCRIPT_BODY = "(function() {\n\n\"use strict\";\n const VIOLATION_REPORTER_MARKER = \"securitypolicyviolation\";\n const READY_MESSAGE_REPEAT_COUNT = 20;\n const READY_MESSAGE_REPEAT_INTERVAL_MS = 100;\n const READY_CHECK_MESSAGE_SOURCE = \"artifactshare-parent\";\n const READY_CHECK_MESSAGE_KIND = \"ready-check\";\n\n const ANCHOR_IGNORE_ATTRIBUTE = \"data-anchor-ignore\";\n const COMMENT_UI_ATTRIBUTE = \"data-comment-ui\";\n const EXCLUSION_CLASS_ATTRIBUTE = \"class\";\n const HIGHLIGHT_STYLE_ID = \"ash-comment-highlight-style\";\n const TEXT_ANCHOR_EXCLUDED_SELECTOR = \"script,style,noscript,template,textarea,select,[\" + ANCHOR_IGNORE_ATTRIBUTE + \"],[\" + COMMENT_UI_ATTRIBUTE + \"],.ash-comment-highlight-badge,.mermaid-diagram\";\n const IGNORED_MUTATION_SELECTOR = \"[\" + ANCHOR_IGNORE_ATTRIBUTE + \"],#\" + HIGHLIGHT_STYLE_ID;\n const COMMENT_UI_SELECTOR = \"[\" + COMMENT_UI_ATTRIBUTE + \"]\";\n function anchorIgnoreAttribute() {\n return ANCHOR_IGNORE_ATTRIBUTE;\n }\n function commentUiAttribute() {\n return COMMENT_UI_ATTRIBUTE;\n }\n function highlightStyleId() {\n return HIGHLIGHT_STYLE_ID;\n }\n function ignoredMutationSelector() {\n return IGNORED_MUTATION_SELECTOR;\n }\n function commentUiSelector() {\n return COMMENT_UI_SELECTOR;\n }\n function createTextAnchorEngine(root) {\n const document = root.ownerDocument;\n const units = [];\n let text = \"\";\n let previousBlock = null;\n const blockTags = new Set(\"p div li ul ol dl dt dd h1 h2 h3 h4 h5 h6 pre blockquote table thead tbody tfoot tr td th caption section article aside header footer nav main figure figcaption details summary hr br address form fieldset\".split(\" \"));\n const walker = document.createTreeWalker(root, 4 | 1);\n let node;\n while (node = walker.nextNode()) {\n const element = node.nodeType === 1 ? node : node.parentElement;\n if (!element || element.closest(TEXT_ANCHOR_EXCLUDED_SELECTOR)) continue;\n if (node.nodeType === 1) {\n if ((node.localName === \"br\" || node.localName === \"hr\") && text && !text.endsWith(\" \")) {\n text += \" \";\n units.push([]);\n }\n continue;\n }\n const parent = node.parentElement;\n let block = parent;\n while (block && block !== root && !blockTags.has(block.localName)) block = block.parentElement;\n if (text && previousBlock !== block && !text.endsWith(\" \")) {\n text += \" \";\n units.push([]);\n }\n previousBlock = block;\n const value = node.nodeValue || \"\";\n for (let offset = 0; offset < value.length; offset++) {\n const segment = {\n node,\n start: offset,\n end: offset + 1\n };\n if (/\\s/.test(value[offset])) {\n if (!text) continue;\n if (text.endsWith(\" \")) units[units.length - 1].push(segment);\n else {\n text += \" \";\n units.push([segment]);\n }\n } else {\n text += value[offset];\n units.push([segment]);\n }\n }\n }\n function textHash(value) {\n const bytes = new TextEncoder().encode(value);\n const words = new Uint32Array(Math.ceil((bytes.length + 9) / 64) * 16);\n for (let i = 0; i < bytes.length; i++) words[i >>> 2] = words[i >>> 2] | bytes[i] << 24 - i % 4 * 8;\n words[bytes.length >>> 2] = words[bytes.length >>> 2] | 128 << 24 - bytes.length % 4 * 8;\n words[words.length - 2] = Math.floor(bytes.length / 536870912);\n words[words.length - 1] = bytes.length * 8;\n const h = [\n 1779033703,\n 3144134277,\n 1013904242,\n 2773480762,\n 1359893119,\n 2600822924,\n 528734635,\n 1541459225\n ];\n const k = [\n 1116352408,\n 1899447441,\n 3049323471,\n 3921009573,\n 961987163,\n 1508970993,\n 2453635748,\n 2870763221,\n 3624381080,\n 310598401,\n 607225278,\n 1426881987,\n 1925078388,\n 2162078206,\n 2614888103,\n 3248222580,\n 3835390401,\n 4022224774,\n 264347078,\n 604807628,\n 770255983,\n 1249150122,\n 1555081692,\n 1996064986,\n 2554220882,\n 2821834349,\n 2952996808,\n 3210313671,\n 3336571891,\n 3584528711,\n 113926993,\n 338241895,\n 666307205,\n 773529912,\n 1294757372,\n 1396182291,\n 1695183700,\n 1986661051,\n 2177026350,\n 2456956037,\n 2730485921,\n 2820302411,\n 3259730800,\n 3345764771,\n 3516065817,\n 3600352804,\n 4094571909,\n 275423344,\n 430227734,\n 506948616,\n 659060556,\n 883997877,\n 958139571,\n 1322822218,\n 1537002063,\n 1747873779,\n 1955562222,\n 2024104815,\n 2227730452,\n 2361852424,\n 2428436474,\n 2756734187,\n 3204031479,\n 3329325298\n ];\n const rotate = (x, n) => x >>> n | x << 32 - n;\n const w = new Uint32Array(64);\n for (let offset = 0; offset < words.length; offset += 16) {\n for (let i = 0; i < 64; i++) {\n if (i < 16) w[i] = words[offset + i];\n else {\n const x = w[i - 15], y = w[i - 2];\n w[i] = w[i - 16] + (rotate(x, 7) ^ rotate(x, 18) ^ x >>> 3) + w[i - 7] + (rotate(y, 17) ^ rotate(y, 19) ^ y >>> 10);\n }\n }\n let [a, b, c, d, e, f, g, j] = h;\n for (let i = 0; i < 64; i++) {\n const t1 = j + (rotate(e, 6) ^ rotate(e, 11) ^ rotate(e, 25)) + (e & f ^ ~e & g) + k[i] + w[i] | 0;\n const t2 = (rotate(a, 2) ^ rotate(a, 13) ^ rotate(a, 22)) + (a & b ^ a & c ^ b & c) | 0;\n j = g;\n g = f;\n f = e;\n e = d + t1 | 0;\n d = c;\n c = b;\n b = a;\n a = t1 + t2 | 0;\n }\n const next = [\n a,\n b,\n c,\n d,\n e,\n f,\n g,\n j\n ];\n for (let i = 0; i < 8; i++) h[i] = h[i] + next[i] | 0;\n }\n return h.map((word) => (word >>> 0).toString(16).padStart(8, \"0\")).join(\"\");\n }\n const hash = textHash(text);\n function hits(haystack, needle) {\n const found = [];\n if (needle) for (let at = haystack.indexOf(needle); at >= 0; at = haystack.indexOf(needle, at + 1)) found.push(at);\n return found;\n }\n function normalizedQuote(selector) {\n return selector.selectorFormat === \"normalized-v1\" ? selector.quotedText : selector.quotedText.replace(/\\s+/g, \" \").trim();\n }\n function resolve(selector) {\n if (!selector || typeof selector.quotedText !== \"string\" || selector.prefixText != null && typeof selector.prefixText !== \"string\" || selector.suffixText != null && typeof selector.suffixText !== \"string\") return null;\n const modern = selector.selectorFormat === \"normalized-v1\";\n const legacy = !selector.selectorFormat;\n const normalize = (value) => modern ? value : legacy ? value.replace(/\\s+/g, \" \").trim() : value.replace(/\\s+/g, \" \");\n const quote = normalizedQuote(selector);\n const prefix = normalize(selector.prefixText || \"\");\n const suffix = normalize(selector.suffixText || \"\");\n if (!quote.trim()) return null;\n if (legacy || selector.selectorFormat === \"quote-v1\") {\n const positions = new Set();\n for (const before of prefix && !prefix.endsWith(\" \") ? [\"\", \" \"] : [\"\"]) for (const after of suffix && !suffix.startsWith(\" \") ? [\"\", \" \"] : [\"\"]) for (const at of hits(text, prefix + before + quote + after + suffix)) positions.add(at + prefix.length + before.length);\n if (positions.size !== 1) return null;\n const start = positions.values().next().value;\n return {\n textStart: start,\n textEnd: start + quote.length\n };\n }\n const matches = hits(text, prefix + quote + suffix);\n const hit = matches.length === 1 ? matches[0] + prefix.length : -1;\n const context = prefix + quote + suffix;\n const start = selector.textStart, end = selector.textEnd;\n if (modern && typeof start === \"number\" && Number.isInteger(start) && typeof end === \"number\" && Number.isInteger(end) && start >= prefix.length && end - start === quote.length && text.slice(start, end) === quote && text.slice(start - prefix.length, end + suffix.length) === context && (hit >= 0 || selector.textHash === hash)) return {\n textStart: start,\n textEnd: end\n };\n if (hit >= 0 && !selector.ambiguousAtCreation) return {\n textStart: hit,\n textEnd: hit + quote.length\n };\n return null;\n }\n function ranges(start, end) {\n const segments = [];\n for (const unit of units.slice(start, end)) for (const segment of unit) {\n const last = segments[segments.length - 1];\n if (last && last.node === segment.node && last.end === segment.start) last.end = segment.end;\n else segments.push({ ...segment });\n }\n return segments.map((segment) => {\n const range = document.createRange();\n range.setStart(segment.node, segment.start);\n range.setEnd(segment.node, segment.end);\n return range;\n });\n }\n const sourceIndexes = new WeakMap();\n const sourceSegments = [];\n units.forEach((segments, index) => {\n for (const segment of segments) {\n sourceSegments.push({\n segment,\n index\n });\n let offsets = sourceIndexes.get(segment.node);\n if (!offsets) sourceIndexes.set(segment.node, offsets = []);\n offsets[segment.start] = index;\n }\n });\n function paintedText(first, last) {\n const start = sourceIndexes.get(first.startContainer)?.[first.startOffset];\n const end = sourceIndexes.get(last.endContainer)?.[last.endOffset - 1];\n return start === undefined || end === undefined || start > end ? null : text.slice(start, end + 1).trim();\n }\n function mappedSlice(range) {\n if (!root.contains(range.startContainer) || !root.contains(range.endContainer) || range.collapsed) return null;\n function boundary(boundaryNode, offset, isEnd) {\n const direct = sourceIndexes.get(boundaryNode)?.[isEnd ? offset - 1 : offset];\n if (direct !== undefined) return direct + (isEnd ? 1 : 0);\n const point = document.createRange();\n point.setStart(boundaryNode, offset);\n point.collapse(true);\n let low = 0, high = sourceSegments.length;\n while (low < high) {\n const mid = low + high >>> 1;\n const entry = sourceSegments[mid];\n const comparison = point.comparePoint(entry.segment.node, isEnd ? entry.segment.start : entry.segment.end);\n if (isEnd ? comparison < 0 : comparison <= 0) low = mid + 1;\n else high = mid;\n }\n return isEnd ? low ? sourceSegments[low - 1].index + 1 : 0 : low < sourceSegments.length ? sourceSegments[low].index : text.length;\n }\n let start = boundary(range.startContainer, range.startOffset, false);\n let end = boundary(range.endContainer, range.endOffset, true);\n while (start >= 0 && start < end && /\\s/.test(text[start])) start++;\n while (end > start && /\\s/.test(text[end - 1])) end--;\n if (start < 0 || start >= end || end - start > 1e3) return null;\n return {\n textStart: start,\n textEnd: end,\n quotedText: text.slice(start, end)\n };\n }\n function describe(range) {\n const mapped = mappedSlice(range);\n if (!mapped) return null;\n const { textStart: start, textEnd: end, quotedText: quote } = mapped;\n let prefix = \"\", suffix = \"\", ambiguous = true;\n for (let size = 32;; size = Math.min(400, size + 32)) {\n prefix = text.slice(Math.max(0, start - size), start);\n suffix = text.slice(end, end + size);\n ambiguous = hits(text, prefix + quote + suffix).length !== 1;\n if (!ambiguous || size === 400) break;\n }\n return {\n quotedText: quote,\n prefixText: prefix,\n suffixText: suffix,\n textStart: start,\n textEnd: end,\n textHash: hash,\n selectorFormat: \"normalized-v1\",\n ambiguousAtCreation: ambiguous\n };\n }\n return {\n text,\n hash,\n describe,\n mappedSlice,\n resolve,\n ranges,\n paintedText,\n normalizedQuote\n };\n }\n\n function trusted(ctx, event) {\n try {\n return ctx.primordials.trustedGetter && ctx.primordials.trustedGetter.get ? ctx.primordials.trustedGet(event) === true : event.isTrusted === true;\n } catch (e) {\n return false;\n }\n }\n function shouldHandleLink(ctx, url) {\n if (url.origin !== ctx.win.location.origin) return true;\n if (url.pathname !== ctx.win.location.pathname) return true;\n if (url.search !== ctx.win.location.search && url.search !== \"\") return true;\n return false;\n }\n function openExternalLink(ctx, href) {\n ctx.win.open(href, \"_blank\", \"noopener,noreferrer\");\n }\n function isExternallyOpenable(ctx, url) {\n return url.protocol === \"http:\" || url.protocol === \"https:\";\n }\n function prepareLinkClick(ctx, event) {\n let defaultPrevented = readEventValue(ctx, ctx.primordials.defaultPreventedGet, event);\n let button = readEventValue(ctx, ctx.primordials.buttonGet, event);\n let metaKey = readEventValue(ctx, ctx.primordials.metaKeyGet, event);\n let ctrlKey = readEventValue(ctx, ctx.primordials.ctrlKeyGet, event);\n let shiftKey = readEventValue(ctx, ctx.primordials.shiftKeyGet, event);\n let altKey = readEventValue(ctx, ctx.primordials.altKeyGet, event);\n if (!trusted(ctx, event) || defaultPrevented !== false || button !== 0 || metaKey !== false || ctrlKey !== false || shiftKey !== false || altKey !== false) {\n return;\n }\n if (hitComment(ctx, event)) return;\n let target = readEventValue(ctx, ctx.primordials.targetGet, event);\n let element = target && target.nodeType === 1 ? target : target && target.parentElement;\n if (element && ctx.primordials.closest(element, \".ash-comment-highlight, .ash-comment-highlight-badge\")) {\n return;\n }\n let anchor = element ? ctx.primordials.closest(element, \"a[href]\") : null;\n if (!anchor || ctx.primordials.hasAttribute(anchor, \"download\")) return;\n let rawHref = ctx.primordials.getAttribute(anchor, \"href\");\n if (!rawHref || rawHref.charAt(0) === \"#\") return;\n let url;\n let href;\n let openExternally = false;\n try {\n url = new ctx.win.URL(rawHref, ctx.win.location.href);\n if (!shouldHandleLink(ctx, url)) return;\n href = url.href;\n openExternally = url.origin !== ctx.win.location.origin && isExternallyOpenable(ctx, url);\n } catch (e) {\n href = rawHref;\n }\n let pending = ctx.primordials.objectCreate(null);\n pending.artifactPrevented = false;\n pending.href = href;\n pending.openExternally = openExternally;\n try {\n ctx.primordials.defineProperty(event, \"preventDefault\", {\n configurable: true,\n value: function() {\n pending.artifactPrevented = true;\n ctx.primordials.preventDefault(event);\n }\n });\n ctx.primordials.defineProperty(event, \"defaultPrevented\", {\n configurable: true,\n get: function() {\n return pending.artifactPrevented;\n }\n });\n ctx.primordials.weakMapSet(ctx.pendingLinkClicks, event, pending);\n } catch (e) {\n ctx.primordials.preventDefault(event);\n return;\n }\n ctx.primordials.preventDefault(event);\n }\n function finishLinkClick(ctx, event) {\n let pending = ctx.primordials.weakMapGet(ctx.pendingLinkClicks, event);\n if (!pending) return;\n ctx.primordials.weakMapDelete(ctx.pendingLinkClicks, event);\n if (pending.artifactPrevented) return;\n if (pending.openExternally && ctx.externalLinkPolicyMode === \"direct\") {\n openExternalLink(ctx, pending.href);\n return;\n }\n send(ctx, {\n kind: \"link-clicked\",\n href: pending.href,\n token: ctx.documentToken\n });\n }\n\n function badgeStyleForHighlight(ctx, highlight, isDark) {\n let palette = highlightPalette(ctx, isDark, highlight.status === \"resolved\");\n let base = \"display:inline-flex;align-items:center;gap:4px;min-height:16px;padding:0 5px;border-radius:999px;font:700 10px system-ui,sans-serif;box-shadow:0 2px 8px rgba(27,39,35,.08);cursor:pointer;touch-action:none;position:absolute;z-index:2147483646;\";\n let borderColor;\n let textColor;\n let bgColor;\n if (highlight.target) {\n borderColor = palette.badgeTargetBorder;\n textColor = palette.badgeTargetText;\n bgColor = palette.badgeTargetBg;\n } else {\n borderColor = palette.badgeBorder;\n textColor = palette.badgeText;\n bgColor = palette.badgeBg;\n }\n return base + \"border:1px solid \" + borderColor + \";color:\" + textColor + \";background:\" + bgColor + \";\";\n }\n function positionSingleBadge(ctx, entry) {\n let badge = entry.badge;\n let rects = measureBadgeEntry(ctx, entry);\n let rect = rects.length ? rects[rects.length - 1] : null;\n if (!rect || rect.width === 0 || rect.height === 0) {\n badge.style.display = \"none\";\n return;\n }\n badge.style.display = \"inline-flex\";\n badge.style.left = \"0px\";\n badge.style.top = \"0px\";\n let base = badge.getBoundingClientRect();\n let scaleX = badge.offsetWidth ? base.width / badge.offsetWidth : 1;\n let scaleY = badge.offsetHeight ? base.height / badge.offsetHeight : 1;\n if (!scaleX || !isFinite(scaleX)) scaleX = 1;\n if (!scaleY || !isFinite(scaleY)) scaleY = 1;\n let badgeHeight = badge.offsetHeight || 16;\n let threadId = badge.dataset.threadId;\n let offset = ctx.badgeOffsets[threadId] || {\n x: 0,\n y: 0\n };\n badge.style.left = (rect.right - base.left) / scaleX - 6 + offset.x + \"px\";\n badge.style.top = (rect.top - base.top) / scaleY - badgeHeight + 3 + offset.y + \"px\";\n }\n function positionBadges(ctx) {\n let layouts = [];\n for (let i = 0; i < ctx.badges.length; i++) {\n let badge = ctx.badges[i].badge;\n let rects = measureBadgeEntry(ctx, ctx.badges[i]);\n let rect = rects.length ? rects[rects.length - 1] : null;\n badge.style.display = \"inline-flex\";\n badge.style.left = \"0px\";\n badge.style.top = \"0px\";\n let base = badge.getBoundingClientRect();\n let scaleX = badge.offsetWidth ? base.width / badge.offsetWidth : 1;\n let scaleY = badge.offsetHeight ? base.height / badge.offsetHeight : 1;\n if (!scaleX || !isFinite(scaleX)) scaleX = 1;\n if (!scaleY || !isFinite(scaleY)) scaleY = 1;\n layouts.push({\n badge,\n rect,\n base,\n badgeHeight: badge.offsetHeight || 16,\n scaleX,\n scaleY,\n threadId: badge.dataset.threadId\n });\n }\n for (let j = 0; j < layouts.length; j++) {\n let layout = layouts[j];\n if (!layout.rect || layout.rect.width === 0 || layout.rect.height === 0) {\n layout.badge.style.display = \"none\";\n continue;\n }\n let offset = ctx.badgeOffsets[layout.threadId] || {\n x: 0,\n y: 0\n };\n layout.badge.style.display = \"inline-flex\";\n layout.badge.style.left = (layout.rect.right - layout.base.left) / layout.scaleX - 6 + offset.x + \"px\";\n layout.badge.style.top = (layout.rect.top - layout.base.top) / layout.scaleY - layout.badgeHeight + 3 + offset.y + \"px\";\n }\n }\n function isBadgeAnchorVisible(ctx, element) {\n if (!element) return false;\n let visibility = ctx.win.getComputedStyle(element).visibility;\n if (visibility === \"hidden\" || visibility === \"collapse\") return false;\n let boxedElement = element;\n while (boxedElement && ctx.win.getComputedStyle(boxedElement).display === \"contents\") {\n boxedElement = boxedElement.parentElement;\n }\n return !!boxedElement && !!boxedElement.getClientRects().length && (!boxedElement.checkVisibility || boxedElement.checkVisibility());\n }\n function measureBadgeEntry(ctx, entry) {\n if (entry.measure) return entry.measure();\n return [];\n }\n function schedulePositionBadges(ctx) {\n if (ctx.badgePositionFrame) return;\n ctx.badgePositionFrame = ctx.win.requestAnimationFrame(function() {\n ctx.badgePositionFrame = 0;\n positionBadges(ctx);\n });\n }\n function takeBadge(ctx, highlight) {\n let badge = ctx.reusableBadges.get(highlight.threadId);\n if (badge) ctx.reusableBadges.delete(highlight.threadId);\n else {\n badge = ctx.doc.createElement(\"button\");\n bindBadgePointer(ctx, badge);\n }\n if (!badge.isConnected) ctx.doc.documentElement.appendChild(badge);\n return badge;\n }\n function hitComment(ctx, event) {\n if (!trusted(ctx, event) || event.type === \"click\" && (event.detail <= 0 || event.pointerType === \"\" || event.mozInputSource === 6)) return null;\n for (let index = 0; index < ctx.badges.length; index++) {\n let rects = measureBadgeEntry(ctx, ctx.badges[index]);\n if (Array.from(rects).some(function(rect) {\n return event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom;\n })) return ctx.badges[index].badge;\n }\n return null;\n }\n function rectFromPointer(ctx, event, fallback) {\n if (event.detail !== 0 && typeof event.clientX === \"number\" && typeof event.clientY === \"number\") {\n return {\n top: event.clientY - 8,\n left: event.clientX,\n width: 1,\n height: 16\n };\n }\n return fallback;\n }\n function bindBadgePointer(ctx, badge) {\n let dragState = null;\n let badgeEntry = null;\n function finishDrag(event) {\n if (!dragState || event.pointerId !== dragState.pointerId) return;\n if (event.type === \"pointerup\" && dragState.dragged) ctx.badgeDragged = true;\n try {\n badge.releasePointerCapture(event.pointerId);\n } catch (e) {}\n dragState = null;\n }\n badge.addEventListener(\"pointerdown\", function(event) {\n ctx.badgeDragged = false;\n if (event.button !== 0) return;\n for (let i = 0; i < ctx.badges.length; i++) {\n if (ctx.badges[i].badge === badge) {\n badgeEntry = ctx.badges[i];\n break;\n }\n }\n let threadId = badge.dataset.threadId;\n let offset = ctx.badgeOffsets[threadId] || {\n x: 0,\n y: 0\n };\n dragState = {\n pointerId: event.pointerId,\n startX: event.clientX,\n startY: event.clientY,\n offsetX: offset.x,\n offsetY: offset.y,\n dragged: false\n };\n try {\n badge.setPointerCapture(event.pointerId);\n } catch (e) {}\n event.preventDefault();\n });\n badge.addEventListener(\"pointermove\", function(event) {\n if (!dragState || event.pointerId !== dragState.pointerId) return;\n let dx = event.clientX - dragState.startX;\n let dy = event.clientY - dragState.startY;\n if (!dragState.dragged && (Math.abs(dx) > 4 || Math.abs(dy) > 4)) {\n dragState.dragged = true;\n }\n if (!dragState.dragged) return;\n let threadId = badge.dataset.threadId;\n ctx.badgeOffsets[threadId] = {\n x: dragState.offsetX + dx,\n y: dragState.offsetY + dy\n };\n if (badgeEntry) positionSingleBadge(ctx, badgeEntry);\n });\n badge.addEventListener(\"pointerup\", finishDrag);\n badge.addEventListener(\"pointercancel\", finishDrag);\n badge.addEventListener(\"click\", function(event) {\n if (ctx.badgeDragged) {\n ctx.badgeDragged = false;\n event.preventDefault();\n event.stopPropagation();\n return;\n }\n let r = badge.getBoundingClientRect();\n selectThreadFromElement(ctx, badge, rectFromPointer(ctx, event, r));\n event.preventDefault();\n event.stopPropagation();\n });\n function updateSvgActive(active) {\n ctx.svgActiveThreads[badge.dataset.threadId] = active;\n setSvgHighlightState(ctx, badge.dataset.threadId, active);\n }\n badge.addEventListener(\"pointerenter\", function() {\n updateSvgActive(true);\n });\n badge.addEventListener(\"pointerleave\", function() {\n updateSvgActive(ctx.doc.activeElement === badge);\n });\n badge.addEventListener(\"focus\", function() {\n updateSvgActive(true);\n });\n badge.addEventListener(\"blur\", function() {\n updateSvgActive(badge.matches(\":hover\"));\n });\n }\n function selectThreadFromElement(ctx, element, rect) {\n send(ctx, {\n kind: \"comment-thread-selected\",\n threadId: element.dataset.threadId,\n rect: {\n top: rect.top,\n left: rect.left,\n width: rect.width,\n height: rect.height\n }\n });\n }\n function sendOutsidePointerDown(ctx, event) {\n if (!ctx.textAnchorsEnabled || hitComment(ctx, event)) return;\n let target = event.target;\n if (target && target.closest && target.closest(\".ash-comment-highlight, .ash-comment-highlight-badge, [data-code-copy]\")) {\n return;\n }\n send(ctx, { kind: \"comment-outside-pointer-down\" });\n }\n\n function setSvgHighlightState(ctx, threadId, active) {\n ctx.textPaints.forEach(function(paint) {\n if (paint.threadId === threadId) paint.active = active || paint.target;\n });\n refreshTextPaints(ctx);\n let overlays = ctx.doc.querySelectorAll(\".ash-comment-highlight-svg[data-thread-id=\\\"\" + ctx.win.CSS.escape(threadId) + \"\\\"]\");\n for (let i = 0; i < overlays.length; i++) {\n let overlay = overlays[i];\n let palette = overlay.dataset.palette;\n if (!palette) continue;\n let parts = palette.split(\"|\");\n let normalFill = parts[0];\n let outline = parts[1];\n let target = overlay.dataset.target === \"true\";\n let state = active || target ? \"active\" : \"normal\";\n let applied = ctx.svgOverlayStyles.get(overlay);\n if (overlay.dataset.state !== state) overlay.dataset.state = state;\n if (applied && applied.state === state && overlay.getAttribute(\"style\") === applied.style) continue;\n if (active || target) {\n overlay.style.fill = normalFill;\n overlay.style.stroke = outline;\n overlay.style.strokeWidth = \"2\";\n overlay.style.vectorEffect = \"non-scaling-stroke\";\n } else {\n overlay.style.fill = normalFill;\n overlay.style.stroke = \"none\";\n overlay.style.strokeWidth = \"0\";\n }\n ctx.svgOverlayStyles.set(overlay, {\n state,\n style: overlay.getAttribute(\"style\")\n });\n }\n }\n function svgTextRange(ctx, ranges) {\n return ranges.flatMap(function(range) {\n let node = range.startContainer;\n if (!node.parentElement.closest(\"svg text\")) return [];\n let text = node.parentElement.closest(\"text,tspan,textPath\");\n if (!text || !text.getNumberOfChars) return [];\n let walker = ctx.doc.createTreeWalker(text, ctx.win.NodeFilter.SHOW_TEXT);\n let raw = [], collapsed = [], candidate;\n let whitespace = false;\n while (candidate = walker.nextNode()) {\n let value = candidate.nodeValue || \"\";\n for (let offset = 0; offset < value.length; offset++) {\n let unit = {\n node: candidate,\n offset\n };\n raw.push([unit]);\n if (/[\\t\\n\\r ]/.test(value[offset])) {\n if (!collapsed.length) continue;\n if (whitespace) collapsed[collapsed.length - 1].push(unit);\n else collapsed.push([unit]);\n whitespace = true;\n } else {\n collapsed.push([unit]);\n whitespace = false;\n }\n }\n }\n if (whitespace) collapsed.pop();\n let count = text.getNumberOfChars();\n let characters = collapsed.length === count ? collapsed : raw.length === count ? raw : null;\n if (!characters) return [];\n let start = -1, end = -1;\n characters.forEach(function(units, index) {\n for (let i = 0; i < units.length; i++) {\n let unit = units[i];\n if (unit.node === node && unit.offset >= range.startOffset && unit.offset < range.endOffset) {\n if (start < 0) start = index;\n end = index + 1;\n break;\n }\n }\n });\n return start < 0 ? [] : [{\n text,\n start,\n end\n }];\n });\n }\n function wrapSvgRange(ctx, highlight, groups) {\n if (!groups.length) return false;\n let texts = groups.map(function(group) {\n return group.text;\n }).filter(function(text, index, all) {\n return all.indexOf(text) === index;\n });\n let first = texts[0];\n let svg = first && first.ownerSVGElement;\n while (svg && svg.ownerSVGElement) svg = svg.ownerSVGElement;\n if (!svg || !svg.parentNode) return false;\n ensureCommentStyles(ctx);\n let overlays = {};\n let badgeEntry = {\n badge: null,\n highlight,\n overlays,\n measure: measureSvgRange\n };\n function overlayKey(text, index) {\n return texts.indexOf(text) + \":\" + index;\n }\n function setAttributeIfChanged(shape, name, value) {\n value = String(value);\n if (shape.getAttribute(name) !== value) shape.setAttribute(name, String(value));\n }\n function updateOverlay(text, index, box, screenCtm) {\n let currentHighlight = badgeEntry.highlight;\n let key = overlayKey(text, index);\n let shape = overlays[key];\n if (!shape) {\n shape = ctx.doc.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\");\n shape.setAttribute(\"class\", \"ash-comment-highlight-svg\");\n shape.setAttribute(anchorIgnoreAttribute(), \"\");\n shape.setAttribute(\"pointer-events\", \"none\");\n shape.dataset.threadId = currentHighlight.threadId;\n shape.dataset.target = currentHighlight.target ? \"true\" : \"false\";\n let palette = highlightPalette(ctx, isDarkBackgroundForSvgText(ctx, text), currentHighlight.status === \"resolved\");\n shape.dataset.palette = palette.markBg + \"|\" + palette.outline;\n let textRoot = text.closest(\"text\");\n textRoot.parentNode.insertBefore(shape, textRoot);\n overlays[key] = shape;\n }\n let scaleX = screenCtm ? Math.hypot(screenCtm.a, screenCtm.b) : 1;\n let scaleY = screenCtm ? Math.hypot(screenCtm.c, screenCtm.d) : 1;\n let padX = scaleX ? 2 / scaleX : 2;\n let padY = scaleY ? 2 / scaleY : 2;\n setAttributeIfChanged(shape, \"x\", box.x - padX);\n setAttributeIfChanged(shape, \"y\", box.y - padY);\n setAttributeIfChanged(shape, \"width\", box.width + padX * 2);\n setAttributeIfChanged(shape, \"height\", box.height + padY * 2);\n let textCtm = text.getCTM ? text.getCTM() : null;\n let parentNode = shape.parentNode;\n let parentCtm = parentNode && parentNode.getCTM ? parentNode.getCTM() : null;\n if (textCtm && parentCtm && parentCtm.inverse) {\n let matrix = parentCtm.inverse().multiply(textCtm);\n setAttributeIfChanged(shape, \"transform\", \"matrix(\" + [\n matrix.a,\n matrix.b,\n matrix.c,\n matrix.d,\n matrix.e,\n matrix.f\n ].join(\" \") + \")\");\n } else if (shape.hasAttribute(\"transform\")) {\n shape.removeAttribute(\"transform\");\n }\n return shape;\n }\n function measureSvgRange() {\n let current = [];\n let lastElement = null;\n let usedOverlays = {};\n for (let i = 0; i < groups.length; i++) {\n let group = groups[i];\n let ctm = group.text.getScreenCTM ? group.text.getScreenCTM() : null;\n let runs = [];\n for (let index = group.start; index < group.end; index++) {\n try {\n let box = group.text.getExtentOfChar(index);\n if (!box || box.width < 0 || box.height <= 0) continue;\n let previous = runs.length ? runs[runs.length - 1] : null;\n let overlapsVertically = previous && box.y <= previous.y + previous.height && previous.y <= box.y + box.height;\n let sameLine = previous && overlapsVertically && box.x <= previous.x + previous.width + Math.max(4, box.height * .5);\n if (sameLine && previous) {\n let runRight = Math.max(previous.x + previous.width, box.x + box.width);\n let runBottom = Math.max(previous.y + previous.height, box.y + box.height);\n previous.x = Math.min(previous.x, box.x);\n previous.y = Math.min(previous.y, box.y);\n previous.width = runRight - previous.x;\n previous.height = runBottom - previous.y;\n } else {\n runs.push({\n x: box.x,\n y: box.y,\n width: box.width,\n height: box.height\n });\n }\n } catch (e) {}\n }\n for (let runIndex = 0; runIndex < runs.length; runIndex++) {\n try {\n let run = runs[runIndex];\n let overlayIndex = i + \"-\" + runIndex;\n let overlay = updateOverlay(group.text, overlayIndex, run, ctm);\n let display = isBadgeAnchorVisible(ctx, group.text) ? \"inline\" : \"none\";\n if (overlay.style.display !== display) overlay.style.display = display;\n usedOverlays[overlayKey(group.text, overlayIndex)] = true;\n let points = [\n [run.x, run.y],\n [run.x + run.width, run.y],\n [run.x, run.y + run.height],\n [run.x + run.width, run.y + run.height]\n ].map(function(point) {\n return ctm ? new ctx.win.DOMPoint(point[0], point[1]).matrixTransform(ctm) : {\n x: point[0],\n y: point[1]\n };\n });\n let left = Math.min.apply(null, points.map(function(point) {\n return point.x;\n }));\n let top = Math.min.apply(null, points.map(function(point) {\n return point.y;\n }));\n let right = Math.max.apply(null, points.map(function(point) {\n return point.x;\n }));\n let bottom = Math.max.apply(null, points.map(function(point) {\n return point.y;\n }));\n if (right > left && bottom > top) {\n current.push({\n left,\n right,\n top,\n width: right - left,\n height: bottom - top\n });\n lastElement = group.text;\n }\n } catch (e) {}\n }\n }\n Object.keys(overlays).forEach(function(key) {\n if (!usedOverlays[key]) {\n overlays[key].remove();\n delete overlays[key];\n }\n });\n setSvgHighlightState(ctx, highlight.threadId, ctx.svgActiveThreads[highlight.threadId] === true);\n if (current.length) return isBadgeAnchorVisible(ctx, lastElement) ? current : [];\n if (!isBadgeAnchorVisible(ctx, first)) return [];\n let fallback = first.getBoundingClientRect ? first.getBoundingClientRect() : null;\n if (!fallback || fallback.width === 0 || fallback.height === 0) {\n fallback = svg.getBoundingClientRect();\n }\n return fallback ? [fallback] : [];\n }\n let badge = takeBadge(ctx, highlight);\n badge.setAttribute(anchorIgnoreAttribute(), \"\");\n badge.type = \"button\";\n badge.className = \"ash-comment-highlight-badge\";\n badge.dataset.threadId = highlight.threadId;\n badge.dataset.count = String(highlight.count || 1);\n badge.setAttribute(\"aria-label\", commentLabel(ctx, highlight));\n badge.innerHTML = highlight.status === \"resolved\" ? \"<svg viewBox=\\\"0 0 24 24\\\" width=\\\"10\\\" height=\\\"10\\\" style=\\\"width:10px;height:10px;flex:none;border:0;padding:0;margin:0;background:none;box-shadow:none\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\" aria-hidden=\\\"true\\\"><path d=\\\"M20 6 9 17l-5-5\\\"/></svg>\" : \"<svg viewBox=\\\"0 0 24 24\\\" width=\\\"10\\\" height=\\\"10\\\" style=\\\"width:10px;height:10px;flex:none;border:0;padding:0;margin:0;background:none;box-shadow:none\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\" aria-hidden=\\\"true\\\"><path d=\\\"M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4z\\\"/></svg>\";\n badge.style.cssText = badgeStyleForHighlight(ctx, highlight, isDarkBackgroundForSvgText(ctx, first));\n badgeEntry.badge = badge;\n ctx.badges.push(badgeEntry);\n measureSvgRange();\n return true;\n }\n\n function cssPath(ctx, element) {\n if (!element || element.nodeType !== 1) return null;\n let parts = [];\n while (element && element.nodeType === 1 && element !== ctx.doc.body) {\n let name = element.nodeName.toLowerCase();\n let index = 1;\n let sibling = element;\n while (sibling = sibling.previousElementSibling) {\n if (sibling.nodeName.toLowerCase() === name) index++;\n }\n parts[parts.length] = name + \":nth-of-type(\" + index + \")\";\n element = element.parentElement;\n }\n let path = \"body\";\n for (let i = parts.length - 1; i >= 0; i--) path += \" > \" + parts[i];\n return path;\n }\n function selectedElement(ctx, range) {\n let node = range.commonAncestorContainer;\n return (node.nodeType === 1 ? node : node.parentElement) || ctx.doc.body;\n }\n function anchorRoot(ctx) {\n return ctx.doc.querySelector(\"[data-comment-content]\") || ctx.doc.body;\n }\n function sendSelection(ctx) {\n if (!ctx.textAnchorsEnabled) return;\n let selection = ctx.win.getSelection();\n if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {\n send(ctx, { kind: \"text-selection-cleared\" });\n return;\n }\n let range = selection.getRangeAt(0);\n if (!ctx.primordials.rangeToString(range).trim()) {\n send(ctx, { kind: \"text-selection-cleared\" });\n return;\n }\n let engine = createTextAnchorEngine(anchorRoot(ctx));\n let selector = engine.describe(range);\n if (!selector) {\n send(ctx, { kind: \"text-selection-cleared\" });\n return;\n }\n let rect = range.getBoundingClientRect();\n send(ctx, {\n kind: \"text-selection\",\n token: ctx.documentToken,\n quotedText: selector.quotedText,\n prefixText: selector.prefixText,\n suffixText: selector.suffixText,\n textStart: selector.textStart,\n textEnd: selector.textEnd,\n selectorFormat: selector.selectorFormat,\n textHash: selector.textHash,\n ambiguousAtCreation: selector.ambiguousAtCreation,\n versionId: ctx.displayedVersionId,\n cssPath: cssPath(ctx, selectedElement(ctx, range)),\n rect: {\n top: rect.top,\n left: rect.left,\n width: rect.width,\n height: rect.height\n }\n });\n }\n\n function ensureAnnotateStyles(ctx) {\n if (ctx.doc.getElementById(\"as-preview-annotate-style\")) return;\n let style = ctx.doc.createElement(\"style\");\n style.setAttribute(anchorIgnoreAttribute(), \"\");\n style.id = \"as-preview-annotate-style\";\n style.textContent = \".as-preview-annotate-hover{outline:2px solid #6366f1 !important;outline-offset:2px;}\" + \".as-preview-pinged{outline:2px solid #6366f1 !important;outline-offset:2px;background-color:rgba(99,102,241,0.12) !important;transition:background-color 0.4s ease;}\" + \".as-preview-flash{background-color:rgba(34,197,94,0.35) !important;transition:background-color 1s ease;}\" + \".as-preview-flash-fade{background-color:transparent !important;}\";\n ctx.doc.head.appendChild(style);\n }\n function annotateTargetFrom(ctx, eventTarget) {\n const target = eventTarget;\n if (!target || target.nodeType !== 1) return null;\n if (target === ctx.doc.body || target === ctx.doc.documentElement) return null;\n if (ctx.primordials.closest(target, commentUiSelector())) return null;\n return target;\n }\n function clearAnnotateHover(ctx) {\n if (ctx.annotateHoverElement) {\n ctx.annotateHoverElement.classList.remove(\"as-preview-annotate-hover\");\n ctx.annotateHoverElement = null;\n }\n }\n function elementLabel(ctx, el) {\n let quote = function(text) {\n return \"\\\"\" + text + \"\\\"\";\n };\n let tag = el.nodeName.toLowerCase();\n let ariaLabel = el.getAttribute && el.getAttribute(\"aria-label\");\n if (ariaLabel) return tag + \" \" + quote(ariaLabel.trim());\n let text = (el.textContent || \"\").replace(/\\s+/g, \" \").trim();\n if (text) return tag + \" \" + quote(text.slice(0, 25));\n if (tag === \"img\") {\n let alt = el.getAttribute(\"alt\");\n if (alt) return \"img \" + quote(alt.trim());\n }\n let role = el.getAttribute && el.getAttribute(\"role\");\n if (role) return tag + \" [role=\" + role + \"]\";\n return tag;\n }\n function siblingText(ctx, el) {\n return el && el.textContent ? el.textContent.replace(/\\s+/g, \" \").trim().slice(0, 40) : \"\";\n }\n function annotateContextText(ctx, el) {\n let own = (el.textContent || \"\").replace(/\\s+/g, \" \").trim().slice(0, 100);\n let before = siblingText(ctx, el.previousElementSibling);\n let after = siblingText(ctx, el.nextElementSibling);\n let parts = [own];\n if (before) parts.push(\"[before: \" + before + \"]\");\n if (after) parts.push(\"[after: \" + after + \"]\");\n return parts.join(\" \").trim();\n }\n function verifyAnchors(ctx, anchors, engine) {\n ctx.anchorSnapshotGeneration++;\n ctx.pendingAnchors = anchors || [];\n if (!ctx.pendingAnchors.length) {\n ctx.checkingAnchors = [];\n scheduleChecking(ctx);\n return;\n }\n let checking = [];\n let verdicts = [];\n if (!engine) {\n for (let i = 0; i < ctx.pendingAnchors.length; i++) {\n if (ctx.pendingAnchors[i].kind === \"text\") {\n engine = createTextAnchorEngine(anchorRoot(ctx));\n break;\n }\n }\n }\n for (let i = 0; i < (anchors || []).length; i++) {\n let anchor = anchors[i] || {};\n let attached = false;\n if (anchor.kind === \"element\") {\n attached = findElement(ctx, anchor) !== null;\n } else if (anchor.kind === \"text\") {\n attached = engine.resolve(anchor) !== null;\n }\n if (attached) delete ctx.checkingDeadlines[anchor.thread];\n verdicts.push({\n thread: anchor.thread,\n attached,\n position_state: attached ? \"attached\" : missingState(ctx, anchor.thread, checking)\n });\n }\n send(ctx, {\n kind: \"anchor-verdicts\",\n verificationId: ctx.pendingVerificationId,\n generation: ++ctx.resolutionGeneration,\n verdicts\n });\n ctx.checkingAnchors = checking;\n scheduleChecking(ctx);\n }\n function findElement(ctx, anchor) {\n if (!anchor.ownText) {\n try {\n return ctx.doc.querySelector(anchor.selector);\n } catch (error) {\n return null;\n }\n }\n let peers = anchor.tagName ? anchorRoot(ctx).getElementsByTagName(anchor.tagName) : anchorRoot(ctx).getElementsByTagName(\"*\");\n let matches = [];\n for (let i = 0; i < peers.length; i++) {\n if (ownText(ctx, peers[i]) === anchor.ownText) matches.push(peers[i]);\n }\n if (matches.length === 0) return null;\n if (matches.length === 1) return matches[0];\n for (let j = 0; j < matches.length; j++) {\n if (annotateContextText(ctx, matches[j]) === anchor.contextText) return matches[j];\n }\n return null;\n }\n function ownText(ctx, el) {\n return (el.textContent || \"\").replace(/\\s+/g, \" \").trim();\n }\n function setAnnotateMode(ctx, enabled) {\n ctx.annotateModeEnabled = enabled === true;\n if (ctx.annotateModeEnabled) {\n ensureAnnotateStyles(ctx);\n } else {\n clearAnnotateHover(ctx);\n }\n }\n function pingElement(ctx, selector) {\n if (typeof selector !== \"string\" || !selector) return;\n let el = null;\n try {\n el = ctx.doc.querySelector(selector);\n } catch (error) {}\n if (!el) return;\n ensureAnnotateStyles(ctx);\n el.scrollIntoView({\n behavior: \"smooth\",\n block: \"center\"\n });\n el.classList.add(\"as-preview-pinged\");\n ctx.win.setTimeout(function() {\n el.classList.remove(\"as-preview-pinged\");\n }, 2500);\n }\n function flashElement(ctx, selector) {\n if (typeof selector !== \"string\" || !selector) return;\n let el = null;\n try {\n el = ctx.doc.querySelector(selector);\n } catch (error) {}\n if (!el) return;\n ensureAnnotateStyles(ctx);\n el.classList.add(\"as-preview-flash\");\n ctx.win.setTimeout(function() {\n el.classList.add(\"as-preview-flash-fade\");\n }, 100);\n ctx.win.setTimeout(function() {\n el.classList.remove(\"as-preview-flash\");\n el.classList.remove(\"as-preview-flash-fade\");\n }, 1100);\n }\n function onAnnotateHover(ctx, event) {\n if (!ctx.annotateModeEnabled) return;\n let target = annotateTargetFrom(ctx, ctx.primordials.targetGet ? ctx.primordials.targetGet(event) : event.target);\n if (target === ctx.annotateHoverElement) return;\n clearAnnotateHover(ctx);\n if (!target) return;\n ctx.annotateHoverElement = target;\n target.classList.add(\"as-preview-annotate-hover\");\n }\n function onAnnotateClick(ctx, event) {\n if (!ctx.annotateModeEnabled) return;\n let target = annotateTargetFrom(ctx, ctx.primordials.targetGet ? ctx.primordials.targetGet(event) : event.target);\n if (!target) return;\n event.preventDefault();\n event.stopPropagation();\n let selected = ctx.win.getSelection();\n if (selected && !selected.isCollapsed && selected.toString().trim()) return;\n let rect = target.getBoundingClientRect();\n send(ctx, {\n kind: \"element-annotate\",\n selector: cssPath(ctx, target),\n label: elementLabel(ctx, target),\n contextText: annotateContextText(ctx, target),\n ownText: ownText(ctx, target),\n tagName: target.tagName,\n rect: {\n top: rect.top,\n left: rect.left,\n width: rect.width,\n height: rect.height\n }\n });\n }\n\n function ensureCommentStyles(ctx) {\n if (ctx.doc.getElementById(highlightStyleId())) return;\n let style = ctx.doc.createElement(\"style\");\n style.setAttribute(anchorIgnoreAttribute(), \"\");\n style.id = highlightStyleId();\n style.textContent = \".ash-comment-highlight-badge::after{content:attr(data-count);}\";\n ctx.doc.head.appendChild(style);\n }\n function clearMarks(ctx, preserveBadges = false) {\n for (let i = 0; i < ctx.badges.length; i++) {\n if (preserveBadges) ctx.reusableBadges.set(ctx.badges[i].badge.dataset.threadId, ctx.badges[i].badge);\n else ctx.badges[i].badge.remove();\n }\n ctx.badges = [];\n ctx.paintedAnchors = [];\n if (typeof ctx.win.CSS !== \"undefined\" && ctx.win.CSS.highlights) {\n ctx.highlightNames.forEach(function(name) {\n ctx.win.CSS.highlights.delete(name);\n });\n }\n ctx.highlightNames = [];\n ctx.textPaints = [];\n let svgOverlays = ctx.doc.querySelectorAll(\".ash-comment-highlight-svg\");\n for (let s = 0; s < svgOverlays.length; s++) svgOverlays[s].remove();\n if (!preserveBadges) ctx.svgActiveThreads = {};\n ctx.appliedHighlightKey = \"\";\n let style = ctx.doc.getElementById(highlightStyleId());\n if (style) style.textContent = \".ash-comment-highlight-badge::after{content:attr(data-count);}\";\n }\n function paintIntact(ctx, highlightsById) {\n let style = ctx.doc.getElementById(highlightStyleId());\n if (ctx.paintedAnchors.length && (!style || !style.isConnected || style.textContent !== textPaintCss(ctx))) return false;\n if (typeof ctx.win.CSS !== \"undefined\" && ctx.win.CSS.highlights) {\n for (let i = 0; i < ctx.textPaints.length; i++) {\n let paint = ctx.textPaints[i];\n if (ctx.win.CSS.highlights.get(paint.name) !== paint.highlight || paint.highlight.size !== paint.ranges.length) return false;\n for (let j = 0; j < paint.ranges.length; j++) {\n if (!paint.highlight.has(paint.ranges[j])) return false;\n }\n }\n }\n for (let i = 0; i < ctx.badges.length; i++) {\n let entry = ctx.badges[i];\n if (!highlightsById.has(entry.highlight.threadId) || !entry.badge.isConnected) return false;\n if (entry.overlays) {\n let shapes = Object.values(entry.overlays);\n for (let j = 0; j < shapes.length; j++) {\n if (!shapes[j].isConnected) return false;\n }\n }\n }\n return ctx.paintedAnchors.every(function(entry) {\n let next = highlightsById.get(entry.highlight.threadId);\n if (!next || next.ranges.length !== entry.ranges.length) return false;\n for (let i = 0; i < entry.ranges.length; i++) {\n let range = entry.ranges[i];\n let current = next.ranges[i];\n if (range.startContainer !== current.startContainer || range.startOffset !== current.startOffset || range.endContainer !== current.endContainer || range.endOffset !== current.endOffset) return false;\n }\n if (entry.groups.length) {\n let groups = svgTextRange(ctx, entry.ranges);\n if (groups.length !== entry.groups.length) return false;\n for (let i = 0; i < groups.length; i++) {\n let group = groups[i];\n let previous = entry.groups[i];\n if (group.text !== previous.text || group.start !== previous.start || group.end !== previous.end) return false;\n }\n }\n return true;\n });\n }\n function setCommentLabels(ctx, labels) {\n if (!labels || typeof labels !== \"object\") return;\n if (typeof labels.openOne === \"string\") ctx.commentLabels.openOne = labels.openOne;\n if (typeof labels.openOther === \"string\") ctx.commentLabels.openOther = labels.openOther;\n if (typeof labels.resolvedOne === \"string\") ctx.commentLabels.resolvedOne = labels.resolvedOne;\n if (typeof labels.resolvedOther === \"string\") ctx.commentLabels.resolvedOther = labels.resolvedOther;\n }\n function commentLabel(ctx, highlight) {\n let count = highlight.count || 1;\n let template = highlight.status === \"resolved\" ? count === 1 ? ctx.commentLabels.resolvedOne : ctx.commentLabels.resolvedOther : count === 1 ? ctx.commentLabels.openOne : ctx.commentLabels.openOther;\n let label = template.replace(/\\{n\\}/g, String(count));\n return highlight.quotedText ? label + \": \" + highlight.quotedText : label;\n }\n function parseRgbColor(ctx, value) {\n if (!value || value === \"transparent\") return null;\n let match = value.match(/^rgba?\\(\\s*([\\d.]+)\\s*,\\s*([\\d.]+)\\s*,\\s*([\\d.]+)(?:\\s*,\\s*([\\d.]+))?\\s*\\)$/);\n if (!match) return null;\n return [\n parseFloat(match[1]),\n parseFloat(match[2]),\n parseFloat(match[3]),\n match[4] === undefined ? 1 : parseFloat(match[4])\n ];\n }\n function rgbToLuminance(ctx, r, g, b) {\n return .2126 * (r / 255) + .7152 * (g / 255) + .0722 * (b / 255);\n }\n function parseColorValue(ctx, value) {\n if (!value || value === \"transparent\") return { type: \"none\" };\n let rgb = parseRgbColor(ctx, value);\n if (rgb) {\n return {\n type: \"rgb\",\n r: rgb[0],\n g: rgb[1],\n b: rgb[2],\n a: rgb[3]\n };\n }\n let modernMatch = value.match(/^oklch\\(\\s*([\\d.]+)(%?)[^/)]*(?:\\/\\s*([\\d.]+)(%?))?/);\n if (modernMatch) {\n let lightness = parseFloat(modernMatch[1]);\n if (modernMatch[2] === \"%\") lightness = lightness / 100;\n let oklchAlpha = modernMatch[3] === undefined ? 1 : parseFloat(modernMatch[3]);\n if (modernMatch[4] === \"%\") oklchAlpha = oklchAlpha / 100;\n return {\n type: \"luminance\",\n value: lightness,\n a: oklchAlpha\n };\n }\n modernMatch = value.match(/^lab\\(\\s*([\\d.]+)(%?)[^/)]*(?:\\/\\s*([\\d.]+)(%?))?/);\n if (modernMatch) {\n let labLightness = parseFloat(modernMatch[1]);\n if (modernMatch[2] === \"%\") labLightness = labLightness / 100;\n else labLightness = labLightness / 100;\n let labAlpha = modernMatch[3] === undefined ? 1 : parseFloat(modernMatch[3]);\n if (modernMatch[4] === \"%\") labAlpha = labAlpha / 100;\n return {\n type: \"luminance\",\n value: labLightness,\n a: labAlpha\n };\n }\n modernMatch = value.match(/^color\\(\\s*(?:display-p3|srgb)\\s+([\\d.]+)\\s+([\\d.]+)\\s+([\\d.]+)[^/)]*(?:\\/\\s*([\\d.]+)(%?))?/);\n if (modernMatch) {\n let colorAlpha = modernMatch[4] === undefined ? 1 : parseFloat(modernMatch[4]);\n if (modernMatch[5] === \"%\") colorAlpha = colorAlpha / 100;\n return {\n type: \"luminance\",\n value: .2126 * parseFloat(modernMatch[1]) + .7152 * parseFloat(modernMatch[2]) + .0722 * parseFloat(modernMatch[3]),\n a: colorAlpha\n };\n }\n return { type: \"none\" };\n }\n function resolveBackgroundRgb(ctx, el) {\n while (el) {\n let parsed = parseColorValue(ctx, ctx.win.getComputedStyle(el).backgroundColor);\n if (parsed.type === \"none\") {\n el = el.parentElement;\n continue;\n }\n if (parsed.type === \"luminance\") {\n if (parsed.a === 0) {\n el = el.parentElement;\n continue;\n }\n let gray = parsed.value * 255;\n if (parsed.a < 1) {\n let ancestorRgb = resolveBackgroundRgb(ctx, el.parentElement);\n let lumAlpha = parsed.a;\n return [\n gray * lumAlpha + ancestorRgb[0] * (1 - lumAlpha),\n gray * lumAlpha + ancestorRgb[1] * (1 - lumAlpha),\n gray * lumAlpha + ancestorRgb[2] * (1 - lumAlpha)\n ];\n }\n return [\n gray,\n gray,\n gray\n ];\n }\n if (parsed.type === \"rgb\") {\n if (parsed.a === 0) {\n el = el.parentElement;\n continue;\n }\n if (parsed.a < 1) {\n let ancestorRgb = resolveBackgroundRgb(ctx, el.parentElement);\n let alpha = parsed.a;\n return [\n parsed.r * alpha + ancestorRgb[0] * (1 - alpha),\n parsed.g * alpha + ancestorRgb[1] * (1 - alpha),\n parsed.b * alpha + ancestorRgb[2] * (1 - alpha)\n ];\n }\n return [\n parsed.r,\n parsed.g,\n parsed.b\n ];\n }\n }\n return [\n 255,\n 255,\n 255\n ];\n }\n function resolvedLuminance(ctx, element) {\n function resolveFrom(el) {\n while (el) {\n let parsed = parseColorValue(ctx, ctx.win.getComputedStyle(el).backgroundColor);\n if (parsed.type === \"none\") {\n el = el.parentElement;\n continue;\n }\n if (parsed.type === \"luminance\") {\n if (parsed.a === 0) {\n el = el.parentElement;\n continue;\n }\n if (parsed.a < 1) {\n let ancestor = resolveFrom(el.parentElement);\n let ancestorLum = ancestor !== null ? ancestor : 1;\n return parsed.value * parsed.a + ancestorLum * (1 - parsed.a);\n }\n return parsed.value;\n }\n if (parsed.type === \"rgb\") {\n if (parsed.a === 0) {\n el = el.parentElement;\n continue;\n }\n if (parsed.a < 1) {\n let ancestorRgb = resolveBackgroundRgb(ctx, el.parentElement);\n let alpha = parsed.a;\n return rgbToLuminance(ctx, parsed.r * alpha + ancestorRgb[0] * (1 - alpha), parsed.g * alpha + ancestorRgb[1] * (1 - alpha), parsed.b * alpha + ancestorRgb[2] * (1 - alpha));\n }\n return rgbToLuminance(ctx, parsed.r, parsed.g, parsed.b);\n }\n }\n return null;\n }\n let result = resolveFrom(element);\n return result !== null ? result : 1;\n }\n function isDarkBackground(ctx, element) {\n return resolvedLuminance(ctx, element) < .5;\n }\n function isDarkBackgroundForSvgText(ctx, text) {\n if (!text) return isDarkBackground(ctx, ctx.doc.body);\n let fill = ctx.win.getComputedStyle(text).fill;\n let parsed = parseColorValue(ctx, fill);\n if (parsed.type === \"rgb\" && parsed.a > 0) return rgbToLuminance(ctx, parsed.r, parsed.g, parsed.b) >= .5;\n if (parsed.type === \"luminance\" && parsed.a > 0) return parsed.value >= .5;\n return isDarkBackground(ctx, text);\n }\n function textPaintCss(ctx) {\n return \".ash-comment-highlight-badge::after{content:attr(data-count);}\" + ctx.textPaints.map(function(paint) {\n return \"::highlight(\" + paint.name + \"){background-color:\" + paint.palette.markBg + \";text-decoration:underline;text-decoration-color:\" + (paint.active ? paint.palette.outline : paint.palette.markUnderline) + \";text-decoration-thickness:\" + (paint.active ? \"3px\" : \"2px\") + \";}\";\n }).join(\"\");\n }\n function refreshTextPaints(ctx) {\n let style = ctx.doc.getElementById(highlightStyleId());\n if (!style) return;\n let css = textPaintCss(ctx);\n if (style.textContent !== css) style.textContent = css;\n }\n function highlightPalette(ctx, isDark, resolved) {\n if (isDark) {\n if (resolved) {\n return {\n markBg: \"rgba(134,197,165,.14)\",\n markUnderline: \"rgba(134,197,165,.75)\",\n outline: \"#86c5a5\",\n badgeBorder: \"rgba(134,197,165,.75)\",\n badgeText: \"#86c5a5\",\n badgeBg: \"#1f2937\",\n badgeTargetBorder: \"#86c5a5\",\n badgeTargetText: \"#fff\",\n badgeTargetBg: \"#86c5a5\"\n };\n }\n return {\n markBg: \"rgba(96,165,250,.16)\",\n markUnderline: \"rgba(96,165,250,.85)\",\n outline: \"#60a5fa\",\n badgeBorder: \"rgba(96,165,250,.85)\",\n badgeText: \"#60a5fa\",\n badgeBg: \"#1f2937\",\n badgeTargetBorder: \"#60a5fa\",\n badgeTargetText: \"#fff\",\n badgeTargetBg: \"#60a5fa\"\n };\n }\n if (resolved) {\n return {\n markBg: \"rgba(68,131,97,.12)\",\n markUnderline: \"rgba(68,131,97,.58)\",\n outline: \"#448361\",\n badgeBorder: \"rgba(68,131,97,.36)\",\n badgeText: \"#448361\",\n badgeBg: \"#fff\",\n badgeTargetBorder: \"#448361\",\n badgeTargetText: \"#fff\",\n badgeTargetBg: \"#448361\"\n };\n }\n return {\n markBg: \"rgba(37,99,235,.16)\",\n markUnderline: \"rgba(37,99,235,.72)\",\n outline: \"#2383e2\",\n badgeBorder: \"rgba(35,131,226,.44)\",\n badgeText: \"#2383e2\",\n badgeBg: \"#fff\",\n badgeTargetBorder: \"#2383e2\",\n badgeTargetText: \"#fff\",\n badgeTargetBg: \"#2383e2\"\n };\n }\n function wrapRange(ctx, highlight, ranges, covered) {\n if (!ranges.length) return;\n let groups = !covered && ctx.doc.querySelector(\"svg text\") ? svgTextRange(ctx, ranges) : [];\n ctx.paintedAnchors.push({\n highlight,\n ranges,\n groups\n });\n if (covered) return;\n let svgWrapped = wrapSvgRange(ctx, highlight, groups);\n ensureCommentStyles(ctx);\n let name = \"ash-comment-\" + ctx.highlightNames.length;\n let palette = highlightPalette(ctx, isDarkBackground(ctx, ranges[0].startContainer.parentElement), highlight.status === \"resolved\");\n if (typeof ctx.win.CSS !== \"undefined\" && ctx.win.CSS.highlights && typeof ctx.win.Highlight !== \"undefined\") {\n let paint = new ctx.win.Highlight(...ranges);\n ctx.win.CSS.highlights.set(name, paint);\n ctx.highlightNames.push(name);\n ctx.textPaints.push({\n name,\n highlight: paint,\n ranges,\n threadId: highlight.threadId,\n palette,\n active: highlight.target,\n target: highlight.target\n });\n refreshTextPaints(ctx);\n }\n if (svgWrapped) return;\n let badge = takeBadge(ctx, highlight);\n badge.setAttribute(anchorIgnoreAttribute(), \"\");\n badge.type = \"button\";\n badge.className = \"ash-comment-highlight-badge\";\n badge.setAttribute(\"aria-label\", commentLabel(ctx, highlight));\n badge.dataset.threadId = highlight.threadId;\n badge.dataset.count = String(highlight.count || 1);\n badge.style.cssText = badgeStyleForHighlight(ctx, highlight, isDarkBackground(ctx, ranges[0].startContainer.parentElement));\n ctx.badges.push({\n badge,\n highlight,\n measure: function() {\n let rects = [];\n let lastElement = null;\n ranges.forEach(function(range) {\n let current = Array.from(range.getClientRects());\n if (current.length) {\n rects.push(...current);\n lastElement = range.startContainer.parentElement;\n }\n });\n return isBadgeAnchorVisible(ctx, lastElement) ? rects : [];\n }\n });\n }\n function missingState(ctx, id, checking) {\n if (!ctx.checkingDeadlines[id]) ctx.checkingDeadlines[id] = Date.now() + 3e3;\n let deadline = ctx.checkingDeadlines[id];\n if (Date.now() < deadline) {\n checking.push(deadline);\n return \"checking\";\n }\n return \"needs-check\";\n }\n function scheduleChecking(ctx, retryDelay = 0) {\n if (ctx.checkingTimer) ctx.win.clearTimeout(ctx.checkingTimer);\n let deadlines = ctx.checkingHighlights.concat(ctx.checkingAnchors);\n if (!deadlines.length) {\n ctx.checkingTimer = undefined;\n return;\n }\n ctx.checkingTimer = ctx.win.setTimeout(function() {\n ctx.checkingTimer = undefined;\n let completed = false;\n try {\n let engine = createTextAnchorEngine(anchorRoot(ctx));\n try {\n applyHighlights(ctx, ctx.pendingHighlights, engine);\n } finally {\n verifyAnchors(ctx, ctx.pendingAnchors, engine);\n }\n completed = true;\n } finally {\n scheduleChecking(ctx, completed ? 0 : Math.min(1e3, Math.max(1, retryDelay * 2)));\n }\n }, Math.max(1, retryDelay, Math.min.apply(null, deadlines) - Date.now()));\n }\n function applyHighlights(ctx, list, engine) {\n ctx.anchorSnapshotGeneration++;\n ctx.pendingHighlights = Array.isArray(list) ? list : [];\n if (!ctx.pendingHighlights.length) {\n ctx.checkingHighlights = [];\n ctx.lastResolutionSignature = \"\";\n scheduleChecking(ctx);\n clearMarks(ctx);\n return;\n }\n let checking = [];\n let forcePaint = !!engine;\n engine = engine || createTextAnchorEngine(anchorRoot(ctx));\n ctx.measuredText = engine.text;\n let results = [];\n let resolvedHighlights = ctx.pendingHighlights.map(function(highlight) {\n let resolved = engine.resolve(highlight);\n return {\n highlight: resolved ? {\n ...highlight,\n ...resolved\n } : highlight,\n resolved,\n ranges: resolved ? engine.ranges(resolved.textStart, resolved.textEnd) : []\n };\n });\n let highlightsById = new Map(resolvedHighlights.map(function(entry) {\n return [entry.highlight.threadId, entry];\n }));\n let paintKey = JSON.stringify(resolvedHighlights.map(function(entry) {\n let palettes = entry.ranges.map(function(range) {\n let element = range.startContainer.parentElement;\n let svgText = element.closest(\"svg text\") && element.closest(\"text,tspan,textPath\");\n return [isDarkBackground(ctx, element), svgText ? isDarkBackgroundForSvgText(ctx, svgText) : null];\n });\n return [\n entry.highlight.threadId,\n entry.highlight.status,\n entry.highlight.target,\n palettes,\n entry.resolved && entry.resolved.textStart,\n entry.resolved && entry.resolved.textEnd\n ];\n }).sort(function(left, right) {\n return left[0].localeCompare(right[0]);\n }));\n let repaint = forcePaint || ctx.appliedHighlightKey !== paintKey || !paintIntact(ctx, highlightsById);\n if (repaint) clearMarks(ctx, true);\n else {\n ctx.paintedAnchors.forEach(function(entry) {\n entry.highlight = highlightsById.get(entry.highlight.threadId).highlight;\n });\n ctx.badges.forEach(function(entry) {\n let highlight = highlightsById.get(entry.highlight.threadId).highlight;\n entry.highlight = highlight;\n if (entry.badge.dataset.threadId !== highlight.threadId) entry.badge.dataset.threadId = highlight.threadId;\n let count = String(highlight.count || 1), label = commentLabel(ctx, highlight);\n if (entry.badge.dataset.count !== count) entry.badge.dataset.count = count;\n if (entry.badge.getAttribute(\"aria-label\") !== label) entry.badge.setAttribute(\"aria-label\", label);\n });\n }\n resolvedHighlights.forEach(function(entry) {\n let highlight = entry.highlight, resolved = entry.resolved;\n let covered = false;\n if (resolved && highlight.status === \"resolved\") {\n for (let i = 0; i < resolvedHighlights.length; i++) {\n let other = resolvedHighlights[i];\n if (other.highlight.status !== \"resolved\" && other.resolved && resolved.textStart < other.resolved.textEnd && other.resolved.textStart < resolved.textEnd) {\n covered = true;\n break;\n }\n }\n }\n if (resolved) {\n delete ctx.checkingDeadlines[highlight.threadId];\n if (repaint) wrapRange(ctx, entry.highlight, entry.ranges, covered);\n }\n results.push({\n threadId: highlight.threadId,\n state: resolved ? \"attached\" : missingState(ctx, highlight.threadId, checking),\n textStart: resolved ? resolved.textStart : null,\n textEnd: resolved ? resolved.textEnd : null,\n textHash: resolved ? engine.hash : null\n });\n });\n ctx.reusableBadges.forEach(function(badge) {\n badge.remove();\n });\n ctx.reusableBadges.clear();\n ctx.appliedHighlightKey = paintKey;\n positionBadges(ctx);\n let signature = JSON.stringify([\n ctx.displayedVersionId,\n ctx.displayedPath,\n results.map(function(result) {\n return [\n result.threadId,\n result.state,\n result.textStart,\n result.textEnd\n ];\n })\n ]);\n if (signature !== ctx.lastResolutionSignature) for (let offset = 0; offset < results.length; offset += 100) {\n send(ctx, {\n kind: \"anchor-resolutions\",\n token: ctx.documentToken,\n versionId: ctx.displayedVersionId,\n targetPath: ctx.displayedPath,\n generation: ++ctx.resolutionGeneration,\n results: results.slice(offset, offset + 100)\n });\n }\n ctx.lastResolutionSignature = signature;\n ctx.checkingHighlights = checking;\n scheduleChecking(ctx);\n }\n function invalidateChangedPaint(ctx, engine) {\n ctx.paintedAnchors = ctx.paintedAnchors.filter(function(entry) {\n let first = entry.ranges[0];\n let last = entry.ranges[entry.ranges.length - 1];\n if (engine.paintedText(first, last) === engine.normalizedQuote(entry.highlight)) return true;\n ctx.appliedHighlightKey = \"\";\n let id = entry.highlight.threadId;\n ctx.textPaints = ctx.textPaints.filter(function(paint) {\n if (paint.threadId !== id) return true;\n if (typeof ctx.win.CSS !== \"undefined\" && ctx.win.CSS.highlights) ctx.win.CSS.highlights.delete(paint.name);\n return false;\n });\n ctx.badges = ctx.badges.filter(function(badgeEntry) {\n if (badgeEntry.badge.dataset.threadId !== id) return true;\n badgeEntry.badge.remove();\n return false;\n });\n ctx.doc.querySelectorAll(\".ash-comment-highlight-svg\").forEach(function(shape) {\n if (shape.dataset.threadId === id) shape.remove();\n });\n return false;\n });\n }\n function scrollToThread(ctx, id) {\n let painted = ctx.paintedAnchors.find(function(entry) {\n return entry.highlight.threadId === id;\n });\n if (painted && painted.ranges.length) {\n let start = painted.ranges[0].startContainer;\n let target = start.nodeType === 1 ? start : start.parentElement;\n if (target) {\n target.scrollIntoView({\n block: \"center\",\n inline: \"nearest\",\n behavior: \"instant\"\n });\n let range = painted.ranges[0];\n for (let ancestor = target; ancestor && ancestor !== ctx.doc.scrollingElement; ancestor = ancestor.parentElement) {\n let style = ctx.win.getComputedStyle(ancestor);\n let scrollX = /(auto|scroll|hidden|overlay)/.test(style.overflowX) && ancestor.scrollWidth > ancestor.clientWidth;\n let scrollY = /(auto|scroll|hidden|overlay)/.test(style.overflowY) && ancestor.scrollHeight > ancestor.clientHeight;\n if (!scrollX && !scrollY) continue;\n let rect = range.getClientRects()[0];\n if (!rect) return;\n let box = ancestor.getBoundingClientRect();\n let scaleX = ancestor.offsetWidth ? box.width / ancestor.offsetWidth : 1;\n let scaleY = ancestor.offsetHeight ? box.height / ancestor.offsetHeight : 1;\n if (!scaleX || !scaleY) continue;\n let left = box.left + ancestor.clientLeft * scaleX;\n let top = box.top + ancestor.clientTop * scaleY;\n let width = ancestor.clientWidth * scaleX;\n let height = ancestor.clientHeight * scaleY;\n let dx = rect.left < left || rect.width > width ? rect.left - left : Math.max(0, rect.right - left - width);\n ancestor.scrollBy({\n left: scrollX ? dx / scaleX : 0,\n top: scrollY ? (rect.top + rect.height / 2 - top - height / 2) / scaleY : 0,\n behavior: \"instant\"\n });\n }\n let visible = range.getClientRects()[0];\n if (visible) {\n let viewportWidth = ctx.doc.documentElement.clientWidth;\n ctx.win.scrollBy({\n left: visible.left < 0 || visible.width > viewportWidth ? visible.left : Math.max(0, visible.right - viewportWidth),\n top: visible.top + visible.height / 2 - ctx.doc.documentElement.clientHeight / 2,\n behavior: \"instant\"\n });\n }\n schedulePositionBadges(ctx);\n }\n return;\n }\n let element = ctx.doc.querySelector(\".ash-comment-highlight[data-thread-id=\\\"\" + ctx.win.CSS.escape(id) + \"\\\"], .ash-comment-highlight-badge[data-thread-id=\\\"\" + ctx.win.CSS.escape(id) + \"\\\"], .ash-comment-highlight-svg[data-thread-id=\\\"\" + ctx.win.CSS.escape(id) + \"\\\"]\");\n if (element) element.scrollIntoView({\n block: \"center\",\n behavior: \"smooth\"\n });\n }\n\n function requestMermaidRendering(ctx) {\n if (ctx.mermaidRequested) return;\n if (!ctx.doc.body || !ctx.doc.body.hasAttribute(\"data-artifact-markdown\")) return;\n let blocks = ctx.doc.querySelectorAll(\"pre code.language-mermaid\");\n let diagrams = [];\n for (let index = 0; index < blocks.length && diagrams.length < 16; index++) {\n let source = blocks[index].textContent || \"\";\n if (!source || source.length > 2e4) continue;\n let pre = blocks[index].closest(\"pre\");\n if (!pre) continue;\n let id = \"artifactshare-mermaid-\" + index;\n ctx.mermaidBlocks[id] = pre;\n diagrams[diagrams.length] = {\n id,\n source\n };\n }\n if (diagrams.length) {\n ctx.mermaidRequested = true;\n send(ctx, {\n kind: \"mermaid-render-request\",\n renderToken: ctx.readyChallenge,\n diagrams\n });\n }\n }\n function installMermaidResults(ctx, renderToken, results) {\n if (renderToken !== ctx.readyChallenge) return;\n if (!Array.isArray(results)) return;\n for (let index = 0; index < results.length; index++) {\n let result = results[index] || {};\n let pre = typeof result.id === \"string\" ? ctx.mermaidBlocks[result.id] : null;\n if (!pre || typeof result.svg !== \"string\" || !result.svg.startsWith(\"<svg\")) continue;\n let svgDocument = new ctx.win.DOMParser().parseFromString(result.svg, \"image/svg+xml\");\n let svg = svgDocument.documentElement;\n if (svg.localName !== \"svg\" || svg.namespaceURI !== \"http://www.w3.org/2000/svg\" || svgDocument.querySelector(\"parsererror\")) continue;\n let container = ctx.doc.createElement(\"div\");\n container.className = \"mermaid-diagram\";\n container.appendChild(ctx.doc.importNode(svg, true));\n pre.dataset.mermaidRendered = \"true\";\n pre.hidden = true;\n pre.before(container);\n delete ctx.mermaidBlocks[result.id];\n }\n schedulePositionBadges(ctx);\n }\n\n function send(ctx, message) {\n try {\n let payload = createMessagePayload(ctx.primordials, message);\n ctx.primordials.savedPostMessage(ctx.primordials.savedParent, payload, \"*\");\n } catch (e) {}\n }\n function ready(ctx) {\n if (ctx.readyChallenge && ctx.documentToken) {\n send(ctx, {\n kind: \"ready\",\n challenge: ctx.readyChallenge,\n token: ctx.documentToken\n });\n reportHash(ctx, true);\n }\n }\n function onReadyCheck(ctx, event) {\n let message = event && event.data;\n if (!event || event.source !== ctx.primordials.savedParent || !message || message.source !== \"artifactshare-parent\" || message.kind !== \"ready-check\") return;\n if (typeof message.challenge !== \"string\" || !message.challenge) return;\n ctx.readyChallenge = message.challenge;\n for (let index = 0; index < ctx.pendingCspViolationCount; index++) {\n send(ctx, ctx.pendingCspViolations[index]);\n }\n ctx.pendingCspViolations = ctx.primordials.objectCreate(null);\n ctx.pendingCspViolationCount = 0;\n requestMermaidRendering(ctx);\n ready(ctx);\n }\n function readEventValue(ctx, getter, event) {\n if (!getter) return null;\n try {\n return getter(event);\n } catch (e) {\n return null;\n }\n }\n function createMessagePayload(primitives, message) {\n const payload = primitives.objectCreate(null);\n payload.source = \"artifactshare\";\n const keys = primitives.objectKeys(message);\n for (let index = 0; index < keys.length; index++) {\n const key = keys[index];\n payload[key] = message[key];\n }\n return payload;\n }\n function installMessageListener(ctx) {\n ctx.primordials.savedAddEventListener(\"message\", function(event) {\n let data = event.data || {};\n if (event.source !== ctx.primordials.savedParent || data.source !== \"artifactshare-parent\") {\n return;\n }\n if (data.kind === \"ready-check\") {\n onReadyCheck(ctx, event);\n ctx.displayedVersionId = data.versionId || ctx.displayedVersionId;\n ctx.displayedPath = data.targetPath || ctx.displayedPath;\n ctx.textAnchorsEnabled = data.textAnchorsEnabled === true;\n setCommentLabels(ctx, data.commentLabels);\n } else if (data.kind === \"external-link-policy\" && (data.mode === \"parent\" || data.mode === \"direct\")) {\n ctx.externalLinkPolicyMode = data.mode;\n } else if (data.kind === \"comment-highlights\") {\n ctx.textAnchorsEnabled = data.textAnchorsEnabled === true;\n setCommentLabels(ctx, data.commentLabels);\n ctx.displayedVersionId = data.versionId || null;\n ctx.displayedPath = data.targetPath || null;\n applyHighlights(ctx, data.highlights);\n } else if (data.kind === \"scroll-to-comment\") {\n scrollToThread(ctx, data.threadId);\n } else if (data.kind === \"mermaid-rendered\") {\n installMermaidResults(ctx, data.renderToken, data.results);\n } else if (data.kind === \"annotate-mode\") {\n setAnnotateMode(ctx, data.enabled);\n } else if (data.kind === \"element-ping\") {\n pingElement(ctx, data.selector);\n } else if (data.kind === \"element-flash\") {\n flashElement(ctx, data.selector);\n } else if (data.kind === \"verify-anchors\") {\n if (Number.isSafeInteger(ctx.pendingVerificationId) && Number.isSafeInteger(data.verificationId) && data.verificationId < ctx.pendingVerificationId) return;\n ctx.pendingVerificationId = data.verificationId;\n verifyAnchors(ctx, data.anchors);\n }\n });\n }\n\n function reportHash(ctx, force = false) {\n try {\n if (ctx.readyChallenge && ctx.documentToken) {\n const hash = ctx.win.location.hash;\n const path = ctx.win.location.pathname;\n if (!force && ctx.lastHash === hash && ctx.lastHashPath === path) return;\n ctx.lastHash = hash;\n ctx.lastHashPath = path;\n send(ctx, {\n kind: \"hash-changed\",\n hash,\n path,\n token: ctx.documentToken\n });\n }\n } catch (e) {}\n }\n function installHashTracking(ctx) {\n ctx.primordials.addEventListener(ctx.win, \"hashchange\", () => reportHash(ctx));\n wrapHistory(ctx, \"pushState\");\n wrapHistory(ctx, \"replaceState\");\n }\n function wrapHistory(ctx, method) {\n const prototype = ctx.primordials.getPrototypeOf(ctx.win.history);\n const original = prototype[method];\n prototype[method] = function(...args) {\n const result = ctx.primordials.reflectApply(original, this, args);\n reportHash(ctx);\n return result;\n };\n }\n\n function installCspViolations(ctx) {\n ctx.doc.addEventListener(VIOLATION_REPORTER_MARKER, function(event) {\n const message = {\n kind: \"csp-violation\",\n directive: event.violatedDirective || event.effectiveDirective,\n blockedURI: event.blockedURI || \"inline\",\n sourceFile: event.sourceFile || null,\n lineNumber: event.lineNumber || null\n };\n if (typeof event.sample === \"string\" && event.sample.length > 0) {\n let sample = \"\";\n for (let index = 0; index < event.sample.length && index < 80; index++) sample += event.sample[index];\n message.sample = sample;\n }\n if (event.disposition === \"enforce\" || event.disposition === \"report\") message.disposition = event.disposition;\n if (ctx.readyChallenge === \"\") {\n if (ctx.pendingCspViolationCount < 100) {\n ctx.pendingCspViolations[ctx.pendingCspViolationCount] = message;\n ctx.pendingCspViolationCount += 1;\n }\n return;\n }\n send(ctx, message);\n });\n }\n\n function updateMarkdownToc(ctx) {\n let links = ctx.doc.querySelectorAll(\".md-toc a[href^=\\\"#\\\"]\");\n if (!links.length) return;\n let activeId = null;\n for (let index = 0; index < links.length; index++) {\n let id = links[index].getAttribute(\"href\").slice(1);\n let heading = ctx.doc.getElementById(id);\n if (heading && heading.getBoundingClientRect().top <= 96) activeId = id;\n }\n if (!activeId) activeId = links[0].getAttribute(\"href\").slice(1);\n for (let linkIndex = 0; linkIndex < links.length; linkIndex++) {\n if (links[linkIndex].getAttribute(\"href\").slice(1) === activeId) {\n links[linkIndex].setAttribute(\"aria-current\", \"location\");\n } else {\n links[linkIndex].removeAttribute(\"aria-current\");\n }\n }\n }\n function installCodeCopy(ctx) {\n ctx.doc.addEventListener(\"click\", function(event) {\n let target = event.target;\n let button = target && target.closest && target.closest(\"[data-code-copy]\");\n if (!button) return;\n let block = button.closest(\".md-code-block\");\n let code = block && block.querySelector(\"pre code\");\n if (!code) return;\n event.preventDefault();\n event.stopPropagation();\n let copied = function() {\n button.textContent = \"Copied\";\n button.setAttribute(\"aria-label\", \"Code copied\");\n ctx.win.setTimeout(function() {\n button.textContent = \"Copy\";\n button.setAttribute(\"aria-label\", \"Copy code\");\n }, 1500);\n };\n let fallback = function() {\n let textarea = ctx.doc.createElement(\"textarea\");\n textarea.setAttribute(anchorIgnoreAttribute(), \"\");\n textarea.value = code.textContent || \"\";\n textarea.style.position = \"fixed\";\n textarea.style.opacity = \"0\";\n ctx.doc.body.appendChild(textarea);\n textarea.select();\n try {\n if (ctx.doc.execCommand(\"copy\")) copied();\n } catch (error) {}\n textarea.remove();\n };\n if (ctx.win.navigator.clipboard && ctx.win.navigator.clipboard.writeText) {\n ctx.win.navigator.clipboard.writeText(code.textContent || \"\").then(copied, fallback);\n } else {\n fallback();\n }\n });\n }\n\n function rebuildAfterMutations(ctx) {\n let hasText = ctx.pendingHighlights.length > 0;\n for (let i = 0; !hasText && i < ctx.pendingAnchors.length; i++) {\n if (ctx.pendingAnchors[i].kind === \"text\") hasText = true;\n }\n if (!hasText) {\n verifyAnchors(ctx, ctx.pendingAnchors);\n return;\n }\n let engine = createTextAnchorEngine(anchorRoot(ctx));\n if (engine.text === ctx.measuredText) {\n ctx.win.clearTimeout(ctx.resolveTimer);\n ctx.resolveStartedAt = 0;\n try {\n applyHighlights(ctx, ctx.pendingHighlights, engine);\n } finally {\n verifyAnchors(ctx, ctx.pendingAnchors, engine);\n }\n } else {\n invalidateChangedPaint(ctx, engine);\n ctx.win.clearTimeout(ctx.resolveTimer);\n if (!ctx.resolveStartedAt) ctx.resolveStartedAt = Date.now();\n let snapshotGeneration = ctx.anchorSnapshotGeneration;\n ctx.resolveTimer = ctx.win.setTimeout(function() {\n ctx.resolveStartedAt = 0;\n if (snapshotGeneration !== ctx.anchorSnapshotGeneration) engine = createTextAnchorEngine(anchorRoot(ctx));\n try {\n applyHighlights(ctx, ctx.pendingHighlights, engine);\n } finally {\n verifyAnchors(ctx, ctx.pendingAnchors, engine);\n }\n }, Math.min(300, Math.max(0, 1e3 - (Date.now() - ctx.resolveStartedAt))));\n }\n }\n function handleMutations(ctx, records) {\n let root = anchorRoot(ctx);\n let rootReplaced = root !== ctx.observedAnchorRoot;\n ctx.observedAnchorRoot = root;\n let exclusionChanged = false;\n for (let recordIndex = 0; recordIndex < records.length; recordIndex++) {\n const record = records[recordIndex];\n if (record.type === \"attributes\" && (record.attributeName === anchorIgnoreAttribute() || record.attributeName === commentUiAttribute() || record.attributeName === \"class\")) {\n exclusionChanged = true;\n break;\n }\n }\n if (rootReplaced || exclusionChanged) ctx.anchorSnapshotGeneration++;\n if (!root || !ctx.doc.body || !ctx.pendingHighlights.length && !ctx.pendingAnchors.length) return;\n let hasRelevant = false;\n let hasRelevantContent = false;\n for (let recordIndex = 0; recordIndex < records.length; recordIndex++) {\n const record = records[recordIndex];\n if (record.type !== \"attributes\" && !root.contains(record.target)) continue;\n let element = record.target.nodeType === 1 ? record.target : record.target.parentElement;\n if (element && ctx.primordials.closest(element, ignoredMutationSelector())) continue;\n if (record.type === \"childList\") {\n let hasContentNode = false;\n for (let group = 0; group < 2; group++) {\n const nodes = group === 0 ? record.addedNodes : record.removedNodes;\n for (let index = 0; index < nodes.length; index++) {\n const node = nodes[index];\n if (node.nodeType !== 1 || !ctx.primordials.hasAttribute(node, anchorIgnoreAttribute()) && node.id !== highlightStyleId()) hasContentNode = true;\n }\n }\n if (!hasContentNode) continue;\n }\n hasRelevant = true;\n if (record.type !== \"attributes\") hasRelevantContent = true;\n }\n if (!rootReplaced && !hasRelevant) return;\n schedulePositionBadges(ctx);\n if (rootReplaced || hasRelevantContent) {\n rebuildAfterMutations(ctx);\n }\n }\n function installAnchorObserver(ctx) {\n ctx.observedAnchorRoot = anchorRoot(ctx);\n const observer = new ctx.win.MutationObserver((records) => handleMutations(ctx, records));\n ctx.anchorObserver = observer;\n observer.observe(ctx.doc.documentElement, {\n subtree: true,\n childList: true,\n characterData: true,\n attributes: true\n });\n return observer;\n }\n\n function capturePrimordials(win) {\n const savedParent = win.parent;\n const reflectApply = win.Reflect.apply;\n const savedPostMessage = win.Function.prototype.call.bind(savedParent.postMessage);\n const savedAddEventListener = win.addEventListener.bind(win);\n const trustedGetter = win.Object.getOwnPropertyDescriptor(win.Event.prototype, \"isTrusted\");\n const targetGetter = win.Object.getOwnPropertyDescriptor(win.Event.prototype, \"target\");\n const defaultPreventedGetter = win.Object.getOwnPropertyDescriptor(win.Event.prototype, \"defaultPrevented\");\n const persistedGetter = win.PageTransitionEvent ? win.Object.getOwnPropertyDescriptor(win.PageTransitionEvent.prototype, \"persisted\") : undefined;\n const buttonGetter = win.Object.getOwnPropertyDescriptor(win.MouseEvent.prototype, \"button\");\n const metaKeyGetter = win.Object.getOwnPropertyDescriptor(win.MouseEvent.prototype, \"metaKey\");\n const ctrlKeyGetter = win.Object.getOwnPropertyDescriptor(win.MouseEvent.prototype, \"ctrlKey\");\n const shiftKeyGetter = win.Object.getOwnPropertyDescriptor(win.MouseEvent.prototype, \"shiftKey\");\n const altKeyGetter = win.Object.getOwnPropertyDescriptor(win.MouseEvent.prototype, \"altKey\");\n const trustedGet = trustedGetter && trustedGetter.get ? win.Function.prototype.call.bind(trustedGetter.get) : null;\n const targetGet = targetGetter && targetGetter.get ? win.Function.prototype.call.bind(targetGetter.get) : null;\n const defaultPreventedGet = defaultPreventedGetter && defaultPreventedGetter.get ? win.Function.prototype.call.bind(defaultPreventedGetter.get) : null;\n const persistedGet = persistedGetter && persistedGetter.get ? win.Function.prototype.call.bind(persistedGetter.get) : null;\n const buttonGet = buttonGetter && buttonGetter.get ? win.Function.prototype.call.bind(buttonGetter.get) : null;\n const metaKeyGet = metaKeyGetter && metaKeyGetter.get ? win.Function.prototype.call.bind(metaKeyGetter.get) : null;\n const ctrlKeyGet = ctrlKeyGetter && ctrlKeyGetter.get ? win.Function.prototype.call.bind(ctrlKeyGetter.get) : null;\n const shiftKeyGet = shiftKeyGetter && shiftKeyGetter.get ? win.Function.prototype.call.bind(shiftKeyGetter.get) : null;\n const altKeyGet = altKeyGetter && altKeyGetter.get ? win.Function.prototype.call.bind(altKeyGetter.get) : null;\n const preventDefault = win.Function.prototype.call.bind(win.Event.prototype.preventDefault);\n const addEventListener = win.Function.prototype.call.bind(win.EventTarget.prototype.addEventListener);\n const rangeToString = win.Function.prototype.call.bind(win.Range.prototype.toString);\n const arrayMap = win.Function.prototype.call.bind(win.Array.prototype.map);\n const weakMapDelete = win.Function.prototype.call.bind(win.WeakMap.prototype.delete);\n const weakMapGet = win.Function.prototype.call.bind(win.WeakMap.prototype.get);\n const weakMapSet = win.Function.prototype.call.bind(win.WeakMap.prototype.set);\n const defineProperty = win.Object.defineProperty;\n const objectCreate = win.Object.create;\n const objectKeys = win.Object.keys;\n const closest = win.Function.prototype.call.bind(win.Element.prototype.closest);\n const getAttribute = win.Function.prototype.call.bind(win.Element.prototype.getAttribute);\n const hasAttribute = win.Function.prototype.call.bind(win.Element.prototype.hasAttribute);\n return {\n savedParent,\n reflectApply,\n getPrototypeOf: win.Object.getPrototypeOf,\n savedPostMessage,\n savedAddEventListener,\n trustedGetter,\n targetGetter,\n defaultPreventedGetter,\n buttonGetter,\n metaKeyGetter,\n ctrlKeyGetter,\n shiftKeyGetter,\n altKeyGetter,\n trustedGet,\n targetGet,\n defaultPreventedGet,\n persistedGet,\n buttonGet,\n metaKeyGet,\n ctrlKeyGet,\n shiftKeyGet,\n altKeyGet,\n preventDefault,\n addEventListener,\n rangeToString,\n arrayMap,\n weakMapDelete,\n weakMapGet,\n weakMapSet,\n defineProperty,\n objectCreate,\n objectKeys,\n closest,\n getAttribute,\n hasAttribute\n };\n }\n\n function createReporterState(win, primordials = capturePrimordials(win)) {\n return {\n win,\n doc: win.document,\n primordials,\n documentToken: \"\",\n readyChallenge: \"\",\n lastHash: null,\n lastHashPath: null,\n pendingCspViolations: primordials.objectCreate(null),\n pendingCspViolationCount: 0,\n externalLinkPolicyMode: \"parent\",\n pendingLinkClicks: new win.WeakMap(),\n highlightNames: [],\n textPaints: [],\n pendingHighlights: [],\n pendingAnchors: [],\n measuredText: null,\n anchorSnapshotGeneration: 0,\n paintedAnchors: [],\n resolveStartedAt: 0,\n resolveTimer: undefined,\n checkingTimer: undefined,\n checkingDeadlines: {},\n checkingHighlights: [],\n checkingAnchors: [],\n pendingVerificationId: null,\n resolutionGeneration: 0,\n lastResolutionSignature: \"\",\n displayedVersionId: null,\n displayedPath: null,\n badges: [],\n badgeOffsets: {},\n badgeDragged: false,\n appliedHighlightKey: \"\",\n textAnchorsEnabled: false,\n mermaidBlocks: primordials.objectCreate(null),\n mermaidRequested: false,\n commentLabels: {\n openOne: \"Open 1 unresolved comment on this text\",\n openOther: \"Open {n} unresolved comments on this text\",\n resolvedOne: \"Open 1 resolved comment on this text\",\n resolvedOther: \"Open {n} resolved comments on this text\"\n },\n reusableBadges: new win.Map(),\n svgActiveThreads: {},\n svgOverlayStyles: new win.WeakMap(),\n badgePositionFrame: 0,\n annotateModeEnabled: false,\n annotateHoverElement: null,\n readyCount: 0,\n observedAnchorRoot: win.document.body,\n anchorObserver: null,\n readyInterval: 0\n };\n }\n\n function installReporter(win) {\n if (win.parent === win) return;\n const primordials = capturePrimordials(win);\n const ctx = createReporterState(win, primordials);\n try {\n let random = new win.Uint8Array(32);\n ctx.win.crypto.getRandomValues(random);\n ctx.documentToken = ctx.primordials.arrayMap(random, function(byte) {\n return byte.toString(16).padStart(2, \"0\");\n }).join(\"\");\n } catch (e) {\n ctx.documentToken = \"\";\n }\n installHashTracking(ctx);\n installAnchorObserver(ctx);\n ctx.primordials.addEventListener(ctx.win, \"pagehide\", function(event) {\n if (readEventValue(ctx, ctx.primordials.persistedGet, event) === true) return;\n ctx.anchorObserver.disconnect();\n ctx.win.clearTimeout(ctx.resolveTimer);\n ctx.win.clearTimeout(ctx.checkingTimer);\n ctx.win.cancelAnimationFrame(ctx.badgePositionFrame);\n clearMarks(ctx);\n });\n ctx.doc.addEventListener(\"click\", function(event) {\n let selection = ctx.win.getSelection();\n if (selection && !selection.isCollapsed) return;\n let badge = hitComment(ctx, event);\n if (!badge) return;\n selectThreadFromElement(ctx, badge, rectFromPointer(ctx, event, badge.getBoundingClientRect()));\n event.preventDefault();\n event.stopPropagation();\n });\n ctx.primordials.addEventListener(ctx.doc, \"mousemove\", (event) => onAnnotateHover(ctx, event), true);\n ctx.primordials.addEventListener(ctx.doc, \"mouseover\", (event) => onAnnotateHover(ctx, event), true);\n ctx.primordials.addEventListener(ctx.doc, \"click\", (event) => onAnnotateClick(ctx, event), true);\n installMessageListener(ctx);\n ctx.doc.addEventListener(\"mouseup\", function() {\n ctx.win.setTimeout(() => sendSelection(ctx), 0);\n });\n ctx.doc.addEventListener(\"keyup\", function() {\n ctx.win.setTimeout(() => sendSelection(ctx), 0);\n });\n installCodeCopy(ctx);\n ctx.primordials.addEventListener(ctx.win, \"click\", (event) => prepareLinkClick(ctx, event), true);\n ctx.primordials.addEventListener(ctx.win, \"click\", (event) => finishLinkClick(ctx, event));\n ctx.doc.addEventListener(\"pointerdown\", (event) => sendOutsidePointerDown(ctx, event));\n installCspViolations(ctx);\n ctx.win.addEventListener(\"resize\", () => schedulePositionBadges(ctx));\n ctx.win.addEventListener(\"scroll\", () => schedulePositionBadges(ctx), true);\n ctx.win.addEventListener(\"load\", function() {\n if (!ctx.pendingHighlights.length && !ctx.pendingAnchors.length) return;\n let engine = createTextAnchorEngine(anchorRoot(ctx));\n try {\n applyHighlights(ctx, ctx.pendingHighlights, engine);\n } finally {\n verifyAnchors(ctx, ctx.pendingAnchors, engine);\n }\n });\n ctx.win.addEventListener(\"load\", () => schedulePositionBadges(ctx));\n ctx.win.addEventListener(\"load\", () => updateMarkdownToc(ctx));\n ctx.win.addEventListener(\"scroll\", () => updateMarkdownToc(ctx), { passive: true });\n if (ctx.doc.fonts && ctx.doc.fonts.ready) {\n ctx.doc.fonts.ready.then(() => schedulePositionBadges(ctx));\n }\n ctx.readyInterval = ctx.win.setInterval(function() {\n ready(ctx);\n if (++ctx.readyCount >= 20) ctx.win.clearInterval(ctx.readyInterval);\n }, 100);\n ready(ctx);\n return ctx;\n }\n\n installReporter(window);\n\n})();";
6321
+ const VIOLATION_REPORTER_SCRIPT_BODY = "(function() {\n\n\"use strict\";\n const VIOLATION_REPORTER_MARKER = \"securitypolicyviolation\";\n const READY_MESSAGE_REPEAT_COUNT = 20;\n const READY_MESSAGE_REPEAT_INTERVAL_MS = 100;\n const READY_CHECK_MESSAGE_SOURCE = \"artifactshare-parent\";\n const READY_CHECK_MESSAGE_KIND = \"ready-check\";\n\n const ANCHOR_IGNORE_ATTRIBUTE = \"data-anchor-ignore\";\n const COMMENT_UI_ATTRIBUTE = \"data-comment-ui\";\n const EXCLUSION_CLASS_ATTRIBUTE = \"class\";\n const HIGHLIGHT_STYLE_ID = \"ash-comment-highlight-style\";\n const TEXT_ANCHOR_EXCLUDED_SELECTOR = \"script,style,noscript,template,textarea,select,[\" + ANCHOR_IGNORE_ATTRIBUTE + \"],[\" + COMMENT_UI_ATTRIBUTE + \"],.ash-comment-highlight-badge,.mermaid-diagram\";\n const IGNORED_MUTATION_SELECTOR = \"[\" + ANCHOR_IGNORE_ATTRIBUTE + \"],#\" + HIGHLIGHT_STYLE_ID;\n const COMMENT_UI_SELECTOR = \"[\" + COMMENT_UI_ATTRIBUTE + \"]\";\n function anchorIgnoreAttribute() {\n return ANCHOR_IGNORE_ATTRIBUTE;\n }\n function commentUiAttribute() {\n return COMMENT_UI_ATTRIBUTE;\n }\n function highlightStyleId() {\n return HIGHLIGHT_STYLE_ID;\n }\n function ignoredMutationSelector() {\n return IGNORED_MUTATION_SELECTOR;\n }\n function commentUiSelector() {\n return COMMENT_UI_SELECTOR;\n }\n function createTextAnchorEngine(root) {\n const document = root.ownerDocument;\n const units = [];\n let text = \"\";\n let previousBlock = null;\n const blockTags = new Set(\"p div li ul ol dl dt dd h1 h2 h3 h4 h5 h6 pre blockquote table thead tbody tfoot tr td th caption section article aside header footer nav main figure figcaption details summary hr br address form fieldset\".split(\" \"));\n const walker = document.createTreeWalker(root, 4 | 1);\n let node;\n while (node = walker.nextNode()) {\n const element = node.nodeType === 1 ? node : node.parentElement;\n if (!element || element.closest(TEXT_ANCHOR_EXCLUDED_SELECTOR)) continue;\n if (node.nodeType === 1) {\n if ((node.localName === \"br\" || node.localName === \"hr\") && text && !text.endsWith(\" \")) {\n text += \" \";\n units.push([]);\n }\n continue;\n }\n const parent = node.parentElement;\n let block = parent;\n while (block && block !== root && !blockTags.has(block.localName)) block = block.parentElement;\n if (text && previousBlock !== block && !text.endsWith(\" \")) {\n text += \" \";\n units.push([]);\n }\n previousBlock = block;\n const value = node.nodeValue || \"\";\n for (let offset = 0; offset < value.length; offset++) {\n const segment = {\n node,\n start: offset,\n end: offset + 1\n };\n if (/\\s/.test(value[offset])) {\n if (!text) continue;\n if (text.endsWith(\" \")) units[units.length - 1].push(segment);\n else {\n text += \" \";\n units.push([segment]);\n }\n } else {\n text += value[offset];\n units.push([segment]);\n }\n }\n }\n function textHash(value) {\n const bytes = new TextEncoder().encode(value);\n const words = new Uint32Array(Math.ceil((bytes.length + 9) / 64) * 16);\n for (let i = 0; i < bytes.length; i++) words[i >>> 2] = words[i >>> 2] | bytes[i] << 24 - i % 4 * 8;\n words[bytes.length >>> 2] = words[bytes.length >>> 2] | 128 << 24 - bytes.length % 4 * 8;\n words[words.length - 2] = Math.floor(bytes.length / 536870912);\n words[words.length - 1] = bytes.length * 8;\n const h = [\n 1779033703,\n 3144134277,\n 1013904242,\n 2773480762,\n 1359893119,\n 2600822924,\n 528734635,\n 1541459225\n ];\n const k = [\n 1116352408,\n 1899447441,\n 3049323471,\n 3921009573,\n 961987163,\n 1508970993,\n 2453635748,\n 2870763221,\n 3624381080,\n 310598401,\n 607225278,\n 1426881987,\n 1925078388,\n 2162078206,\n 2614888103,\n 3248222580,\n 3835390401,\n 4022224774,\n 264347078,\n 604807628,\n 770255983,\n 1249150122,\n 1555081692,\n 1996064986,\n 2554220882,\n 2821834349,\n 2952996808,\n 3210313671,\n 3336571891,\n 3584528711,\n 113926993,\n 338241895,\n 666307205,\n 773529912,\n 1294757372,\n 1396182291,\n 1695183700,\n 1986661051,\n 2177026350,\n 2456956037,\n 2730485921,\n 2820302411,\n 3259730800,\n 3345764771,\n 3516065817,\n 3600352804,\n 4094571909,\n 275423344,\n 430227734,\n 506948616,\n 659060556,\n 883997877,\n 958139571,\n 1322822218,\n 1537002063,\n 1747873779,\n 1955562222,\n 2024104815,\n 2227730452,\n 2361852424,\n 2428436474,\n 2756734187,\n 3204031479,\n 3329325298\n ];\n const rotate = (x, n) => x >>> n | x << 32 - n;\n const w = new Uint32Array(64);\n for (let offset = 0; offset < words.length; offset += 16) {\n for (let i = 0; i < 64; i++) {\n if (i < 16) w[i] = words[offset + i];\n else {\n const x = w[i - 15], y = w[i - 2];\n w[i] = w[i - 16] + (rotate(x, 7) ^ rotate(x, 18) ^ x >>> 3) + w[i - 7] + (rotate(y, 17) ^ rotate(y, 19) ^ y >>> 10);\n }\n }\n let [a, b, c, d, e, f, g, j] = h;\n for (let i = 0; i < 64; i++) {\n const t1 = j + (rotate(e, 6) ^ rotate(e, 11) ^ rotate(e, 25)) + (e & f ^ ~e & g) + k[i] + w[i] | 0;\n const t2 = (rotate(a, 2) ^ rotate(a, 13) ^ rotate(a, 22)) + (a & b ^ a & c ^ b & c) | 0;\n j = g;\n g = f;\n f = e;\n e = d + t1 | 0;\n d = c;\n c = b;\n b = a;\n a = t1 + t2 | 0;\n }\n const next = [\n a,\n b,\n c,\n d,\n e,\n f,\n g,\n j\n ];\n for (let i = 0; i < 8; i++) h[i] = h[i] + next[i] | 0;\n }\n return h.map((word) => (word >>> 0).toString(16).padStart(8, \"0\")).join(\"\");\n }\n const hash = textHash(text);\n function hits(haystack, needle) {\n const found = [];\n if (needle) for (let at = haystack.indexOf(needle); at >= 0; at = haystack.indexOf(needle, at + 1)) found.push(at);\n return found;\n }\n function normalizedQuote(selector) {\n return selector.selectorFormat === \"normalized-v1\" ? selector.quotedText : selector.quotedText.replace(/\\s+/g, \" \").trim();\n }\n function resolve(selector) {\n if (!selector || typeof selector.quotedText !== \"string\" || selector.prefixText != null && typeof selector.prefixText !== \"string\" || selector.suffixText != null && typeof selector.suffixText !== \"string\") return null;\n const modern = selector.selectorFormat === \"normalized-v1\";\n const legacy = !selector.selectorFormat;\n const normalize = (value) => modern ? value : legacy ? value.replace(/\\s+/g, \" \").trim() : value.replace(/\\s+/g, \" \");\n const quote = normalizedQuote(selector);\n const prefix = normalize(selector.prefixText || \"\");\n const suffix = normalize(selector.suffixText || \"\");\n if (!quote.trim()) return null;\n if (legacy || selector.selectorFormat === \"quote-v1\") {\n const positions = new Set();\n for (const before of prefix && !prefix.endsWith(\" \") ? [\"\", \" \"] : [\"\"]) for (const after of suffix && !suffix.startsWith(\" \") ? [\"\", \" \"] : [\"\"]) for (const at of hits(text, prefix + before + quote + after + suffix)) positions.add(at + prefix.length + before.length);\n if (positions.size !== 1) return null;\n const start = positions.values().next().value;\n return {\n textStart: start,\n textEnd: start + quote.length\n };\n }\n const matches = hits(text, prefix + quote + suffix);\n const hit = matches.length === 1 ? matches[0] + prefix.length : -1;\n const context = prefix + quote + suffix;\n const start = selector.textStart, end = selector.textEnd;\n if (modern && typeof start === \"number\" && Number.isInteger(start) && typeof end === \"number\" && Number.isInteger(end) && start >= prefix.length && end - start === quote.length && text.slice(start, end) === quote && text.slice(start - prefix.length, end + suffix.length) === context && (hit >= 0 || selector.textHash === hash)) return {\n textStart: start,\n textEnd: end\n };\n if (hit >= 0 && !selector.ambiguousAtCreation) return {\n textStart: hit,\n textEnd: hit + quote.length\n };\n return null;\n }\n function ranges(start, end) {\n const segments = [];\n for (const unit of units.slice(start, end)) for (const segment of unit) {\n const last = segments[segments.length - 1];\n if (last && last.node === segment.node && last.end === segment.start) last.end = segment.end;\n else segments.push({ ...segment });\n }\n return segments.map((segment) => {\n const range = document.createRange();\n range.setStart(segment.node, segment.start);\n range.setEnd(segment.node, segment.end);\n return range;\n });\n }\n const sourceIndexes = new WeakMap();\n const sourceSegments = [];\n units.forEach((segments, index) => {\n for (const segment of segments) {\n sourceSegments.push({\n segment,\n index\n });\n let offsets = sourceIndexes.get(segment.node);\n if (!offsets) sourceIndexes.set(segment.node, offsets = []);\n offsets[segment.start] = index;\n }\n });\n function paintedText(first, last) {\n const start = sourceIndexes.get(first.startContainer)?.[first.startOffset];\n const end = sourceIndexes.get(last.endContainer)?.[last.endOffset - 1];\n return start === undefined || end === undefined || start > end ? null : text.slice(start, end + 1).trim();\n }\n function mappedSlice(range) {\n if (!root.contains(range.startContainer) || !root.contains(range.endContainer) || range.collapsed) return null;\n function boundary(boundaryNode, offset, isEnd) {\n const direct = sourceIndexes.get(boundaryNode)?.[isEnd ? offset - 1 : offset];\n if (direct !== undefined) return direct + (isEnd ? 1 : 0);\n const point = document.createRange();\n point.setStart(boundaryNode, offset);\n point.collapse(true);\n let low = 0, high = sourceSegments.length;\n while (low < high) {\n const mid = low + high >>> 1;\n const entry = sourceSegments[mid];\n const comparison = point.comparePoint(entry.segment.node, isEnd ? entry.segment.start : entry.segment.end);\n if (isEnd ? comparison < 0 : comparison <= 0) low = mid + 1;\n else high = mid;\n }\n return isEnd ? low ? sourceSegments[low - 1].index + 1 : 0 : low < sourceSegments.length ? sourceSegments[low].index : text.length;\n }\n let start = boundary(range.startContainer, range.startOffset, false);\n let end = boundary(range.endContainer, range.endOffset, true);\n while (start >= 0 && start < end && /\\s/.test(text[start])) start++;\n while (end > start && /\\s/.test(text[end - 1])) end--;\n if (start < 0 || start >= end || end - start > 1e3) return null;\n return {\n textStart: start,\n textEnd: end,\n quotedText: text.slice(start, end)\n };\n }\n function describe(range) {\n const mapped = mappedSlice(range);\n if (!mapped) return null;\n const { textStart: start, textEnd: end, quotedText: quote } = mapped;\n let prefix = \"\", suffix = \"\", ambiguous = true;\n for (let size = 32;; size = Math.min(400, size + 32)) {\n prefix = text.slice(Math.max(0, start - size), start);\n suffix = text.slice(end, end + size);\n ambiguous = hits(text, prefix + quote + suffix).length !== 1;\n if (!ambiguous || size === 400) break;\n }\n return {\n quotedText: quote,\n prefixText: prefix,\n suffixText: suffix,\n textStart: start,\n textEnd: end,\n textHash: hash,\n selectorFormat: \"normalized-v1\",\n ambiguousAtCreation: ambiguous\n };\n }\n return {\n text,\n hash,\n describe,\n mappedSlice,\n resolve,\n ranges,\n paintedText,\n normalizedQuote\n };\n }\n\n function trusted(ctx, event) {\n try {\n return ctx.primordials.trustedGetter && ctx.primordials.trustedGetter.get ? ctx.primordials.trustedGet(event) === true : event.isTrusted === true;\n } catch (e) {\n return false;\n }\n }\n function shouldHandleLink(ctx, url) {\n if (url.origin !== ctx.win.location.origin) return true;\n if (url.pathname !== ctx.win.location.pathname) return true;\n if (url.search !== ctx.win.location.search && url.search !== \"\") return true;\n return false;\n }\n function openExternalLink(ctx, href) {\n ctx.win.open(href, \"_blank\", \"noopener,noreferrer\");\n }\n function isExternallyOpenable(ctx, url) {\n return url.protocol === \"http:\" || url.protocol === \"https:\";\n }\n function prepareLinkClick(ctx, event) {\n let defaultPrevented = readEventValue(ctx, ctx.primordials.defaultPreventedGet, event);\n let button = readEventValue(ctx, ctx.primordials.buttonGet, event);\n let metaKey = readEventValue(ctx, ctx.primordials.metaKeyGet, event);\n let ctrlKey = readEventValue(ctx, ctx.primordials.ctrlKeyGet, event);\n let shiftKey = readEventValue(ctx, ctx.primordials.shiftKeyGet, event);\n let altKey = readEventValue(ctx, ctx.primordials.altKeyGet, event);\n if (!trusted(ctx, event) || defaultPrevented !== false || button !== 0 || metaKey !== false || ctrlKey !== false || shiftKey !== false || altKey !== false) {\n return;\n }\n if (hitComment(ctx, event)) return;\n let target = readEventValue(ctx, ctx.primordials.targetGet, event);\n let element = target && target.nodeType === 1 ? target : target && target.parentElement;\n if (element && ctx.primordials.closest(element, \".ash-comment-highlight, .ash-comment-highlight-badge\")) {\n return;\n }\n let anchor = element ? ctx.primordials.closest(element, \"a[href]\") : null;\n if (!anchor || ctx.primordials.hasAttribute(anchor, \"download\")) return;\n let rawHref = ctx.primordials.getAttribute(anchor, \"href\");\n if (!rawHref || rawHref.charAt(0) === \"#\") return;\n let url;\n let href;\n let openExternally = false;\n try {\n url = new ctx.win.URL(rawHref, ctx.win.location.href);\n if (!shouldHandleLink(ctx, url)) return;\n href = url.href;\n openExternally = url.origin !== ctx.win.location.origin && isExternallyOpenable(ctx, url);\n } catch (e) {\n href = rawHref;\n }\n let pending = ctx.primordials.objectCreate(null);\n pending.artifactPrevented = false;\n pending.href = href;\n pending.openExternally = openExternally;\n try {\n ctx.primordials.defineProperty(event, \"preventDefault\", {\n configurable: true,\n value: function() {\n pending.artifactPrevented = true;\n ctx.primordials.preventDefault(event);\n }\n });\n ctx.primordials.defineProperty(event, \"defaultPrevented\", {\n configurable: true,\n get: function() {\n return pending.artifactPrevented;\n }\n });\n ctx.primordials.weakMapSet(ctx.pendingLinkClicks, event, pending);\n } catch (e) {\n ctx.primordials.preventDefault(event);\n return;\n }\n ctx.primordials.preventDefault(event);\n }\n function finishLinkClick(ctx, event) {\n let pending = ctx.primordials.weakMapGet(ctx.pendingLinkClicks, event);\n if (!pending) return;\n ctx.primordials.weakMapDelete(ctx.pendingLinkClicks, event);\n if (pending.artifactPrevented) return;\n if (pending.openExternally && ctx.externalLinkPolicyMode === \"direct\") {\n openExternalLink(ctx, pending.href);\n return;\n }\n send(ctx, {\n kind: \"link-clicked\",\n href: pending.href,\n token: ctx.documentToken\n });\n }\n\n function badgeStyleForHighlight(ctx, highlight, isDark) {\n let palette = highlightPalette(ctx, isDark, highlight.status === \"resolved\");\n let base = \"display:inline-flex;align-items:center;gap:4px;min-height:16px;padding:0 5px;border-radius:999px;font:700 10px system-ui,sans-serif;box-shadow:0 2px 8px rgba(27,39,35,.08);cursor:pointer;touch-action:none;position:absolute;z-index:2147483646;\";\n let borderColor;\n let textColor;\n let bgColor;\n if (highlight.target) {\n borderColor = palette.badgeTargetBorder;\n textColor = palette.badgeTargetText;\n bgColor = palette.badgeTargetBg;\n } else {\n borderColor = palette.badgeBorder;\n textColor = palette.badgeText;\n bgColor = palette.badgeBg;\n }\n return base + \"border:1px solid \" + borderColor + \";color:\" + textColor + \";background:\" + bgColor + \";\";\n }\n function positionSingleBadge(ctx, entry) {\n let badge = entry.badge;\n let rects = measureBadgeEntry(ctx, entry);\n let rect = rects.length ? rects[rects.length - 1] : null;\n if (!rect || rect.width === 0 || rect.height === 0) {\n badge.style.display = \"none\";\n return;\n }\n badge.style.display = \"inline-flex\";\n badge.style.left = \"0px\";\n badge.style.top = \"0px\";\n let base = badge.getBoundingClientRect();\n let scaleX = badge.offsetWidth ? base.width / badge.offsetWidth : 1;\n let scaleY = badge.offsetHeight ? base.height / badge.offsetHeight : 1;\n if (!scaleX || !isFinite(scaleX)) scaleX = 1;\n if (!scaleY || !isFinite(scaleY)) scaleY = 1;\n let badgeHeight = badge.offsetHeight || 16;\n let threadId = badge.dataset.threadId;\n let offset = ctx.badgeOffsets[threadId] || {\n x: 0,\n y: 0\n };\n badge.style.left = (rect.right - base.left) / scaleX - 6 + offset.x + \"px\";\n badge.style.top = (rect.top - base.top) / scaleY - badgeHeight + 3 + offset.y + \"px\";\n }\n function positionBadges(ctx) {\n let layouts = [];\n for (let i = 0; i < ctx.badges.length; i++) {\n let badge = ctx.badges[i].badge;\n let rects = measureBadgeEntry(ctx, ctx.badges[i]);\n let rect = rects.length ? rects[rects.length - 1] : null;\n badge.style.display = \"inline-flex\";\n badge.style.left = \"0px\";\n badge.style.top = \"0px\";\n let base = badge.getBoundingClientRect();\n let scaleX = badge.offsetWidth ? base.width / badge.offsetWidth : 1;\n let scaleY = badge.offsetHeight ? base.height / badge.offsetHeight : 1;\n if (!scaleX || !isFinite(scaleX)) scaleX = 1;\n if (!scaleY || !isFinite(scaleY)) scaleY = 1;\n layouts.push({\n badge,\n rect,\n base,\n badgeHeight: badge.offsetHeight || 16,\n scaleX,\n scaleY,\n threadId: badge.dataset.threadId\n });\n }\n for (let j = 0; j < layouts.length; j++) {\n let layout = layouts[j];\n if (!layout.rect || layout.rect.width === 0 || layout.rect.height === 0) {\n layout.badge.style.display = \"none\";\n continue;\n }\n let offset = ctx.badgeOffsets[layout.threadId] || {\n x: 0,\n y: 0\n };\n layout.badge.style.display = \"inline-flex\";\n layout.badge.style.left = (layout.rect.right - layout.base.left) / layout.scaleX - 6 + offset.x + \"px\";\n layout.badge.style.top = (layout.rect.top - layout.base.top) / layout.scaleY - layout.badgeHeight + 3 + offset.y + \"px\";\n }\n }\n function isBadgeAnchorVisible(ctx, element) {\n if (!element) return false;\n let visibility = ctx.win.getComputedStyle(element).visibility;\n if (visibility === \"hidden\" || visibility === \"collapse\") return false;\n let boxedElement = element;\n while (boxedElement && ctx.win.getComputedStyle(boxedElement).display === \"contents\") {\n boxedElement = boxedElement.parentElement;\n }\n return !!boxedElement && !!boxedElement.getClientRects().length && (!boxedElement.checkVisibility || boxedElement.checkVisibility());\n }\n function measureBadgeEntry(ctx, entry) {\n if (entry.measure) return entry.measure();\n return [];\n }\n function schedulePositionBadges(ctx) {\n if (ctx.badgePositionFrame) return;\n ctx.badgePositionFrame = ctx.win.requestAnimationFrame(function() {\n ctx.badgePositionFrame = 0;\n positionBadges(ctx);\n });\n }\n function takeBadge(ctx, highlight) {\n let badge = ctx.reusableBadges.get(highlight.threadId);\n if (badge) ctx.reusableBadges.delete(highlight.threadId);\n else {\n badge = ctx.doc.createElement(\"button\");\n bindBadgePointer(ctx, badge);\n }\n if (!badge.isConnected) ctx.doc.documentElement.appendChild(badge);\n return badge;\n }\n function hitComment(ctx, event) {\n if (!trusted(ctx, event) || event.type === \"click\" && (event.detail <= 0 || event.pointerType === \"\" || event.mozInputSource === 6)) return null;\n for (let index = 0; index < ctx.badges.length; index++) {\n let rects = measureBadgeEntry(ctx, ctx.badges[index]);\n if (Array.from(rects).some(function(rect) {\n return event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom;\n })) return ctx.badges[index].badge;\n }\n return null;\n }\n function rectFromPointer(ctx, event, fallback) {\n if (event.detail !== 0 && typeof event.clientX === \"number\" && typeof event.clientY === \"number\") {\n return {\n top: event.clientY - 8,\n left: event.clientX,\n width: 1,\n height: 16\n };\n }\n return fallback;\n }\n function bindBadgePointer(ctx, badge) {\n let dragState = null;\n let badgeEntry = null;\n function finishDrag(event) {\n if (!dragState || event.pointerId !== dragState.pointerId) return;\n if (event.type === \"pointerup\" && dragState.dragged) ctx.badgeDragged = true;\n try {\n badge.releasePointerCapture(event.pointerId);\n } catch (e) {}\n dragState = null;\n }\n badge.addEventListener(\"pointerdown\", function(event) {\n ctx.badgeDragged = false;\n if (event.button !== 0) return;\n for (let i = 0; i < ctx.badges.length; i++) {\n if (ctx.badges[i].badge === badge) {\n badgeEntry = ctx.badges[i];\n break;\n }\n }\n let threadId = badge.dataset.threadId;\n let offset = ctx.badgeOffsets[threadId] || {\n x: 0,\n y: 0\n };\n dragState = {\n pointerId: event.pointerId,\n startX: event.clientX,\n startY: event.clientY,\n offsetX: offset.x,\n offsetY: offset.y,\n dragged: false\n };\n try {\n badge.setPointerCapture(event.pointerId);\n } catch (e) {}\n event.preventDefault();\n });\n badge.addEventListener(\"pointermove\", function(event) {\n if (!dragState || event.pointerId !== dragState.pointerId) return;\n let dx = event.clientX - dragState.startX;\n let dy = event.clientY - dragState.startY;\n if (!dragState.dragged && (Math.abs(dx) > 4 || Math.abs(dy) > 4)) {\n dragState.dragged = true;\n }\n if (!dragState.dragged) return;\n let threadId = badge.dataset.threadId;\n ctx.badgeOffsets[threadId] = {\n x: dragState.offsetX + dx,\n y: dragState.offsetY + dy\n };\n if (badgeEntry) positionSingleBadge(ctx, badgeEntry);\n });\n badge.addEventListener(\"pointerup\", finishDrag);\n badge.addEventListener(\"pointercancel\", finishDrag);\n badge.addEventListener(\"click\", function(event) {\n if (ctx.badgeDragged) {\n ctx.badgeDragged = false;\n event.preventDefault();\n event.stopPropagation();\n return;\n }\n let r = badge.getBoundingClientRect();\n selectThreadFromElement(ctx, badge, rectFromPointer(ctx, event, r));\n event.preventDefault();\n event.stopPropagation();\n });\n function updateSvgActive(active) {\n ctx.svgActiveThreads[badge.dataset.threadId] = active;\n setSvgHighlightState(ctx, badge.dataset.threadId, active);\n }\n badge.addEventListener(\"pointerenter\", function() {\n updateSvgActive(true);\n });\n badge.addEventListener(\"pointerleave\", function() {\n updateSvgActive(ctx.doc.activeElement === badge);\n });\n badge.addEventListener(\"focus\", function() {\n updateSvgActive(true);\n });\n badge.addEventListener(\"blur\", function() {\n updateSvgActive(badge.matches(\":hover\"));\n });\n }\n function selectThreadFromElement(ctx, element, rect) {\n send(ctx, {\n kind: \"comment-thread-selected\",\n threadId: element.dataset.threadId,\n rect: {\n top: rect.top,\n left: rect.left,\n width: rect.width,\n height: rect.height\n }\n });\n }\n function sendOutsidePointerDown(ctx, event) {\n if (!ctx.textAnchorsEnabled || hitComment(ctx, event)) return;\n let target = event.target;\n if (target && target.closest && target.closest(\".ash-comment-highlight, .ash-comment-highlight-badge, [data-code-copy]\")) {\n return;\n }\n send(ctx, { kind: \"comment-outside-pointer-down\" });\n }\n\n function setSvgHighlightState(ctx, threadId, active) {\n ctx.textPaints.forEach(function(paint) {\n if (paint.threadId === threadId) paint.active = active || paint.target;\n });\n refreshTextPaints(ctx);\n let overlays = ctx.doc.querySelectorAll(\".ash-comment-highlight-svg[data-thread-id=\\\"\" + ctx.win.CSS.escape(threadId) + \"\\\"]\");\n for (let i = 0; i < overlays.length; i++) {\n let overlay = overlays[i];\n let palette = overlay.dataset.palette;\n if (!palette) continue;\n let parts = palette.split(\"|\");\n let normalFill = parts[0];\n let outline = parts[1];\n let target = overlay.dataset.target === \"true\";\n let state = active || target ? \"active\" : \"normal\";\n let applied = ctx.svgOverlayStyles.get(overlay);\n if (overlay.dataset.state !== state) overlay.dataset.state = state;\n if (applied && applied.state === state && overlay.getAttribute(\"style\") === applied.style) continue;\n if (active || target) {\n overlay.style.fill = normalFill;\n overlay.style.stroke = outline;\n overlay.style.strokeWidth = \"2\";\n overlay.style.vectorEffect = \"non-scaling-stroke\";\n } else {\n overlay.style.fill = normalFill;\n overlay.style.stroke = \"none\";\n overlay.style.strokeWidth = \"0\";\n }\n ctx.svgOverlayStyles.set(overlay, {\n state,\n style: overlay.getAttribute(\"style\")\n });\n }\n }\n function svgTextRange(ctx, ranges) {\n return ranges.flatMap(function(range) {\n let node = range.startContainer;\n if (!node.parentElement.closest(\"svg text\")) return [];\n let text = node.parentElement.closest(\"text,tspan,textPath\");\n if (!text || !text.getNumberOfChars) return [];\n let walker = ctx.doc.createTreeWalker(text, ctx.win.NodeFilter.SHOW_TEXT);\n let raw = [], collapsed = [], candidate;\n let whitespace = false;\n while (candidate = walker.nextNode()) {\n let value = candidate.nodeValue || \"\";\n for (let offset = 0; offset < value.length; offset++) {\n let unit = {\n node: candidate,\n offset\n };\n raw.push([unit]);\n if (/[\\t\\n\\r ]/.test(value[offset])) {\n if (!collapsed.length) continue;\n if (whitespace) collapsed[collapsed.length - 1].push(unit);\n else collapsed.push([unit]);\n whitespace = true;\n } else {\n collapsed.push([unit]);\n whitespace = false;\n }\n }\n }\n if (whitespace) collapsed.pop();\n let count = text.getNumberOfChars();\n let characters = collapsed.length === count ? collapsed : raw.length === count ? raw : null;\n if (!characters) return [];\n let start = -1, end = -1;\n characters.forEach(function(units, index) {\n for (let i = 0; i < units.length; i++) {\n let unit = units[i];\n if (unit.node === node && unit.offset >= range.startOffset && unit.offset < range.endOffset) {\n if (start < 0) start = index;\n end = index + 1;\n break;\n }\n }\n });\n return start < 0 ? [] : [{\n text,\n start,\n end\n }];\n });\n }\n function wrapSvgRange(ctx, highlight, groups) {\n if (!groups.length) return false;\n let texts = groups.map(function(group) {\n return group.text;\n }).filter(function(text, index, all) {\n return all.indexOf(text) === index;\n });\n let first = texts[0];\n let svg = first && first.ownerSVGElement;\n while (svg && svg.ownerSVGElement) svg = svg.ownerSVGElement;\n if (!svg || !svg.parentNode) return false;\n ensureCommentStyles(ctx);\n let overlays = {};\n let badgeEntry = {\n badge: null,\n highlight,\n overlays,\n measure: measureSvgRange\n };\n function overlayKey(text, index) {\n return texts.indexOf(text) + \":\" + index;\n }\n function setAttributeIfChanged(shape, name, value) {\n value = String(value);\n if (shape.getAttribute(name) !== value) shape.setAttribute(name, String(value));\n }\n function updateOverlay(text, index, box, screenCtm) {\n let currentHighlight = badgeEntry.highlight;\n let key = overlayKey(text, index);\n let shape = overlays[key];\n if (!shape) {\n shape = ctx.doc.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\");\n shape.setAttribute(\"class\", \"ash-comment-highlight-svg\");\n shape.setAttribute(anchorIgnoreAttribute(), \"\");\n shape.setAttribute(\"pointer-events\", \"none\");\n shape.dataset.threadId = currentHighlight.threadId;\n shape.dataset.target = currentHighlight.target ? \"true\" : \"false\";\n let palette = highlightPalette(ctx, isDarkBackgroundForSvgText(ctx, text), currentHighlight.status === \"resolved\");\n shape.dataset.palette = palette.markBg + \"|\" + palette.outline;\n let textRoot = text.closest(\"text\");\n textRoot.parentNode.insertBefore(shape, textRoot);\n overlays[key] = shape;\n }\n let scaleX = screenCtm ? Math.hypot(screenCtm.a, screenCtm.b) : 1;\n let scaleY = screenCtm ? Math.hypot(screenCtm.c, screenCtm.d) : 1;\n let padX = scaleX ? 2 / scaleX : 2;\n let padY = scaleY ? 2 / scaleY : 2;\n setAttributeIfChanged(shape, \"x\", box.x - padX);\n setAttributeIfChanged(shape, \"y\", box.y - padY);\n setAttributeIfChanged(shape, \"width\", box.width + padX * 2);\n setAttributeIfChanged(shape, \"height\", box.height + padY * 2);\n let textCtm = text.getCTM ? text.getCTM() : null;\n let parentNode = shape.parentNode;\n let parentCtm = parentNode && parentNode.getCTM ? parentNode.getCTM() : null;\n if (textCtm && parentCtm && parentCtm.inverse) {\n let matrix = parentCtm.inverse().multiply(textCtm);\n setAttributeIfChanged(shape, \"transform\", \"matrix(\" + [\n matrix.a,\n matrix.b,\n matrix.c,\n matrix.d,\n matrix.e,\n matrix.f\n ].join(\" \") + \")\");\n } else if (shape.hasAttribute(\"transform\")) {\n shape.removeAttribute(\"transform\");\n }\n return shape;\n }\n function measureSvgRange() {\n let current = [];\n let lastElement = null;\n let usedOverlays = {};\n for (let i = 0; i < groups.length; i++) {\n let group = groups[i];\n let ctm = group.text.getScreenCTM ? group.text.getScreenCTM() : null;\n let runs = [];\n for (let index = group.start; index < group.end; index++) {\n try {\n let box = group.text.getExtentOfChar(index);\n if (!box || box.width < 0 || box.height <= 0) continue;\n let previous = runs.length ? runs[runs.length - 1] : null;\n let overlapsVertically = previous && box.y <= previous.y + previous.height && previous.y <= box.y + box.height;\n let sameLine = previous && overlapsVertically && box.x <= previous.x + previous.width + Math.max(4, box.height * .5);\n if (sameLine && previous) {\n let runRight = Math.max(previous.x + previous.width, box.x + box.width);\n let runBottom = Math.max(previous.y + previous.height, box.y + box.height);\n previous.x = Math.min(previous.x, box.x);\n previous.y = Math.min(previous.y, box.y);\n previous.width = runRight - previous.x;\n previous.height = runBottom - previous.y;\n } else {\n runs.push({\n x: box.x,\n y: box.y,\n width: box.width,\n height: box.height\n });\n }\n } catch (e) {}\n }\n for (let runIndex = 0; runIndex < runs.length; runIndex++) {\n try {\n let run = runs[runIndex];\n let overlayIndex = i + \"-\" + runIndex;\n let overlay = updateOverlay(group.text, overlayIndex, run, ctm);\n let display = isBadgeAnchorVisible(ctx, group.text) ? \"inline\" : \"none\";\n if (overlay.style.display !== display) overlay.style.display = display;\n usedOverlays[overlayKey(group.text, overlayIndex)] = true;\n let points = [\n [run.x, run.y],\n [run.x + run.width, run.y],\n [run.x, run.y + run.height],\n [run.x + run.width, run.y + run.height]\n ].map(function(point) {\n return ctm ? new ctx.win.DOMPoint(point[0], point[1]).matrixTransform(ctm) : {\n x: point[0],\n y: point[1]\n };\n });\n let left = Math.min.apply(null, points.map(function(point) {\n return point.x;\n }));\n let top = Math.min.apply(null, points.map(function(point) {\n return point.y;\n }));\n let right = Math.max.apply(null, points.map(function(point) {\n return point.x;\n }));\n let bottom = Math.max.apply(null, points.map(function(point) {\n return point.y;\n }));\n if (right > left && bottom > top) {\n current.push({\n left,\n right,\n top,\n width: right - left,\n height: bottom - top\n });\n lastElement = group.text;\n }\n } catch (e) {}\n }\n }\n Object.keys(overlays).forEach(function(key) {\n if (!usedOverlays[key]) {\n overlays[key].remove();\n delete overlays[key];\n }\n });\n setSvgHighlightState(ctx, highlight.threadId, ctx.svgActiveThreads[highlight.threadId] === true);\n if (current.length) return isBadgeAnchorVisible(ctx, lastElement) ? current : [];\n if (!isBadgeAnchorVisible(ctx, first)) return [];\n let fallback = first.getBoundingClientRect ? first.getBoundingClientRect() : null;\n if (!fallback || fallback.width === 0 || fallback.height === 0) {\n fallback = svg.getBoundingClientRect();\n }\n return fallback ? [fallback] : [];\n }\n let badge = takeBadge(ctx, highlight);\n badge.setAttribute(anchorIgnoreAttribute(), \"\");\n badge.type = \"button\";\n badge.className = \"ash-comment-highlight-badge\";\n badge.dataset.threadId = highlight.threadId;\n badge.dataset.count = String(highlight.count || 1);\n badge.setAttribute(\"aria-label\", commentLabel(ctx, highlight));\n badge.innerHTML = highlight.status === \"resolved\" ? \"<svg viewBox=\\\"0 0 24 24\\\" width=\\\"10\\\" height=\\\"10\\\" style=\\\"width:10px;height:10px;flex:none;border:0;padding:0;margin:0;background:none;box-shadow:none\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\" aria-hidden=\\\"true\\\"><path d=\\\"M20 6 9 17l-5-5\\\"/></svg>\" : \"<svg viewBox=\\\"0 0 24 24\\\" width=\\\"10\\\" height=\\\"10\\\" style=\\\"width:10px;height:10px;flex:none;border:0;padding:0;margin:0;background:none;box-shadow:none\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\" aria-hidden=\\\"true\\\"><path d=\\\"M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4z\\\"/></svg>\";\n badge.style.cssText = badgeStyleForHighlight(ctx, highlight, isDarkBackgroundForSvgText(ctx, first));\n badgeEntry.badge = badge;\n ctx.badges.push(badgeEntry);\n measureSvgRange();\n return true;\n }\n\n function cssPath(ctx, element) {\n if (!element || element.nodeType !== 1) return null;\n let parts = [];\n while (element && element.nodeType === 1 && element !== ctx.doc.body) {\n let name = element.nodeName.toLowerCase();\n let index = 1;\n let sibling = element;\n while (sibling = sibling.previousElementSibling) {\n if (sibling.nodeName.toLowerCase() === name) index++;\n }\n parts[parts.length] = name + \":nth-of-type(\" + index + \")\";\n element = element.parentElement;\n }\n let path = \"body\";\n for (let i = parts.length - 1; i >= 0; i--) path += \" > \" + parts[i];\n return path;\n }\n function selectedElement(ctx, range) {\n let node = range.commonAncestorContainer;\n return (node.nodeType === 1 ? node : node.parentElement) || ctx.doc.body;\n }\n function anchorRoot(ctx) {\n return ctx.doc.querySelector(\"[data-comment-content]\") || ctx.doc.body;\n }\n function sendSelection(ctx) {\n if (!ctx.textAnchorsEnabled) return;\n let selection = ctx.win.getSelection();\n if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {\n send(ctx, { kind: \"text-selection-cleared\" });\n return;\n }\n let range = selection.getRangeAt(0);\n if (!ctx.primordials.rangeToString(range).trim()) {\n send(ctx, { kind: \"text-selection-cleared\" });\n return;\n }\n let engine = createTextAnchorEngine(anchorRoot(ctx));\n let selector = engine.describe(range);\n if (!selector) {\n send(ctx, { kind: \"text-selection-cleared\" });\n return;\n }\n let rect = range.getBoundingClientRect();\n send(ctx, {\n kind: \"text-selection\",\n token: ctx.documentToken,\n quotedText: selector.quotedText,\n prefixText: selector.prefixText,\n suffixText: selector.suffixText,\n textStart: selector.textStart,\n textEnd: selector.textEnd,\n selectorFormat: selector.selectorFormat,\n textHash: selector.textHash,\n ambiguousAtCreation: selector.ambiguousAtCreation,\n versionId: ctx.displayedVersionId,\n cssPath: cssPath(ctx, selectedElement(ctx, range)),\n rect: {\n top: rect.top,\n left: rect.left,\n width: rect.width,\n height: rect.height\n }\n });\n }\n\n function ensureAnnotateStyles(ctx) {\n if (ctx.doc.getElementById(\"as-preview-annotate-style\")) return;\n let style = ctx.doc.createElement(\"style\");\n style.setAttribute(anchorIgnoreAttribute(), \"\");\n style.id = \"as-preview-annotate-style\";\n style.textContent = \".as-preview-annotate-hover{outline:2px solid #6366f1 !important;outline-offset:2px;}\" + \".as-preview-pinged{outline:2px solid #6366f1 !important;outline-offset:2px;background-color:rgba(99,102,241,0.12) !important;transition:background-color 0.4s ease;}\" + \".as-preview-flash{background-color:rgba(34,197,94,0.35) !important;transition:background-color 1s ease;}\" + \".as-preview-flash-fade{background-color:transparent !important;}\";\n ctx.doc.head.appendChild(style);\n }\n function annotateTargetFrom(ctx, eventTarget) {\n const target = eventTarget;\n if (!target || target.nodeType !== 1) return null;\n if (target === ctx.doc.body || target === ctx.doc.documentElement) return null;\n if (ctx.primordials.closest(target, commentUiSelector())) return null;\n return target;\n }\n function clearAnnotateHover(ctx) {\n if (ctx.annotateHoverElement) {\n ctx.annotateHoverElement.classList.remove(\"as-preview-annotate-hover\");\n ctx.annotateHoverElement = null;\n }\n }\n function elementLabel(ctx, el) {\n let quote = function(text) {\n return \"\\\"\" + text + \"\\\"\";\n };\n let tag = el.nodeName.toLowerCase();\n let ariaLabel = el.getAttribute && el.getAttribute(\"aria-label\");\n if (ariaLabel) return tag + \" \" + quote(ariaLabel.trim());\n let text = (el.textContent || \"\").replace(/\\s+/g, \" \").trim();\n if (text) return tag + \" \" + quote(text.slice(0, 25));\n if (tag === \"img\") {\n let alt = el.getAttribute(\"alt\");\n if (alt) return \"img \" + quote(alt.trim());\n }\n let role = el.getAttribute && el.getAttribute(\"role\");\n if (role) return tag + \" [role=\" + role + \"]\";\n return tag;\n }\n function siblingText(ctx, el) {\n return el && el.textContent ? el.textContent.replace(/\\s+/g, \" \").trim().slice(0, 40) : \"\";\n }\n function annotateContextText(ctx, el) {\n let own = (el.textContent || \"\").replace(/\\s+/g, \" \").trim().slice(0, 100);\n let before = siblingText(ctx, el.previousElementSibling);\n let after = siblingText(ctx, el.nextElementSibling);\n let parts = [own];\n if (before) parts.push(\"[before: \" + before + \"]\");\n if (after) parts.push(\"[after: \" + after + \"]\");\n return parts.join(\" \").trim();\n }\n function verifyAnchors(ctx, anchors, engine) {\n ctx.anchorSnapshotGeneration++;\n ctx.pendingAnchors = anchors || [];\n if (!ctx.pendingAnchors.length) {\n ctx.checkingAnchors = [];\n scheduleChecking(ctx);\n return;\n }\n let checking = [];\n let verdicts = [];\n if (!engine) {\n for (let i = 0; i < ctx.pendingAnchors.length; i++) {\n if (ctx.pendingAnchors[i].kind === \"text\") {\n engine = createTextAnchorEngine(anchorRoot(ctx));\n break;\n }\n }\n }\n for (let i = 0; i < (anchors || []).length; i++) {\n let anchor = anchors[i] || {};\n let attached = false;\n if (anchor.kind === \"element\") {\n attached = findElement(ctx, anchor) !== null;\n } else if (anchor.kind === \"text\") {\n attached = engine.resolve(anchor) !== null;\n }\n if (attached) delete ctx.checkingDeadlines[anchor.thread];\n verdicts.push({\n thread: anchor.thread,\n attached,\n position_state: attached ? \"attached\" : missingState(ctx, anchor.thread, checking)\n });\n }\n send(ctx, {\n kind: \"anchor-verdicts\",\n verificationId: ctx.pendingVerificationId,\n generation: ++ctx.resolutionGeneration,\n verdicts\n });\n ctx.checkingAnchors = checking;\n scheduleChecking(ctx);\n }\n function findElement(ctx, anchor) {\n if (!anchor.ownText) {\n try {\n return ctx.doc.querySelector(anchor.selector);\n } catch (error) {\n return null;\n }\n }\n let peers = anchor.tagName ? anchorRoot(ctx).getElementsByTagName(anchor.tagName) : anchorRoot(ctx).getElementsByTagName(\"*\");\n let matches = [];\n for (let i = 0; i < peers.length; i++) {\n if (ownText(ctx, peers[i]) === anchor.ownText) matches.push(peers[i]);\n }\n if (matches.length === 0) return null;\n if (matches.length === 1) return matches[0];\n for (let j = 0; j < matches.length; j++) {\n if (annotateContextText(ctx, matches[j]) === anchor.contextText) return matches[j];\n }\n return null;\n }\n function ownText(ctx, el) {\n return (el.textContent || \"\").replace(/\\s+/g, \" \").trim();\n }\n function setAnnotateMode(ctx, enabled) {\n ctx.annotateModeEnabled = enabled === true;\n if (ctx.annotateModeEnabled) {\n ensureAnnotateStyles(ctx);\n } else {\n clearAnnotateHover(ctx);\n }\n }\n function pingElement(ctx, selector) {\n if (typeof selector !== \"string\" || !selector) return;\n let el = null;\n try {\n el = ctx.doc.querySelector(selector);\n } catch (error) {}\n if (!el) return;\n ensureAnnotateStyles(ctx);\n el.scrollIntoView({\n behavior: \"smooth\",\n block: \"center\"\n });\n el.classList.add(\"as-preview-pinged\");\n ctx.win.setTimeout(function() {\n el.classList.remove(\"as-preview-pinged\");\n }, 2500);\n }\n function flashElement(ctx, selector) {\n if (typeof selector !== \"string\" || !selector) return;\n let el = null;\n try {\n el = ctx.doc.querySelector(selector);\n } catch (error) {}\n if (!el) return;\n ensureAnnotateStyles(ctx);\n el.classList.add(\"as-preview-flash\");\n ctx.win.setTimeout(function() {\n el.classList.add(\"as-preview-flash-fade\");\n }, 100);\n ctx.win.setTimeout(function() {\n el.classList.remove(\"as-preview-flash\");\n el.classList.remove(\"as-preview-flash-fade\");\n }, 1100);\n }\n function onAnnotateHover(ctx, event) {\n if (!ctx.annotateModeEnabled) return;\n let target = annotateTargetFrom(ctx, ctx.primordials.targetGet ? ctx.primordials.targetGet(event) : event.target);\n if (target === ctx.annotateHoverElement) return;\n clearAnnotateHover(ctx);\n if (!target) return;\n ctx.annotateHoverElement = target;\n target.classList.add(\"as-preview-annotate-hover\");\n }\n function onAnnotateClick(ctx, event) {\n if (!ctx.annotateModeEnabled) return;\n let target = annotateTargetFrom(ctx, ctx.primordials.targetGet ? ctx.primordials.targetGet(event) : event.target);\n if (!target) return;\n event.preventDefault();\n event.stopPropagation();\n let selected = ctx.win.getSelection();\n if (selected && !selected.isCollapsed && selected.toString().trim()) return;\n let rect = target.getBoundingClientRect();\n send(ctx, {\n kind: \"element-annotate\",\n selector: cssPath(ctx, target),\n label: elementLabel(ctx, target),\n contextText: annotateContextText(ctx, target),\n ownText: ownText(ctx, target),\n tagName: target.tagName,\n rect: {\n top: rect.top,\n left: rect.left,\n width: rect.width,\n height: rect.height\n }\n });\n }\n\n function ensureCommentStyles(ctx) {\n if (ctx.doc.getElementById(highlightStyleId())) return;\n let style = ctx.doc.createElement(\"style\");\n style.setAttribute(anchorIgnoreAttribute(), \"\");\n style.id = highlightStyleId();\n style.textContent = \".ash-comment-highlight-badge::after{content:attr(data-count);}\";\n ctx.doc.head.appendChild(style);\n }\n function clearMarks(ctx, preserveBadges = false) {\n for (let i = 0; i < ctx.badges.length; i++) {\n if (preserveBadges) ctx.reusableBadges.set(ctx.badges[i].badge.dataset.threadId, ctx.badges[i].badge);\n else ctx.badges[i].badge.remove();\n }\n ctx.badges = [];\n ctx.paintedAnchors = [];\n if (typeof ctx.win.CSS !== \"undefined\" && ctx.win.CSS.highlights) {\n ctx.highlightNames.forEach(function(name) {\n ctx.win.CSS.highlights.delete(name);\n });\n }\n ctx.highlightNames = [];\n ctx.textPaints = [];\n let svgOverlays = ctx.doc.querySelectorAll(\".ash-comment-highlight-svg\");\n for (let s = 0; s < svgOverlays.length; s++) svgOverlays[s].remove();\n if (!preserveBadges) ctx.svgActiveThreads = {};\n ctx.appliedHighlightKey = \"\";\n let style = ctx.doc.getElementById(highlightStyleId());\n if (style) style.textContent = \".ash-comment-highlight-badge::after{content:attr(data-count);}\";\n }\n function paintIntact(ctx, highlightsById) {\n let style = ctx.doc.getElementById(highlightStyleId());\n if (ctx.paintedAnchors.length && (!style || !style.isConnected || style.textContent !== textPaintCss(ctx))) return false;\n if (typeof ctx.win.CSS !== \"undefined\" && ctx.win.CSS.highlights) {\n for (let i = 0; i < ctx.textPaints.length; i++) {\n let paint = ctx.textPaints[i];\n if (ctx.win.CSS.highlights.get(paint.name) !== paint.highlight || paint.highlight.size !== paint.ranges.length) return false;\n for (let j = 0; j < paint.ranges.length; j++) {\n if (!paint.highlight.has(paint.ranges[j])) return false;\n }\n }\n }\n for (let i = 0; i < ctx.badges.length; i++) {\n let entry = ctx.badges[i];\n if (!highlightsById.has(entry.highlight.threadId) || !entry.badge.isConnected) return false;\n if (entry.overlays) {\n let shapes = Object.values(entry.overlays);\n for (let j = 0; j < shapes.length; j++) {\n if (!shapes[j].isConnected) return false;\n }\n }\n }\n return ctx.paintedAnchors.every(function(entry) {\n let next = highlightsById.get(entry.highlight.threadId);\n if (!next || next.ranges.length !== entry.ranges.length) return false;\n for (let i = 0; i < entry.ranges.length; i++) {\n let range = entry.ranges[i];\n let current = next.ranges[i];\n if (range.startContainer !== current.startContainer || range.startOffset !== current.startOffset || range.endContainer !== current.endContainer || range.endOffset !== current.endOffset) return false;\n }\n if (entry.groups.length) {\n let groups = svgTextRange(ctx, entry.ranges);\n if (groups.length !== entry.groups.length) return false;\n for (let i = 0; i < groups.length; i++) {\n let group = groups[i];\n let previous = entry.groups[i];\n if (group.text !== previous.text || group.start !== previous.start || group.end !== previous.end) return false;\n }\n }\n return true;\n });\n }\n function setCommentLabels(ctx, labels) {\n if (!labels || typeof labels !== \"object\") return;\n if (typeof labels.openOne === \"string\") ctx.commentLabels.openOne = labels.openOne;\n if (typeof labels.openOther === \"string\") ctx.commentLabels.openOther = labels.openOther;\n if (typeof labels.resolvedOne === \"string\") ctx.commentLabels.resolvedOne = labels.resolvedOne;\n if (typeof labels.resolvedOther === \"string\") ctx.commentLabels.resolvedOther = labels.resolvedOther;\n }\n function commentLabel(ctx, highlight) {\n let count = highlight.count || 1;\n let template = highlight.status === \"resolved\" ? count === 1 ? ctx.commentLabels.resolvedOne : ctx.commentLabels.resolvedOther : count === 1 ? ctx.commentLabels.openOne : ctx.commentLabels.openOther;\n let label = template.replace(/\\{n\\}/g, String(count));\n return highlight.quotedText ? label + \": \" + highlight.quotedText : label;\n }\n function parseRgbColor(ctx, value) {\n if (!value || value === \"transparent\") return null;\n let match = value.match(/^rgba?\\(\\s*([\\d.]+)\\s*,\\s*([\\d.]+)\\s*,\\s*([\\d.]+)(?:\\s*,\\s*([\\d.]+))?\\s*\\)$/);\n if (!match) return null;\n return [\n parseFloat(match[1]),\n parseFloat(match[2]),\n parseFloat(match[3]),\n match[4] === undefined ? 1 : parseFloat(match[4])\n ];\n }\n function rgbToLuminance(ctx, r, g, b) {\n return .2126 * (r / 255) + .7152 * (g / 255) + .0722 * (b / 255);\n }\n function parseColorValue(ctx, value) {\n if (!value || value === \"transparent\") return { type: \"none\" };\n let rgb = parseRgbColor(ctx, value);\n if (rgb) {\n return {\n type: \"rgb\",\n r: rgb[0],\n g: rgb[1],\n b: rgb[2],\n a: rgb[3]\n };\n }\n let modernMatch = value.match(/^oklch\\(\\s*([\\d.]+)(%?)[^/)]*(?:\\/\\s*([\\d.]+)(%?))?/);\n if (modernMatch) {\n let lightness = parseFloat(modernMatch[1]);\n if (modernMatch[2] === \"%\") lightness = lightness / 100;\n let oklchAlpha = modernMatch[3] === undefined ? 1 : parseFloat(modernMatch[3]);\n if (modernMatch[4] === \"%\") oklchAlpha = oklchAlpha / 100;\n return {\n type: \"luminance\",\n value: lightness,\n a: oklchAlpha\n };\n }\n modernMatch = value.match(/^lab\\(\\s*([\\d.]+)(%?)[^/)]*(?:\\/\\s*([\\d.]+)(%?))?/);\n if (modernMatch) {\n let labLightness = parseFloat(modernMatch[1]);\n if (modernMatch[2] === \"%\") labLightness = labLightness / 100;\n else labLightness = labLightness / 100;\n let labAlpha = modernMatch[3] === undefined ? 1 : parseFloat(modernMatch[3]);\n if (modernMatch[4] === \"%\") labAlpha = labAlpha / 100;\n return {\n type: \"luminance\",\n value: labLightness,\n a: labAlpha\n };\n }\n modernMatch = value.match(/^color\\(\\s*(?:display-p3|srgb)\\s+([\\d.]+)\\s+([\\d.]+)\\s+([\\d.]+)[^/)]*(?:\\/\\s*([\\d.]+)(%?))?/);\n if (modernMatch) {\n let colorAlpha = modernMatch[4] === undefined ? 1 : parseFloat(modernMatch[4]);\n if (modernMatch[5] === \"%\") colorAlpha = colorAlpha / 100;\n return {\n type: \"luminance\",\n value: .2126 * parseFloat(modernMatch[1]) + .7152 * parseFloat(modernMatch[2]) + .0722 * parseFloat(modernMatch[3]),\n a: colorAlpha\n };\n }\n return { type: \"none\" };\n }\n function resolveBackgroundRgb(ctx, el) {\n while (el) {\n let parsed = parseColorValue(ctx, ctx.win.getComputedStyle(el).backgroundColor);\n if (parsed.type === \"none\") {\n el = el.parentElement;\n continue;\n }\n if (parsed.type === \"luminance\") {\n if (parsed.a === 0) {\n el = el.parentElement;\n continue;\n }\n let gray = parsed.value * 255;\n if (parsed.a < 1) {\n let ancestorRgb = resolveBackgroundRgb(ctx, el.parentElement);\n let lumAlpha = parsed.a;\n return [\n gray * lumAlpha + ancestorRgb[0] * (1 - lumAlpha),\n gray * lumAlpha + ancestorRgb[1] * (1 - lumAlpha),\n gray * lumAlpha + ancestorRgb[2] * (1 - lumAlpha)\n ];\n }\n return [\n gray,\n gray,\n gray\n ];\n }\n if (parsed.type === \"rgb\") {\n if (parsed.a === 0) {\n el = el.parentElement;\n continue;\n }\n if (parsed.a < 1) {\n let ancestorRgb = resolveBackgroundRgb(ctx, el.parentElement);\n let alpha = parsed.a;\n return [\n parsed.r * alpha + ancestorRgb[0] * (1 - alpha),\n parsed.g * alpha + ancestorRgb[1] * (1 - alpha),\n parsed.b * alpha + ancestorRgb[2] * (1 - alpha)\n ];\n }\n return [\n parsed.r,\n parsed.g,\n parsed.b\n ];\n }\n }\n return [\n 255,\n 255,\n 255\n ];\n }\n function resolvedLuminance(ctx, element) {\n function resolveFrom(el) {\n while (el) {\n let parsed = parseColorValue(ctx, ctx.win.getComputedStyle(el).backgroundColor);\n if (parsed.type === \"none\") {\n el = el.parentElement;\n continue;\n }\n if (parsed.type === \"luminance\") {\n if (parsed.a === 0) {\n el = el.parentElement;\n continue;\n }\n if (parsed.a < 1) {\n let ancestor = resolveFrom(el.parentElement);\n let ancestorLum = ancestor !== null ? ancestor : 1;\n return parsed.value * parsed.a + ancestorLum * (1 - parsed.a);\n }\n return parsed.value;\n }\n if (parsed.type === \"rgb\") {\n if (parsed.a === 0) {\n el = el.parentElement;\n continue;\n }\n if (parsed.a < 1) {\n let ancestorRgb = resolveBackgroundRgb(ctx, el.parentElement);\n let alpha = parsed.a;\n return rgbToLuminance(ctx, parsed.r * alpha + ancestorRgb[0] * (1 - alpha), parsed.g * alpha + ancestorRgb[1] * (1 - alpha), parsed.b * alpha + ancestorRgb[2] * (1 - alpha));\n }\n return rgbToLuminance(ctx, parsed.r, parsed.g, parsed.b);\n }\n }\n return null;\n }\n let result = resolveFrom(element);\n return result !== null ? result : 1;\n }\n function isDarkBackground(ctx, element) {\n return resolvedLuminance(ctx, element) < .5;\n }\n function isDarkBackgroundForSvgText(ctx, text) {\n if (!text) return isDarkBackground(ctx, ctx.doc.body);\n let fill = ctx.win.getComputedStyle(text).fill;\n let parsed = parseColorValue(ctx, fill);\n if (parsed.type === \"rgb\" && parsed.a > 0) return rgbToLuminance(ctx, parsed.r, parsed.g, parsed.b) >= .5;\n if (parsed.type === \"luminance\" && parsed.a > 0) return parsed.value >= .5;\n return isDarkBackground(ctx, text);\n }\n function textPaintCss(ctx) {\n return \".ash-comment-highlight-badge::after{content:attr(data-count);}\" + ctx.textPaints.map(function(paint) {\n return \"::highlight(\" + paint.name + \"){background-color:\" + paint.palette.markBg + \";text-decoration:underline;text-decoration-color:\" + (paint.active ? paint.palette.outline : paint.palette.markUnderline) + \";text-decoration-thickness:\" + (paint.active ? \"3px\" : \"2px\") + \";}\";\n }).join(\"\");\n }\n function refreshTextPaints(ctx) {\n let style = ctx.doc.getElementById(highlightStyleId());\n if (!style) return;\n let css = textPaintCss(ctx);\n if (style.textContent !== css) style.textContent = css;\n }\n function highlightPalette(ctx, isDark, resolved) {\n if (isDark) {\n if (resolved) {\n return {\n markBg: \"rgba(134,197,165,.14)\",\n markUnderline: \"rgba(134,197,165,.75)\",\n outline: \"#86c5a5\",\n badgeBorder: \"rgba(134,197,165,.75)\",\n badgeText: \"#86c5a5\",\n badgeBg: \"#1f2937\",\n badgeTargetBorder: \"#86c5a5\",\n badgeTargetText: \"#fff\",\n badgeTargetBg: \"#86c5a5\"\n };\n }\n return {\n markBg: \"rgba(96,165,250,.16)\",\n markUnderline: \"rgba(96,165,250,.85)\",\n outline: \"#60a5fa\",\n badgeBorder: \"rgba(96,165,250,.85)\",\n badgeText: \"#60a5fa\",\n badgeBg: \"#1f2937\",\n badgeTargetBorder: \"#60a5fa\",\n badgeTargetText: \"#fff\",\n badgeTargetBg: \"#60a5fa\"\n };\n }\n if (resolved) {\n return {\n markBg: \"rgba(68,131,97,.12)\",\n markUnderline: \"rgba(68,131,97,.58)\",\n outline: \"#448361\",\n badgeBorder: \"rgba(68,131,97,.36)\",\n badgeText: \"#448361\",\n badgeBg: \"#fff\",\n badgeTargetBorder: \"#448361\",\n badgeTargetText: \"#fff\",\n badgeTargetBg: \"#448361\"\n };\n }\n return {\n markBg: \"rgba(37,99,235,.16)\",\n markUnderline: \"rgba(37,99,235,.72)\",\n outline: \"#2383e2\",\n badgeBorder: \"rgba(35,131,226,.44)\",\n badgeText: \"#2383e2\",\n badgeBg: \"#fff\",\n badgeTargetBorder: \"#2383e2\",\n badgeTargetText: \"#fff\",\n badgeTargetBg: \"#2383e2\"\n };\n }\n function wrapRange(ctx, highlight, ranges, covered) {\n if (!ranges.length) return;\n let groups = !covered && ctx.doc.querySelector(\"svg text\") ? svgTextRange(ctx, ranges) : [];\n ctx.paintedAnchors.push({\n highlight,\n ranges,\n groups\n });\n if (covered) return;\n let svgWrapped = wrapSvgRange(ctx, highlight, groups);\n ensureCommentStyles(ctx);\n let name = \"ash-comment-\" + ctx.highlightNames.length;\n let palette = highlightPalette(ctx, isDarkBackground(ctx, ranges[0].startContainer.parentElement), highlight.status === \"resolved\");\n if (typeof ctx.win.CSS !== \"undefined\" && ctx.win.CSS.highlights && typeof ctx.win.Highlight !== \"undefined\") {\n let paint = new ctx.win.Highlight(...ranges);\n ctx.win.CSS.highlights.set(name, paint);\n ctx.highlightNames.push(name);\n ctx.textPaints.push({\n name,\n highlight: paint,\n ranges,\n threadId: highlight.threadId,\n palette,\n active: highlight.target,\n target: highlight.target\n });\n refreshTextPaints(ctx);\n }\n if (svgWrapped) return;\n let badge = takeBadge(ctx, highlight);\n badge.setAttribute(anchorIgnoreAttribute(), \"\");\n badge.type = \"button\";\n badge.className = \"ash-comment-highlight-badge\";\n badge.setAttribute(\"aria-label\", commentLabel(ctx, highlight));\n badge.dataset.threadId = highlight.threadId;\n badge.dataset.count = String(highlight.count || 1);\n badge.style.cssText = badgeStyleForHighlight(ctx, highlight, isDarkBackground(ctx, ranges[0].startContainer.parentElement));\n ctx.badges.push({\n badge,\n highlight,\n measure: function() {\n let rects = [];\n let lastElement = null;\n ranges.forEach(function(range) {\n let current = Array.from(range.getClientRects());\n if (current.length) {\n rects.push(...current);\n lastElement = range.startContainer.parentElement;\n }\n });\n return isBadgeAnchorVisible(ctx, lastElement) ? rects : [];\n }\n });\n }\n function missingState(ctx, id, checking) {\n if (!ctx.checkingDeadlines[id]) ctx.checkingDeadlines[id] = Date.now() + 3e3;\n let deadline = ctx.checkingDeadlines[id];\n if (Date.now() < deadline) {\n checking.push(deadline);\n return \"checking\";\n }\n return \"needs-check\";\n }\n function scheduleChecking(ctx, retryDelay = 0) {\n if (ctx.checkingTimer) ctx.win.clearTimeout(ctx.checkingTimer);\n let deadlines = ctx.checkingHighlights.concat(ctx.checkingAnchors);\n if (!deadlines.length) {\n ctx.checkingTimer = undefined;\n return;\n }\n ctx.checkingTimer = ctx.win.setTimeout(function() {\n ctx.checkingTimer = undefined;\n let completed = false;\n try {\n let engine = createTextAnchorEngine(anchorRoot(ctx));\n try {\n applyHighlights(ctx, ctx.pendingHighlights, engine);\n } finally {\n verifyAnchors(ctx, ctx.pendingAnchors, engine);\n }\n completed = true;\n } finally {\n scheduleChecking(ctx, completed ? 0 : Math.min(1e3, Math.max(1, retryDelay * 2)));\n }\n }, Math.max(1, retryDelay, Math.min.apply(null, deadlines) - Date.now()));\n }\n function applyHighlights(ctx, list, engine) {\n ctx.anchorSnapshotGeneration++;\n ctx.pendingHighlights = Array.isArray(list) ? list : [];\n if (!ctx.pendingHighlights.length) {\n ctx.checkingHighlights = [];\n ctx.lastResolutionSignature = \"\";\n scheduleChecking(ctx);\n clearMarks(ctx);\n return;\n }\n let checking = [];\n let forcePaint = !!engine;\n engine = engine || createTextAnchorEngine(anchorRoot(ctx));\n ctx.measuredText = engine.text;\n let results = [];\n let resolvedHighlights = ctx.pendingHighlights.map(function(highlight) {\n let resolved = engine.resolve(highlight);\n return {\n highlight: resolved ? {\n ...highlight,\n ...resolved\n } : highlight,\n resolved,\n ranges: resolved ? engine.ranges(resolved.textStart, resolved.textEnd) : []\n };\n });\n let highlightsById = new Map(resolvedHighlights.map(function(entry) {\n return [entry.highlight.threadId, entry];\n }));\n let paintKey = JSON.stringify(resolvedHighlights.map(function(entry) {\n let palettes = entry.ranges.map(function(range) {\n let element = range.startContainer.parentElement;\n let svgText = element.closest(\"svg text\") && element.closest(\"text,tspan,textPath\");\n return [isDarkBackground(ctx, element), svgText ? isDarkBackgroundForSvgText(ctx, svgText) : null];\n });\n return [\n entry.highlight.threadId,\n entry.highlight.status,\n entry.highlight.target,\n palettes,\n entry.resolved && entry.resolved.textStart,\n entry.resolved && entry.resolved.textEnd\n ];\n }).sort(function(left, right) {\n return left[0].localeCompare(right[0]);\n }));\n let repaint = forcePaint || ctx.appliedHighlightKey !== paintKey || !paintIntact(ctx, highlightsById);\n if (repaint) clearMarks(ctx, true);\n else {\n ctx.paintedAnchors.forEach(function(entry) {\n entry.highlight = highlightsById.get(entry.highlight.threadId).highlight;\n });\n ctx.badges.forEach(function(entry) {\n let highlight = highlightsById.get(entry.highlight.threadId).highlight;\n entry.highlight = highlight;\n if (entry.badge.dataset.threadId !== highlight.threadId) entry.badge.dataset.threadId = highlight.threadId;\n let count = String(highlight.count || 1), label = commentLabel(ctx, highlight);\n if (entry.badge.dataset.count !== count) entry.badge.dataset.count = count;\n if (entry.badge.getAttribute(\"aria-label\") !== label) entry.badge.setAttribute(\"aria-label\", label);\n });\n }\n resolvedHighlights.forEach(function(entry) {\n let highlight = entry.highlight, resolved = entry.resolved;\n let covered = false;\n if (resolved && highlight.status === \"resolved\") {\n for (let i = 0; i < resolvedHighlights.length; i++) {\n let other = resolvedHighlights[i];\n if (other.highlight.status !== \"resolved\" && other.resolved && resolved.textStart < other.resolved.textEnd && other.resolved.textStart < resolved.textEnd) {\n covered = true;\n break;\n }\n }\n }\n if (resolved) {\n delete ctx.checkingDeadlines[highlight.threadId];\n if (repaint) wrapRange(ctx, entry.highlight, entry.ranges, covered);\n }\n results.push({\n threadId: highlight.threadId,\n state: resolved ? \"attached\" : missingState(ctx, highlight.threadId, checking),\n textStart: resolved ? resolved.textStart : null,\n textEnd: resolved ? resolved.textEnd : null,\n textHash: resolved ? engine.hash : null\n });\n });\n ctx.reusableBadges.forEach(function(badge) {\n badge.remove();\n });\n ctx.reusableBadges.clear();\n ctx.appliedHighlightKey = paintKey;\n positionBadges(ctx);\n let signature = JSON.stringify([\n ctx.displayedVersionId,\n ctx.displayedPath,\n results.map(function(result) {\n return [\n result.threadId,\n result.state,\n result.textStart,\n result.textEnd\n ];\n })\n ]);\n if (signature !== ctx.lastResolutionSignature) for (let offset = 0; offset < results.length; offset += 100) {\n send(ctx, {\n kind: \"anchor-resolutions\",\n token: ctx.documentToken,\n versionId: ctx.displayedVersionId,\n targetPath: ctx.displayedPath,\n generation: ++ctx.resolutionGeneration,\n results: results.slice(offset, offset + 100)\n });\n }\n ctx.lastResolutionSignature = signature;\n ctx.checkingHighlights = checking;\n scheduleChecking(ctx);\n }\n function invalidateChangedPaint(ctx, engine) {\n ctx.paintedAnchors = ctx.paintedAnchors.filter(function(entry) {\n let first = entry.ranges[0];\n let last = entry.ranges[entry.ranges.length - 1];\n if (engine.paintedText(first, last) === engine.normalizedQuote(entry.highlight)) return true;\n ctx.appliedHighlightKey = \"\";\n let id = entry.highlight.threadId;\n ctx.textPaints = ctx.textPaints.filter(function(paint) {\n if (paint.threadId !== id) return true;\n if (typeof ctx.win.CSS !== \"undefined\" && ctx.win.CSS.highlights) ctx.win.CSS.highlights.delete(paint.name);\n return false;\n });\n ctx.badges = ctx.badges.filter(function(badgeEntry) {\n if (badgeEntry.badge.dataset.threadId !== id) return true;\n badgeEntry.badge.remove();\n return false;\n });\n ctx.doc.querySelectorAll(\".ash-comment-highlight-svg\").forEach(function(shape) {\n if (shape.dataset.threadId === id) shape.remove();\n });\n return false;\n });\n }\n function scrollToThread(ctx, id) {\n let painted = ctx.paintedAnchors.find(function(entry) {\n return entry.highlight.threadId === id;\n });\n if (painted && painted.ranges.length) {\n let start = painted.ranges[0].startContainer;\n let target = start.nodeType === 1 ? start : start.parentElement;\n if (target) {\n target.scrollIntoView({\n block: \"center\",\n inline: \"nearest\",\n behavior: \"instant\"\n });\n let range = painted.ranges[0];\n for (let ancestor = target; ancestor && ancestor !== ctx.doc.scrollingElement; ancestor = ancestor.parentElement) {\n let style = ctx.win.getComputedStyle(ancestor);\n let scrollX = /(auto|scroll|hidden|overlay)/.test(style.overflowX) && ancestor.scrollWidth > ancestor.clientWidth;\n let scrollY = /(auto|scroll|hidden|overlay)/.test(style.overflowY) && ancestor.scrollHeight > ancestor.clientHeight;\n if (!scrollX && !scrollY) continue;\n let rect = range.getClientRects()[0];\n if (!rect) return;\n let box = ancestor.getBoundingClientRect();\n let scaleX = ancestor.offsetWidth ? box.width / ancestor.offsetWidth : 1;\n let scaleY = ancestor.offsetHeight ? box.height / ancestor.offsetHeight : 1;\n if (!scaleX || !scaleY) continue;\n let left = box.left + ancestor.clientLeft * scaleX;\n let top = box.top + ancestor.clientTop * scaleY;\n let width = ancestor.clientWidth * scaleX;\n let height = ancestor.clientHeight * scaleY;\n let dx = rect.left < left || rect.width > width ? rect.left - left : Math.max(0, rect.right - left - width);\n ancestor.scrollBy({\n left: scrollX ? dx / scaleX : 0,\n top: scrollY ? (rect.top + rect.height / 2 - top - height / 2) / scaleY : 0,\n behavior: \"instant\"\n });\n }\n let visible = range.getClientRects()[0];\n if (visible) {\n let viewportWidth = ctx.doc.documentElement.clientWidth;\n ctx.win.scrollBy({\n left: visible.left < 0 || visible.width > viewportWidth ? visible.left : Math.max(0, visible.right - viewportWidth),\n top: visible.top + visible.height / 2 - ctx.doc.documentElement.clientHeight / 2,\n behavior: \"instant\"\n });\n }\n schedulePositionBadges(ctx);\n }\n return;\n }\n let element = ctx.doc.querySelector(\".ash-comment-highlight[data-thread-id=\\\"\" + ctx.win.CSS.escape(id) + \"\\\"], .ash-comment-highlight-badge[data-thread-id=\\\"\" + ctx.win.CSS.escape(id) + \"\\\"], .ash-comment-highlight-svg[data-thread-id=\\\"\" + ctx.win.CSS.escape(id) + \"\\\"]\");\n if (element) element.scrollIntoView({\n block: \"center\",\n behavior: \"smooth\"\n });\n }\n\n function requestMermaidRendering(ctx) {\n if (ctx.mermaidRequested) return;\n if (!ctx.doc.body || !ctx.doc.body.hasAttribute(\"data-artifact-markdown\")) return;\n let blocks = ctx.doc.querySelectorAll(\"pre code.language-mermaid\");\n let diagrams = [];\n for (let index = 0; index < blocks.length && diagrams.length < 16; index++) {\n let source = blocks[index].textContent || \"\";\n if (!source || source.length > 2e4) continue;\n let pre = blocks[index].closest(\"pre\");\n if (!pre) continue;\n let id = \"artifactshare-mermaid-\" + index;\n ctx.mermaidBlocks[id] = pre;\n diagrams[diagrams.length] = {\n id,\n source\n };\n }\n if (diagrams.length) {\n ctx.mermaidRequested = true;\n send(ctx, {\n kind: \"mermaid-render-request\",\n renderToken: ctx.readyChallenge,\n diagrams\n });\n }\n }\n function installMermaidResults(ctx, renderToken, results) {\n if (renderToken !== ctx.readyChallenge) return;\n if (!Array.isArray(results)) return;\n for (let index = 0; index < results.length; index++) {\n let result = results[index] || {};\n let pre = typeof result.id === \"string\" ? ctx.mermaidBlocks[result.id] : null;\n if (!pre || typeof result.svg !== \"string\" || !result.svg.startsWith(\"<svg\")) continue;\n let svgDocument = new ctx.win.DOMParser().parseFromString(result.svg, \"image/svg+xml\");\n let svg = svgDocument.documentElement;\n if (svg.localName !== \"svg\" || svg.namespaceURI !== \"http://www.w3.org/2000/svg\" || svgDocument.querySelector(\"parsererror\")) continue;\n let container = ctx.doc.createElement(\"div\");\n container.className = \"mermaid-diagram\";\n container.appendChild(ctx.doc.importNode(svg, true));\n pre.dataset.mermaidRendered = \"true\";\n pre.hidden = true;\n pre.before(container);\n delete ctx.mermaidBlocks[result.id];\n }\n schedulePositionBadges(ctx);\n }\n\n function send(ctx, message) {\n try {\n let payload = createMessagePayload(ctx.primordials, message);\n if (ctx.previewCapability) {\n payload.previewCapability = ctx.previewCapability;\n payload.documentGeneration = ctx.previewGeneration;\n payload.sequence = ++ctx.previewSendSequence;\n }\n ctx.primordials.savedPostMessage(ctx.primordials.savedParent, payload, \"*\");\n } catch (e) {}\n }\n function ready(ctx) {\n if (ctx.readyChallenge && ctx.documentToken) {\n send(ctx, {\n kind: \"ready\",\n challenge: ctx.readyChallenge,\n token: ctx.documentToken\n });\n reportHash(ctx, true);\n }\n }\n function onReadyCheck(ctx, event) {\n let message = event && event.data;\n if (!event || event.source !== ctx.primordials.savedParent || !message || message.source !== \"artifactshare-parent\" || message.kind !== \"ready-check\") return;\n if (typeof message.challenge !== \"string\" || !message.challenge) return;\n ctx.readyChallenge = message.challenge;\n for (let index = 0; index < ctx.pendingCspViolationCount; index++) {\n send(ctx, ctx.pendingCspViolations[index]);\n }\n ctx.pendingCspViolations = ctx.primordials.objectCreate(null);\n ctx.pendingCspViolationCount = 0;\n requestMermaidRendering(ctx);\n ready(ctx);\n }\n function readEventValue(ctx, getter, event) {\n if (!getter) return null;\n try {\n return getter(event);\n } catch (e) {\n return null;\n }\n }\n function createMessagePayload(primitives, message) {\n const payload = primitives.objectCreate(null);\n payload.source = \"artifactshare\";\n const keys = primitives.objectKeys(message);\n for (let index = 0; index < keys.length; index++) {\n const key = keys[index];\n payload[key] = message[key];\n }\n return payload;\n }\n function installMessageListener(ctx) {\n ctx.primordials.savedAddEventListener(\"message\", function(event) {\n let data = event.data || {};\n if (event.source !== ctx.primordials.savedParent || data.source !== \"artifactshare-parent\") {\n return;\n }\n if (!ctx.previewCapability && data.kind === \"ready-check\" && typeof data.previewCapability === \"string\" && /^[a-f0-9]{64}$/.test(data.previewCapability) && Number.isSafeInteger(data.documentGeneration) && data.documentGeneration > 0) {\n ctx.previewCapability = data.previewCapability;\n ctx.previewGeneration = data.documentGeneration;\n }\n if (ctx.previewCapability) {\n if (data.previewCapability !== ctx.previewCapability || data.documentGeneration !== ctx.previewGeneration || !Number.isSafeInteger(data.sequence) || data.sequence <= ctx.previewReceiveSequence) return;\n ctx.previewReceiveSequence = data.sequence;\n }\n if (data.kind === \"ready-check\") {\n onReadyCheck(ctx, event);\n ctx.displayedVersionId = data.versionId || ctx.displayedVersionId;\n ctx.displayedPath = data.targetPath || ctx.displayedPath;\n ctx.textAnchorsEnabled = data.textAnchorsEnabled === true;\n setCommentLabels(ctx, data.commentLabels);\n } else if (data.kind === \"external-link-policy\" && (data.mode === \"parent\" || data.mode === \"direct\")) {\n ctx.externalLinkPolicyMode = data.mode;\n } else if (data.kind === \"comment-highlights\") {\n ctx.textAnchorsEnabled = data.textAnchorsEnabled === true;\n setCommentLabels(ctx, data.commentLabels);\n ctx.displayedVersionId = data.versionId || null;\n ctx.displayedPath = data.targetPath || null;\n applyHighlights(ctx, data.highlights);\n } else if (data.kind === \"scroll-to-comment\") {\n scrollToThread(ctx, data.threadId);\n } else if (data.kind === \"mermaid-rendered\") {\n installMermaidResults(ctx, data.renderToken, data.results);\n } else if (data.kind === \"annotate-mode\") {\n setAnnotateMode(ctx, data.enabled);\n } else if (data.kind === \"element-ping\") {\n pingElement(ctx, data.selector);\n } else if (data.kind === \"element-flash\") {\n flashElement(ctx, data.selector);\n } else if (data.kind === \"verify-anchors\") {\n if (Number.isSafeInteger(ctx.pendingVerificationId) && Number.isSafeInteger(data.verificationId) && data.verificationId < ctx.pendingVerificationId) return;\n ctx.pendingVerificationId = data.verificationId;\n verifyAnchors(ctx, data.anchors);\n }\n });\n }\n\n function reportHash(ctx, force = false) {\n try {\n if (ctx.readyChallenge && ctx.documentToken) {\n const hash = ctx.win.location.hash;\n const path = ctx.win.location.pathname;\n if (!force && ctx.lastHash === hash && ctx.lastHashPath === path) return;\n ctx.lastHash = hash;\n ctx.lastHashPath = path;\n send(ctx, {\n kind: \"hash-changed\",\n hash,\n path,\n token: ctx.documentToken\n });\n }\n } catch (e) {}\n }\n function installHashTracking(ctx) {\n ctx.primordials.addEventListener(ctx.win, \"hashchange\", () => reportHash(ctx));\n wrapHistory(ctx, \"pushState\");\n wrapHistory(ctx, \"replaceState\");\n }\n function wrapHistory(ctx, method) {\n const prototype = ctx.primordials.getPrototypeOf(ctx.win.history);\n const original = prototype[method];\n prototype[method] = function(...args) {\n const result = ctx.primordials.reflectApply(original, this, args);\n reportHash(ctx);\n return result;\n };\n }\n\n function installCspViolations(ctx) {\n ctx.doc.addEventListener(VIOLATION_REPORTER_MARKER, function(event) {\n const message = {\n kind: \"csp-violation\",\n directive: event.violatedDirective || event.effectiveDirective,\n blockedURI: event.blockedURI || \"inline\",\n sourceFile: event.sourceFile || null,\n lineNumber: event.lineNumber || null\n };\n if (typeof event.sample === \"string\" && event.sample.length > 0) {\n let sample = \"\";\n for (let index = 0; index < event.sample.length && index < 80; index++) sample += event.sample[index];\n message.sample = sample;\n }\n if (event.disposition === \"enforce\" || event.disposition === \"report\") message.disposition = event.disposition;\n if (ctx.readyChallenge === \"\") {\n if (ctx.pendingCspViolationCount < 100) {\n ctx.pendingCspViolations[ctx.pendingCspViolationCount] = message;\n ctx.pendingCspViolationCount += 1;\n }\n return;\n }\n send(ctx, message);\n });\n }\n\n function updateMarkdownToc(ctx) {\n let links = ctx.doc.querySelectorAll(\".md-toc a[href^=\\\"#\\\"]\");\n if (!links.length) return;\n let activeId = null;\n for (let index = 0; index < links.length; index++) {\n let id = links[index].getAttribute(\"href\").slice(1);\n let heading = ctx.doc.getElementById(id);\n if (heading && heading.getBoundingClientRect().top <= 96) activeId = id;\n }\n if (!activeId) activeId = links[0].getAttribute(\"href\").slice(1);\n for (let linkIndex = 0; linkIndex < links.length; linkIndex++) {\n if (links[linkIndex].getAttribute(\"href\").slice(1) === activeId) {\n links[linkIndex].setAttribute(\"aria-current\", \"location\");\n } else {\n links[linkIndex].removeAttribute(\"aria-current\");\n }\n }\n }\n function installCodeCopy(ctx) {\n ctx.doc.addEventListener(\"click\", function(event) {\n let target = event.target;\n let button = target && target.closest && target.closest(\"[data-code-copy]\");\n if (!button) return;\n let block = button.closest(\".md-code-block\");\n let code = block && block.querySelector(\"pre code\");\n if (!code) return;\n event.preventDefault();\n event.stopPropagation();\n let copied = function() {\n button.textContent = \"Copied\";\n button.setAttribute(\"aria-label\", \"Code copied\");\n ctx.win.setTimeout(function() {\n button.textContent = \"Copy\";\n button.setAttribute(\"aria-label\", \"Copy code\");\n }, 1500);\n };\n let fallback = function() {\n let textarea = ctx.doc.createElement(\"textarea\");\n textarea.setAttribute(anchorIgnoreAttribute(), \"\");\n textarea.value = code.textContent || \"\";\n textarea.style.position = \"fixed\";\n textarea.style.opacity = \"0\";\n ctx.doc.body.appendChild(textarea);\n textarea.select();\n try {\n if (ctx.doc.execCommand(\"copy\")) copied();\n } catch (error) {}\n textarea.remove();\n };\n if (ctx.win.navigator.clipboard && ctx.win.navigator.clipboard.writeText) {\n ctx.win.navigator.clipboard.writeText(code.textContent || \"\").then(copied, fallback);\n } else {\n fallback();\n }\n });\n }\n\n function rebuildAfterMutations(ctx) {\n let hasText = ctx.pendingHighlights.length > 0;\n for (let i = 0; !hasText && i < ctx.pendingAnchors.length; i++) {\n if (ctx.pendingAnchors[i].kind === \"text\") hasText = true;\n }\n if (!hasText) {\n verifyAnchors(ctx, ctx.pendingAnchors);\n return;\n }\n let engine = createTextAnchorEngine(anchorRoot(ctx));\n if (engine.text === ctx.measuredText) {\n ctx.win.clearTimeout(ctx.resolveTimer);\n ctx.resolveStartedAt = 0;\n try {\n applyHighlights(ctx, ctx.pendingHighlights, engine);\n } finally {\n verifyAnchors(ctx, ctx.pendingAnchors, engine);\n }\n } else {\n invalidateChangedPaint(ctx, engine);\n ctx.win.clearTimeout(ctx.resolveTimer);\n if (!ctx.resolveStartedAt) ctx.resolveStartedAt = Date.now();\n let snapshotGeneration = ctx.anchorSnapshotGeneration;\n ctx.resolveTimer = ctx.win.setTimeout(function() {\n ctx.resolveStartedAt = 0;\n if (snapshotGeneration !== ctx.anchorSnapshotGeneration) engine = createTextAnchorEngine(anchorRoot(ctx));\n try {\n applyHighlights(ctx, ctx.pendingHighlights, engine);\n } finally {\n verifyAnchors(ctx, ctx.pendingAnchors, engine);\n }\n }, Math.min(300, Math.max(0, 1e3 - (Date.now() - ctx.resolveStartedAt))));\n }\n }\n function handleMutations(ctx, records) {\n let root = anchorRoot(ctx);\n let rootReplaced = root !== ctx.observedAnchorRoot;\n ctx.observedAnchorRoot = root;\n let exclusionChanged = false;\n for (let recordIndex = 0; recordIndex < records.length; recordIndex++) {\n const record = records[recordIndex];\n if (record.type === \"attributes\" && (record.attributeName === anchorIgnoreAttribute() || record.attributeName === commentUiAttribute() || record.attributeName === \"class\")) {\n exclusionChanged = true;\n break;\n }\n }\n if (rootReplaced || exclusionChanged) ctx.anchorSnapshotGeneration++;\n if (!root || !ctx.doc.body || !ctx.pendingHighlights.length && !ctx.pendingAnchors.length) return;\n let hasRelevant = false;\n let hasRelevantContent = false;\n for (let recordIndex = 0; recordIndex < records.length; recordIndex++) {\n const record = records[recordIndex];\n if (record.type !== \"attributes\" && !root.contains(record.target)) continue;\n let element = record.target.nodeType === 1 ? record.target : record.target.parentElement;\n if (element && ctx.primordials.closest(element, ignoredMutationSelector())) continue;\n if (record.type === \"childList\") {\n let hasContentNode = false;\n for (let group = 0; group < 2; group++) {\n const nodes = group === 0 ? record.addedNodes : record.removedNodes;\n for (let index = 0; index < nodes.length; index++) {\n const node = nodes[index];\n if (node.nodeType !== 1 || !ctx.primordials.hasAttribute(node, anchorIgnoreAttribute()) && node.id !== highlightStyleId()) hasContentNode = true;\n }\n }\n if (!hasContentNode) continue;\n }\n hasRelevant = true;\n if (record.type !== \"attributes\") hasRelevantContent = true;\n }\n if (!rootReplaced && !hasRelevant) return;\n schedulePositionBadges(ctx);\n if (rootReplaced || hasRelevantContent) {\n rebuildAfterMutations(ctx);\n }\n }\n function installAnchorObserver(ctx) {\n ctx.observedAnchorRoot = anchorRoot(ctx);\n const observer = new ctx.win.MutationObserver((records) => handleMutations(ctx, records));\n ctx.anchorObserver = observer;\n observer.observe(ctx.doc.documentElement, {\n subtree: true,\n childList: true,\n characterData: true,\n attributes: true\n });\n return observer;\n }\n\n function capturePrimordials(win) {\n const savedParent = win.parent;\n const reflectApply = win.Reflect.apply;\n const savedPostMessage = win.Function.prototype.call.bind(savedParent.postMessage);\n const savedAddEventListener = win.addEventListener.bind(win);\n const trustedGetter = win.Object.getOwnPropertyDescriptor(win.Event.prototype, \"isTrusted\");\n const targetGetter = win.Object.getOwnPropertyDescriptor(win.Event.prototype, \"target\");\n const defaultPreventedGetter = win.Object.getOwnPropertyDescriptor(win.Event.prototype, \"defaultPrevented\");\n const persistedGetter = win.PageTransitionEvent ? win.Object.getOwnPropertyDescriptor(win.PageTransitionEvent.prototype, \"persisted\") : undefined;\n const buttonGetter = win.Object.getOwnPropertyDescriptor(win.MouseEvent.prototype, \"button\");\n const metaKeyGetter = win.Object.getOwnPropertyDescriptor(win.MouseEvent.prototype, \"metaKey\");\n const ctrlKeyGetter = win.Object.getOwnPropertyDescriptor(win.MouseEvent.prototype, \"ctrlKey\");\n const shiftKeyGetter = win.Object.getOwnPropertyDescriptor(win.MouseEvent.prototype, \"shiftKey\");\n const altKeyGetter = win.Object.getOwnPropertyDescriptor(win.MouseEvent.prototype, \"altKey\");\n const trustedGet = trustedGetter && trustedGetter.get ? win.Function.prototype.call.bind(trustedGetter.get) : null;\n const targetGet = targetGetter && targetGetter.get ? win.Function.prototype.call.bind(targetGetter.get) : null;\n const defaultPreventedGet = defaultPreventedGetter && defaultPreventedGetter.get ? win.Function.prototype.call.bind(defaultPreventedGetter.get) : null;\n const persistedGet = persistedGetter && persistedGetter.get ? win.Function.prototype.call.bind(persistedGetter.get) : null;\n const buttonGet = buttonGetter && buttonGetter.get ? win.Function.prototype.call.bind(buttonGetter.get) : null;\n const metaKeyGet = metaKeyGetter && metaKeyGetter.get ? win.Function.prototype.call.bind(metaKeyGetter.get) : null;\n const ctrlKeyGet = ctrlKeyGetter && ctrlKeyGetter.get ? win.Function.prototype.call.bind(ctrlKeyGetter.get) : null;\n const shiftKeyGet = shiftKeyGetter && shiftKeyGetter.get ? win.Function.prototype.call.bind(shiftKeyGetter.get) : null;\n const altKeyGet = altKeyGetter && altKeyGetter.get ? win.Function.prototype.call.bind(altKeyGetter.get) : null;\n const preventDefault = win.Function.prototype.call.bind(win.Event.prototype.preventDefault);\n const addEventListener = win.Function.prototype.call.bind(win.EventTarget.prototype.addEventListener);\n const rangeToString = win.Function.prototype.call.bind(win.Range.prototype.toString);\n const arrayMap = win.Function.prototype.call.bind(win.Array.prototype.map);\n const weakMapDelete = win.Function.prototype.call.bind(win.WeakMap.prototype.delete);\n const weakMapGet = win.Function.prototype.call.bind(win.WeakMap.prototype.get);\n const weakMapSet = win.Function.prototype.call.bind(win.WeakMap.prototype.set);\n const defineProperty = win.Object.defineProperty;\n const objectCreate = win.Object.create;\n const objectKeys = win.Object.keys;\n const closest = win.Function.prototype.call.bind(win.Element.prototype.closest);\n const getAttribute = win.Function.prototype.call.bind(win.Element.prototype.getAttribute);\n const hasAttribute = win.Function.prototype.call.bind(win.Element.prototype.hasAttribute);\n return {\n savedParent,\n reflectApply,\n getPrototypeOf: win.Object.getPrototypeOf,\n savedPostMessage,\n savedAddEventListener,\n trustedGetter,\n targetGetter,\n defaultPreventedGetter,\n buttonGetter,\n metaKeyGetter,\n ctrlKeyGetter,\n shiftKeyGetter,\n altKeyGetter,\n trustedGet,\n targetGet,\n defaultPreventedGet,\n persistedGet,\n buttonGet,\n metaKeyGet,\n ctrlKeyGet,\n shiftKeyGet,\n altKeyGet,\n preventDefault,\n addEventListener,\n rangeToString,\n arrayMap,\n weakMapDelete,\n weakMapGet,\n weakMapSet,\n defineProperty,\n objectCreate,\n objectKeys,\n closest,\n getAttribute,\n hasAttribute\n };\n }\n\n function createReporterState(win, primordials = capturePrimordials(win)) {\n return {\n win,\n doc: win.document,\n primordials,\n documentToken: \"\",\n readyChallenge: \"\",\n previewCapability: \"\",\n previewGeneration: 0,\n previewSendSequence: 0,\n previewReceiveSequence: 0,\n lastHash: null,\n lastHashPath: null,\n pendingCspViolations: primordials.objectCreate(null),\n pendingCspViolationCount: 0,\n externalLinkPolicyMode: \"parent\",\n pendingLinkClicks: new win.WeakMap(),\n highlightNames: [],\n textPaints: [],\n pendingHighlights: [],\n pendingAnchors: [],\n measuredText: null,\n anchorSnapshotGeneration: 0,\n paintedAnchors: [],\n resolveStartedAt: 0,\n resolveTimer: undefined,\n checkingTimer: undefined,\n checkingDeadlines: {},\n checkingHighlights: [],\n checkingAnchors: [],\n pendingVerificationId: null,\n resolutionGeneration: 0,\n lastResolutionSignature: \"\",\n displayedVersionId: null,\n displayedPath: null,\n badges: [],\n badgeOffsets: {},\n badgeDragged: false,\n appliedHighlightKey: \"\",\n textAnchorsEnabled: false,\n mermaidBlocks: primordials.objectCreate(null),\n mermaidRequested: false,\n commentLabels: {\n openOne: \"Open 1 unresolved comment on this text\",\n openOther: \"Open {n} unresolved comments on this text\",\n resolvedOne: \"Open 1 resolved comment on this text\",\n resolvedOther: \"Open {n} resolved comments on this text\"\n },\n reusableBadges: new win.Map(),\n svgActiveThreads: {},\n svgOverlayStyles: new win.WeakMap(),\n badgePositionFrame: 0,\n annotateModeEnabled: false,\n annotateHoverElement: null,\n readyCount: 0,\n observedAnchorRoot: win.document.body,\n anchorObserver: null,\n readyInterval: 0\n };\n }\n\n function installReporter(win) {\n if (win.parent === win) return;\n const primordials = capturePrimordials(win);\n const ctx = createReporterState(win, primordials);\n try {\n let random = new win.Uint8Array(32);\n ctx.win.crypto.getRandomValues(random);\n ctx.documentToken = ctx.primordials.arrayMap(random, function(byte) {\n return byte.toString(16).padStart(2, \"0\");\n }).join(\"\");\n } catch (e) {\n ctx.documentToken = \"\";\n }\n installHashTracking(ctx);\n installAnchorObserver(ctx);\n ctx.primordials.addEventListener(ctx.win, \"pagehide\", function(event) {\n if (readEventValue(ctx, ctx.primordials.persistedGet, event) === true) return;\n ctx.anchorObserver.disconnect();\n ctx.win.clearTimeout(ctx.resolveTimer);\n ctx.win.clearTimeout(ctx.checkingTimer);\n ctx.win.cancelAnimationFrame(ctx.badgePositionFrame);\n clearMarks(ctx);\n });\n ctx.doc.addEventListener(\"click\", function(event) {\n let selection = ctx.win.getSelection();\n if (selection && !selection.isCollapsed) return;\n let badge = hitComment(ctx, event);\n if (!badge) return;\n selectThreadFromElement(ctx, badge, rectFromPointer(ctx, event, badge.getBoundingClientRect()));\n event.preventDefault();\n event.stopPropagation();\n });\n ctx.primordials.addEventListener(ctx.doc, \"mousemove\", (event) => onAnnotateHover(ctx, event), true);\n ctx.primordials.addEventListener(ctx.doc, \"mouseover\", (event) => onAnnotateHover(ctx, event), true);\n ctx.primordials.addEventListener(ctx.doc, \"click\", (event) => onAnnotateClick(ctx, event), true);\n installMessageListener(ctx);\n ctx.doc.addEventListener(\"mouseup\", function() {\n ctx.win.setTimeout(() => sendSelection(ctx), 0);\n });\n ctx.doc.addEventListener(\"keyup\", function() {\n ctx.win.setTimeout(() => sendSelection(ctx), 0);\n });\n installCodeCopy(ctx);\n ctx.primordials.addEventListener(ctx.win, \"click\", (event) => prepareLinkClick(ctx, event), true);\n ctx.primordials.addEventListener(ctx.win, \"click\", (event) => finishLinkClick(ctx, event));\n ctx.doc.addEventListener(\"pointerdown\", (event) => sendOutsidePointerDown(ctx, event));\n installCspViolations(ctx);\n ctx.win.addEventListener(\"resize\", () => schedulePositionBadges(ctx));\n ctx.win.addEventListener(\"scroll\", () => schedulePositionBadges(ctx), true);\n ctx.win.addEventListener(\"load\", function() {\n if (!ctx.pendingHighlights.length && !ctx.pendingAnchors.length) return;\n let engine = createTextAnchorEngine(anchorRoot(ctx));\n try {\n applyHighlights(ctx, ctx.pendingHighlights, engine);\n } finally {\n verifyAnchors(ctx, ctx.pendingAnchors, engine);\n }\n });\n ctx.win.addEventListener(\"load\", () => schedulePositionBadges(ctx));\n ctx.win.addEventListener(\"load\", () => updateMarkdownToc(ctx));\n ctx.win.addEventListener(\"scroll\", () => updateMarkdownToc(ctx), { passive: true });\n if (ctx.doc.fonts && ctx.doc.fonts.ready) {\n ctx.doc.fonts.ready.then(() => schedulePositionBadges(ctx));\n }\n ctx.readyInterval = ctx.win.setInterval(function() {\n ready(ctx);\n if (++ctx.readyCount >= 20) ctx.win.clearInterval(ctx.readyInterval);\n }, 100);\n ready(ctx);\n return ctx;\n }\n\n installReporter(window);\n\n})();";
6293
6322
  //#endregion
6294
6323
  //#region ../viewer-kit/src/reporter-constants.ts
6295
6324
  const READY_CHECK_MESSAGE_SOURCE = "artifactshare-parent";
@@ -9328,6 +9357,78 @@ body {
9328
9357
  .md input[type="checkbox"] { margin-right: 0.4em; }
9329
9358
  `;
9330
9359
  //#endregion
9360
+ //#region src/preview/reporter-protocol.ts
9361
+ /** Self-contained so the exact validator can also run in the local shell.
9362
+ * This admits display observations only, never authorization or commands. */
9363
+ function validPreviewObservation(value) {
9364
+ const record = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
9365
+ const keys = (v, names) => Object.keys(v).length === names.length && names.every((key) => Object.hasOwn(v, key));
9366
+ const str = (v, max) => typeof v === "string" && v.length <= max;
9367
+ const integer = (v, max = Number.MAX_SAFE_INTEGER) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0 && v <= max;
9368
+ const rect = (v) => record(v) && keys(v, [
9369
+ "top",
9370
+ "left",
9371
+ "width",
9372
+ "height"
9373
+ ]) && [
9374
+ "top",
9375
+ "left",
9376
+ "width",
9377
+ "height"
9378
+ ].every((key) => typeof v[key] === "number" && Number.isFinite(v[key]) && Math.abs(v[key]) <= 1e6 && (key !== "width" && key !== "height" || v[key] >= 0));
9379
+ if (!record(value)) return false;
9380
+ const base = [
9381
+ "source",
9382
+ "kind",
9383
+ "previewCapability",
9384
+ "documentGeneration",
9385
+ "sequence"
9386
+ ];
9387
+ if (value.source !== "artifactshare" || typeof value.previewCapability !== "string" || !/^[a-f0-9]{64}$/.test(value.previewCapability) || !integer(value.documentGeneration) || !integer(value.sequence) || value.sequence === 0) return false;
9388
+ switch (value.kind) {
9389
+ case "ready": return keys(value, [
9390
+ ...base,
9391
+ "challenge",
9392
+ "token"
9393
+ ]) && str(value.challenge, 64) && typeof value.token === "string" && /^[a-f0-9]{64}$/.test(value.token);
9394
+ case "element-annotate": return keys(value, [
9395
+ ...base,
9396
+ "selector",
9397
+ "label",
9398
+ "contextText",
9399
+ "ownText",
9400
+ "tagName",
9401
+ "rect"
9402
+ ]) && str(value.selector, 4096) && str(value.label, 1024) && str(value.contextText, 4096) && str(value.ownText, 1e6) && str(value.tagName, 128) && rect(value.rect);
9403
+ case "text-selection": return keys(value, [
9404
+ ...base,
9405
+ "token",
9406
+ "quotedText",
9407
+ "prefixText",
9408
+ "suffixText",
9409
+ "textStart",
9410
+ "textEnd",
9411
+ "selectorFormat",
9412
+ "textHash",
9413
+ "ambiguousAtCreation",
9414
+ "versionId",
9415
+ "cssPath",
9416
+ "rect"
9417
+ ]) && typeof value.token === "string" && /^[a-f0-9]{64}$/.test(value.token) && str(value.quotedText, 16384) && value.quotedText.length > 0 && str(value.prefixText, 4096) && str(value.suffixText, 4096) && integer(value.textStart, 1e8) && integer(value.textEnd, 1e8) && value.textEnd - value.textStart === value.quotedText.length && value.selectorFormat === "normalized-v1" && typeof value.textHash === "string" && /^[a-f0-9]{64}$/.test(value.textHash) && typeof value.ambiguousAtCreation === "boolean" && value.versionId === null && (value.cssPath === null || str(value.cssPath, 4096)) && rect(value.rect);
9418
+ case "anchor-verdicts": return keys(value, [
9419
+ ...base,
9420
+ "verificationId",
9421
+ "generation",
9422
+ "verdicts"
9423
+ ]) && integer(value.verificationId) && integer(value.generation) && Array.isArray(value.verdicts) && value.verdicts.length <= 1e3 && new Set(value.verdicts.map((v) => record(v) ? v.thread : null)).size === value.verdicts.length && value.verdicts.every((v) => record(v) && keys(v, [
9424
+ "thread",
9425
+ "attached",
9426
+ "position_state"
9427
+ ]) && str(v.thread, 128) && typeof v.attached === "boolean" && (v.attached ? v.position_state === "attached" : ["checking", "needs-check"].includes(v.position_state)));
9428
+ default: return false;
9429
+ }
9430
+ }
9431
+ //#endregion
9331
9432
  //#region src/preview/shell.ts
9332
9433
  function escapeHtml(value) {
9333
9434
  return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;");
@@ -9352,6 +9453,7 @@ function renderPreviewShell(options) {
9352
9453
  <html lang="ja">
9353
9454
  <head>
9354
9455
  <meta charset="utf-8">
9456
+ <meta name="referrer" content="no-referrer">
9355
9457
  <meta name="viewport" content="width=device-width, initial-scale=1">
9356
9458
  <title>${escapeHtml(fileName)} - as preview</title>
9357
9459
  <style>
@@ -9520,9 +9622,10 @@ function renderPreviewShell(options) {
9520
9622
  </header>
9521
9623
  <div class="layout">
9522
9624
  <div class="doc-wrap">
9523
- <iframe id="artifactFrame" src="/artifact" title="${escapeHtml(fileName)}"></iframe>
9625
+ <iframe id="artifactFrame" sandbox="allow-scripts" referrerpolicy="no-referrer" src="/artifact" title="${escapeHtml(fileName)}"></iframe>
9524
9626
  </div>
9525
9627
  <aside class="panel">
9628
+ <p data-msg="preview.isolationNotice" style="font-size:12px;color:var(--muted-foreground);margin:0"></p>
9526
9629
  <h2 data-msg="preview.panelTitle"></h2>
9527
9630
  <div class="submit-bar" id="submitBar">
9528
9631
  <button class="btn btn-primary" id="submitBtn" aria-describedby="batchStatus"></button>
@@ -9664,16 +9767,22 @@ function renderPreviewShell(options) {
9664
9767
  let ended = false;
9665
9768
 
9666
9769
  // --- iframe protocol ----------------------------------------------------
9770
+ const validObservation = ${validPreviewObservation.toString()};
9771
+ let documentGeneration = 0;
9772
+ let previewCapability = '';
9773
+ let sendSequence = 0;
9774
+ let receiveSequence = 0;
9775
+ let sharePopup = null;
9667
9776
  function postToFrame(message) {
9668
9777
  try {
9669
9778
  frame.contentWindow.postMessage(
9670
- Object.assign({ source: CONFIG.readySource }, message), '*');
9779
+ Object.assign({ source: CONFIG.readySource, previewCapability, documentGeneration, sequence: ++sendSequence }, message), '*');
9671
9780
  } catch (error) {}
9672
9781
  }
9673
9782
  function readyPayload() {
9674
9783
  return {
9675
9784
  kind: CONFIG.readyKind,
9676
- challenge: String(Math.random()).slice(2) + String(Date.now()),
9785
+ challenge: previewCapability,
9677
9786
  textAnchorsEnabled: true,
9678
9787
  commentLabels: {},
9679
9788
  };
@@ -9681,6 +9790,10 @@ function renderPreviewShell(options) {
9681
9790
  let readyBurstTimer = null;
9682
9791
  function startReadyBurst() {
9683
9792
  if (readyBurstTimer) clearInterval(readyBurstTimer);
9793
+ documentGeneration++;
9794
+ previewCapability = Array.from(crypto.getRandomValues(new Uint8Array(32)), byte => byte.toString(16).padStart(2, '0')).join('');
9795
+ sendSequence = 0;
9796
+ receiveSequence = 0;
9684
9797
  let sent = 0;
9685
9798
  const payload = readyPayload();
9686
9799
  postToFrame(payload);
@@ -9705,7 +9818,7 @@ function renderPreviewShell(options) {
9705
9818
  // share finished; everything else must come from the artifact frame.
9706
9819
  const data = event.data || {};
9707
9820
  if (data.source === 'artifactshare-preview-share') {
9708
- if (event.origin !== CONFIG.shareOrigin) return;
9821
+ if (!sharePopup || event.source !== sharePopup || event.origin !== CONFIG.shareOrigin) return;
9709
9822
  // "Preview ended" has to be true for the agent too: without the stop,
9710
9823
  // the process keeps serving and pending next polls never receive
9711
9824
  // session_ended.
@@ -9719,9 +9832,12 @@ function renderPreviewShell(options) {
9719
9832
  // check any page that opens this port can post a crafted element-annotate
9720
9833
  // and steer what the user is about to write into the store.
9721
9834
  if (event.source !== frame.contentWindow) return;
9722
- if (event.origin !== window.location.origin) return;
9723
- if (data.source !== 'artifactshare') return;
9835
+ if (ended || !previewCapability || event.origin !== 'null') return;
9836
+ if (!validObservation(data) || data.previewCapability !== previewCapability ||
9837
+ data.documentGeneration !== documentGeneration || data.sequence <= receiveSequence) return;
9838
+ receiveSequence = data.sequence;
9724
9839
  if (data.kind === 'element-annotate') {
9840
+ if (!annotateMode) return;
9725
9841
  openPopover({
9726
9842
  kind: 'element', state: 'attached',
9727
9843
  selector: data.selector, label: data.label, contextText: data.contextText,
@@ -9930,13 +10046,14 @@ function renderPreviewShell(options) {
9930
10046
 
9931
10047
  // --- reload + orphan handling ------------------------------------------
9932
10048
  function reloadFrame(nextRevision) {
10049
+ previewCapability = '';
10050
+ hidePopover();
9933
10051
  verificationId++;
9934
10052
  verificationGeneration = -1;
9935
10053
  let scrollY = 0;
9936
10054
  try { scrollY = frame.contentWindow.scrollY || 0; } catch (error) {}
9937
10055
  const restore = () => {
9938
10056
  try { frame.contentWindow.scrollTo(0, scrollY); } catch (error) {}
9939
- startReadyBurst();
9940
10057
  setTimeout(() => { lastVerifiedAnchors = null; checkOrphans(); }, 400);
9941
10058
  frame.removeEventListener('load', restore);
9942
10059
  };
@@ -9984,24 +10101,16 @@ function renderPreviewShell(options) {
9984
10101
  const attached = new Map((verdicts || []).map((v) => [v.thread, v.attached === true]));
9985
10102
  checkingThreads = new Set((verdicts || []).filter(v => v.position_state === 'checking').map(v => v.thread));
9986
10103
  const newlyOrphaned = [];
9987
- const states = [];
9988
10104
  annotations.forEach((annotation) => {
9989
10105
  if (!attached.has(annotation.thread) || checkingThreads.has(annotation.thread)) return;
9990
- const anchor = annotation.anchor;
9991
10106
  const found = attached.get(annotation.thread);
9992
10107
  if (!found && !orphanedThreads.has(annotation.thread)) {
9993
10108
  newlyOrphaned.push(annotation.thread);
9994
10109
  }
9995
10110
  if (!found) orphanedThreads.add(annotation.thread);
9996
10111
  else orphanedThreads.delete(annotation.thread);
9997
- const nextState = found ? 'attached' : 'orphaned';
9998
- if (anchor.state !== nextState || (anchor.kind === 'text' && anchor.position_state !== (found ? 'attached' : 'needs-check'))) {
9999
- states.push({ thread: annotation.thread, state: nextState });
10000
- }
10001
10112
  });
10002
- if (states.length > 0) {
10003
- api('POST', '/api/annotations/anchor-state', { states });
10004
- }
10113
+ // Reporter observations are display-only. Persist only explicit user actions.
10005
10114
  renderPanel();
10006
10115
  if (newlyOrphaned.length > 0) {
10007
10116
  document.getElementById('orphanText').textContent =
@@ -10085,13 +10194,18 @@ function renderPreviewShell(options) {
10085
10194
  function showEnded() {
10086
10195
  if (ended) return;
10087
10196
  ended = true;
10197
+ previewCapability = '';
10198
+ if (readyBurstTimer) clearInterval(readyBurstTimer);
10088
10199
  events.close();
10089
10200
  document.getElementById('endedScreen').classList.add('show');
10090
10201
  }
10091
10202
 
10092
10203
  // --- share --------------------------------------------------------------
10093
10204
  document.getElementById('shareBtn').addEventListener('click', () => {
10094
- window.open(CONFIG.shareOrigin + '/', 'as-preview-share', 'width=440,height=560');
10205
+ if (sharePopup && !sharePopup.closed) {
10206
+ sharePopup.close();
10207
+ }
10208
+ sharePopup = window.open(CONFIG.shareOrigin + '/', '_blank', 'width=440,height=560');
10095
10209
  });
10096
10210
 
10097
10211
  // --- boot ---------------------------------------------------------------
@@ -10284,6 +10398,10 @@ async function startPreviewServer(options) {
10284
10398
  }
10285
10399
  const method = request.method ?? "GET";
10286
10400
  if (method === "POST" || method === "DELETE") {
10401
+ if (!mutationOriginAllowed(request.headers.origin, request.headers.host, request.headers["sec-fetch-site"])) {
10402
+ sendJson(response, 403, { error: "forbidden_origin" });
10403
+ return false;
10404
+ }
10287
10405
  if (!mutationHeadersValid(request)) {
10288
10406
  sendJson(response, 403, { error: "missing_preview_header" });
10289
10407
  return false;
@@ -10292,6 +10410,8 @@ async function startPreviewServer(options) {
10292
10410
  return true;
10293
10411
  }
10294
10412
  function serveArtifact(response) {
10413
+ response.setHeader("Content-Security-Policy", "sandbox allow-scripts");
10414
+ response.setHeader("Referrer-Policy", "no-referrer");
10295
10415
  let bytes;
10296
10416
  try {
10297
10417
  bytes = readFileSync(filePath);
@@ -11739,45 +11859,636 @@ async function runChangelog(_parsed, mode) {
11739
11859
  return writeSuccess("changelog", await buildChangelogData(await loadCliVersion()), mode);
11740
11860
  }
11741
11861
  //#endregion
11862
+ //#region src/write-boundary.ts
11863
+ var WriteBoundaryError = class extends Error {
11864
+ path;
11865
+ error;
11866
+ constructor(path, hint = "Choose a regular directory without links, check retained recovery paths, and retry.", message = `Unsafe or changed write path ${path}.`) {
11867
+ super(message);
11868
+ this.path = path;
11869
+ this.error = validationError(this.message, hint);
11870
+ }
11871
+ };
11872
+ var WriteFileSystemError = class extends Error {
11873
+ path;
11874
+ constructor(path, cause) {
11875
+ super(`Could not complete a filesystem operation at ${path}.`, { cause });
11876
+ this.path = path;
11877
+ }
11878
+ };
11879
+ const same = (a, b) => a.dev === b.dev && a.ino === b.ino && a.isDirectory() === b.isDirectory() && a.isFile() === b.isFile();
11880
+ /** Observed identity checks, not an atomic directory-relative filesystem API. */
11881
+ var WriteBoundary = class {
11882
+ dependencies;
11883
+ entries = /* @__PURE__ */ new Map();
11884
+ children = /* @__PURE__ */ new Map();
11885
+ trustedParents = /* @__PURE__ */ new Set();
11886
+ absent = /* @__PURE__ */ new Set();
11887
+ guards = /* @__PURE__ */ new Set();
11888
+ watch(...paths) {
11889
+ for (const path of paths) this.guards.add(resolve(path));
11890
+ }
11891
+ backupPaths = [];
11892
+ workspace;
11893
+ constructor(dependencies = {}) {
11894
+ this.dependencies = dependencies;
11895
+ }
11896
+ setEntry(path, entry) {
11897
+ this.entries.set(path, entry);
11898
+ const parent = dirname(path);
11899
+ if (parent === path) return;
11900
+ let children = this.children.get(parent);
11901
+ if (!children) this.children.set(parent, children = /* @__PURE__ */ new Set());
11902
+ children.add(path);
11903
+ }
11904
+ deleteEntry(path) {
11905
+ this.entries.delete(path);
11906
+ this.children.get(dirname(path))?.delete(path);
11907
+ }
11908
+ *subtree(path) {
11909
+ const entry = this.entries.get(path);
11910
+ if (entry) yield [path, entry];
11911
+ for (const child of this.children.get(path) ?? []) yield* this.subtree(child);
11912
+ }
11913
+ async outputParent(path) {
11914
+ path = resolve(path);
11915
+ if (this.entries.has(path)) {
11916
+ await this.record(path, true);
11917
+ return;
11918
+ }
11919
+ this.trustedParents.add(path);
11920
+ this.watch(path);
11921
+ if (!await this.record(path, true)) await this.outputParent(dirname(path));
11922
+ }
11923
+ async io(path, action) {
11924
+ try {
11925
+ return await action();
11926
+ } catch (error) {
11927
+ if (error instanceof WriteBoundaryError || error instanceof WriteFileSystemError) throw error;
11928
+ throw new WriteFileSystemError(path, error);
11929
+ }
11930
+ }
11931
+ async stat(path) {
11932
+ try {
11933
+ const s = await (this.trustedParents.has(path) ? this.dependencies.stat ?? ((name) => fs.stat(name, { bigint: true })) : this.dependencies.lstat ?? ((name) => fs.lstat(name, { bigint: true })))(path);
11934
+ if (s.isSymbolicLink() || !s.isDirectory() && !s.isFile() || typeof s.dev !== "bigint" || typeof s.ino !== "bigint" || s.ino <= 0n) throw new WriteBoundaryError(path);
11935
+ return s;
11936
+ } catch (error) {
11937
+ if (error.code === "ENOENT") return null;
11938
+ throw new WriteBoundaryError(path);
11939
+ }
11940
+ }
11941
+ async record(path, directory = false) {
11942
+ path = resolve(path);
11943
+ if (this.entries.has(path) || this.absent.has(path)) {
11944
+ await this.check(path);
11945
+ if (directory && this.entries.has(path) && !this.entries.get(path).stat.isDirectory()) throw new WriteBoundaryError(path);
11946
+ return this.entries.has(path);
11947
+ }
11948
+ const s = await this.stat(path);
11949
+ if (!s) {
11950
+ this.absent.add(path);
11951
+ return false;
11952
+ }
11953
+ if (directory && !s.isDirectory()) throw new WriteBoundaryError(path);
11954
+ this.setEntry(path, {
11955
+ stat: s,
11956
+ owned: false
11957
+ });
11958
+ await this.check(path);
11959
+ return true;
11960
+ }
11961
+ async check(...paths) {
11962
+ const selected = /* @__PURE__ */ new Set();
11963
+ for (const target of [
11964
+ ...this.guards,
11965
+ ...paths,
11966
+ ...this.workspace ? [this.workspace] : []
11967
+ ]) {
11968
+ let path = resolve(target);
11969
+ selected.add(path);
11970
+ while (!this.trustedParents.has(path)) {
11971
+ const parent = dirname(path);
11972
+ if (parent === path || !this.entries.has(parent)) break;
11973
+ selected.add(parent);
11974
+ path = parent;
11975
+ }
11976
+ }
11977
+ const observed = /* @__PURE__ */ new Map();
11978
+ const inspect = async (path) => {
11979
+ if (!observed.has(path)) observed.set(path, await this.stat(path));
11980
+ return observed.get(path);
11981
+ };
11982
+ for (const path of selected) {
11983
+ const entry = this.entries.get(path);
11984
+ if (!entry) {
11985
+ if (this.absent.has(path) && await inspect(path)) throw new WriteBoundaryError(path);
11986
+ continue;
11987
+ }
11988
+ const s = await inspect(path);
11989
+ if (!s || !same(s, entry.stat)) throw new WriteBoundaryError(path);
11990
+ const parent = this.entries.get(dirname(path));
11991
+ if (parent && !this.trustedParents.has(path)) {
11992
+ const physical = await (this.dependencies.realpath ?? fs.realpath)(path).catch(() => {
11993
+ throw new WriteBoundaryError(path);
11994
+ });
11995
+ const actualEntry = await inspect(physical);
11996
+ if (!actualEntry || !same(actualEntry, s)) throw new WriteBoundaryError(path);
11997
+ const actual = await inspect(dirname(physical));
11998
+ if (!actual || !same(actual, parent.stat)) throw new WriteBoundaryError(path);
11999
+ }
12000
+ }
12001
+ }
12002
+ async directory(path) {
12003
+ path = resolve(path);
12004
+ if (this.entries.has(path)) {
12005
+ await this.check(path);
12006
+ if (!this.entries.get(path).stat.isDirectory()) throw new WriteBoundaryError(path);
12007
+ return;
12008
+ }
12009
+ if (await this.record(path, true)) return;
12010
+ await this.directory(dirname(path));
12011
+ await this.before("create", path);
12012
+ await this.io(path, () => fs.mkdir(path));
12013
+ this.absent.delete(path);
12014
+ const s = await this.stat(path);
12015
+ if (!s?.isDirectory()) throw new WriteBoundaryError(path);
12016
+ this.setEntry(path, {
12017
+ stat: s,
12018
+ owned: true
12019
+ });
12020
+ await this.check(path);
12021
+ }
12022
+ async tree(path) {
12023
+ if (!await this.record(path)) return;
12024
+ if (this.entries.get(resolve(path)).stat.isDirectory()) {
12025
+ for (const name of await this.io(path, () => fs.readdir(path))) await this.tree(join(path, name));
12026
+ await this.check(path);
12027
+ }
12028
+ }
12029
+ async checkTree(path) {
12030
+ await this.check(path, ...[...this.subtree(resolve(path))].map(([name]) => name));
12031
+ }
12032
+ async before(phase, path, ...otherPaths) {
12033
+ await this.dependencies.checkpoint?.(phase, path);
12034
+ await this.check(path, ...otherPaths);
12035
+ }
12036
+ async privateDirectory(parent) {
12037
+ await this.directory(parent);
12038
+ await this.before("create", parent);
12039
+ const path = await this.io(parent, () => fs.mkdtemp(join(parent, ".artifactshare-")));
12040
+ const stat = await this.stat(path);
12041
+ if (!stat?.isDirectory()) throw new WriteBoundaryError(path);
12042
+ this.setEntry(path, {
12043
+ stat,
12044
+ owned: true
12045
+ });
12046
+ await this.check(path);
12047
+ return path;
12048
+ }
12049
+ async read(path) {
12050
+ path = resolve(path);
12051
+ if (!await this.record(path)) return null;
12052
+ const entry = this.entries.get(path);
12053
+ if (!entry.stat.isFile()) throw new WriteBoundaryError(path);
12054
+ await this.before("read", path);
12055
+ const handle = await this.io(path, () => (this.dependencies.open ?? fs.open)(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)));
12056
+ try {
12057
+ const s = await handle.stat({ bigint: true });
12058
+ if (!same(s, entry.stat)) throw new WriteBoundaryError(path);
12059
+ const text = await this.io(path, () => handle.readFile("utf8"));
12060
+ await this.check(path);
12061
+ const after = await handle.stat({ bigint: true });
12062
+ if (!same(after, s) || after.size !== s.size || after.mtimeNs !== s.mtimeNs) throw new WriteBoundaryError(path);
12063
+ return text;
12064
+ } finally {
12065
+ await this.io(path, () => handle.close());
12066
+ }
12067
+ }
12068
+ async write(path, content, mode) {
12069
+ path = resolve(path);
12070
+ await this.directory(dirname(path));
12071
+ if (await this.record(path)) throw new WriteBoundaryError(path);
12072
+ await this.before("create", path);
12073
+ const handle = await this.io(path, () => (this.dependencies.open ?? fs.open)(path, "wx", mode ?? 438));
12074
+ try {
12075
+ const stat = await handle.stat({ bigint: true });
12076
+ this.absent.delete(path);
12077
+ this.setEntry(path, {
12078
+ stat,
12079
+ owned: true
12080
+ });
12081
+ await this.check(path);
12082
+ await this.io(path, () => handle.writeFile(content));
12083
+ if (mode !== void 0) await this.io(path, () => handle.chmod(mode));
12084
+ await this.check(path);
12085
+ } finally {
12086
+ await this.io(path, () => handle.close());
12087
+ }
12088
+ }
12089
+ async move(source, destination, replace = false) {
12090
+ source = resolve(source);
12091
+ destination = resolve(destination);
12092
+ if (!this.entries.has(source)) throw new WriteBoundaryError(source);
12093
+ for (const path of [source, destination]) if (!this.entries.get(dirname(path))?.stat.isDirectory()) throw new WriteBoundaryError(dirname(path));
12094
+ await this.record(destination);
12095
+ if (!replace && this.entries.has(destination)) throw new WriteBoundaryError(destination);
12096
+ await this.before("rename", destination, source);
12097
+ await this.io(destination, () => (this.dependencies.rename ?? fs.rename)(source, destination));
12098
+ this.deleteEntry(destination);
12099
+ this.absent.delete(destination);
12100
+ const moved = [...this.subtree(source)];
12101
+ for (const [path] of moved) this.deleteEntry(path);
12102
+ for (const [path, entry] of moved) this.setEntry(destination + path.slice(source.length), entry);
12103
+ this.absent.add(source);
12104
+ await this.check(source, destination);
12105
+ }
12106
+ async replace(source, destination, retain = true) {
12107
+ const guarded = this.guards.has(resolve(destination));
12108
+ this.watch(destination);
12109
+ try {
12110
+ let backup;
12111
+ if (await this.record(destination)) {
12112
+ if (!retain) {
12113
+ await this.move(source, destination, true);
12114
+ return;
12115
+ }
12116
+ if (!this.workspace) throw new WriteBoundaryError(destination);
12117
+ backup = join(this.workspace, `backup-${randomUUID()}`);
12118
+ await this.move(destination, backup);
12119
+ this.backupPaths.push(backup);
12120
+ }
12121
+ try {
12122
+ await this.move(source, destination);
12123
+ } catch (error) {
12124
+ if (backup) try {
12125
+ await this.before("rollback", destination);
12126
+ await this.move(backup, destination);
12127
+ this.backupPaths.splice(this.backupPaths.indexOf(backup), 1);
12128
+ } catch (restoreError) {
12129
+ const failure = new WriteBoundaryError(destination, `Publication failed and backup restoration could not finish. Recover original data at ${backup}; inspect it before manual cleanup.`);
12130
+ Object.defineProperty(failure, "cause", { value: new AggregateError([error, restoreError]) });
12131
+ throw failure;
12132
+ }
12133
+ throw error;
12134
+ }
12135
+ } finally {
12136
+ if (!guarded) this.guards.delete(resolve(destination));
12137
+ }
12138
+ }
12139
+ async atomicWrite(path, content, retain = false, temporaryParent = dirname(path)) {
12140
+ await this.record(path);
12141
+ const temp = join(temporaryParent, `.artifactshare-${randomUUID()}.tmp`);
12142
+ const existing = this.entries.get(resolve(path));
12143
+ await this.write(temp, content, existing ? Number(existing.stat.mode & 511n) : void 0);
12144
+ await this.replace(temp, path, retain);
12145
+ }
12146
+ async cleanup() {
12147
+ const retained = (path) => this.backupPaths.some((backup) => backup === path || backup.startsWith(`${path}${sep}`));
12148
+ for (const [path, entry] of [...this.entries].reverse()) {
12149
+ if (!entry.owned || retained(path)) continue;
12150
+ await this.before("remove", path);
12151
+ if (entry.stat.isDirectory()) await this.io(path, () => (this.dependencies.rmdir ?? fs.rmdir)(path));
12152
+ else await this.io(path, () => (this.dependencies.unlink ?? fs.unlink)(path));
12153
+ this.deleteEntry(path);
12154
+ this.absent.add(path);
12155
+ }
12156
+ }
12157
+ async retainedWorkspace() {
12158
+ if (!this.workspace || !this.entries.has(this.workspace)) return;
12159
+ try {
12160
+ await this.check(this.workspace);
12161
+ if ((await fs.readdir(this.workspace)).length > 0) return this.workspace;
12162
+ } catch {}
12163
+ }
12164
+ async finish() {
12165
+ await this.cleanup();
12166
+ }
12167
+ keep(path) {
12168
+ path = resolve(path);
12169
+ for (const [, entry] of this.subtree(path)) entry.owned = false;
12170
+ for (let parent = dirname(path);; parent = dirname(parent)) {
12171
+ const entry = this.entries.get(parent);
12172
+ if (entry) entry.owned = false;
12173
+ if (dirname(parent) === parent) break;
12174
+ }
12175
+ }
12176
+ };
12177
+ //#endregion
12178
+ //#region src/upload-boundary.ts
12179
+ const hints = {
12180
+ parent_traversal: "Pass a direct absolute path without any .. component.",
12181
+ link: "Copy the file into the selection or pass the target by absolute path.",
12182
+ outside_cwd: "Pass an absolute path to select a file outside the current directory.",
12183
+ not_found: "Check the path and retry.",
12184
+ changed: "The selection changed while reading. Retry the command.",
12185
+ unsupported_guarantee: "Stable file identity (dev/ino) and the available no-follow open guarantee are required. Select a filesystem that supports them.",
12186
+ invalid_type: "Select a regular file or directory."
12187
+ };
12188
+ const messages = {
12189
+ parent_traversal: "Parent traversal (..) is not allowed",
12190
+ link: "A symbolic link is not allowed",
12191
+ outside_cwd: "The selection leaves the current directory",
12192
+ not_found: "Path was not found",
12193
+ changed: "The selection changed while reading",
12194
+ unsupported_guarantee: "The filesystem cannot provide the required guarantee",
12195
+ invalid_type: "Path must be a regular file or directory"
12196
+ };
12197
+ var UploadBoundaryError = class extends Error {
12198
+ error;
12199
+ constructor(display, reason, cause, guarantee) {
12200
+ super(`Upload path ${display}: ${messages[reason]}.`, { cause });
12201
+ this.error = cliError({
12202
+ code: "validation_failed",
12203
+ message: this.message,
12204
+ why: this.message,
12205
+ hint: guarantee ? `Required guarantee unavailable: ${guarantee}. Select a filesystem that supports it.` : hints[reason],
12206
+ agentRecoverable: true,
12207
+ requiresHuman: false,
12208
+ recovery: { kind: reason === "changed" ? "retry_later" : "change_input" },
12209
+ details: {
12210
+ path: display,
12211
+ reason,
12212
+ ...guarantee ? { guarantee } : {}
12213
+ }
12214
+ });
12215
+ Object.defineProperty(this.error, "cause", { value: cause });
12216
+ }
12217
+ };
12218
+ var UploadReadFailure = class extends Error {
12219
+ error;
12220
+ constructor(error, cause) {
12221
+ super(error.message, { cause });
12222
+ this.error = error;
12223
+ }
12224
+ };
12225
+ function uploadReadError(error, display) {
12226
+ if (error instanceof UploadReadFailure) return error.error;
12227
+ if (error instanceof UploadBoundaryError) return error.error;
12228
+ const result = cliError({
12229
+ code: "upload_read_failed",
12230
+ message: `Could not read upload path ${display}.`,
12231
+ why: "The local filesystem rejected an upload read.",
12232
+ hint: "Check filesystem availability and permissions, then retry.",
12233
+ agentRecoverable: true,
12234
+ requiresHuman: false,
12235
+ recovery: { kind: "retry_later" },
12236
+ details: {
12237
+ path: display,
12238
+ errno: error?.code
12239
+ }
12240
+ });
12241
+ Object.defineProperty(result, "cause", { value: error });
12242
+ return result;
12243
+ }
12244
+ async function prepareUploadSelection(input, singleFile = false, dependencies = {}) {
12245
+ const fail = (display, reason, cause, guarantee) => {
12246
+ throw new UploadBoundaryError(display, reason, cause, guarantee);
12247
+ };
12248
+ if (input.replace(/^[a-z]:/iu, "").split(/[\\/]/u).includes("..")) fail(input, "parent_traversal");
12249
+ const paths = dependencies.paths ?? path;
12250
+ const cwd = dependencies.cwd ?? process.cwd();
12251
+ const inspect = dependencies.lstat ?? ((name) => fs.lstat(name, { bigint: true }));
12252
+ const checkpoint = dependencies.checkpoint ?? (async () => {});
12253
+ const identity = (s, display) => {
12254
+ if (typeof s.dev !== "bigint" || typeof s.ino !== "bigint" || s.ino <= 0n) fail(display, "unsupported_guarantee", void 0, "stable file identity (dev/ino)");
12255
+ };
12256
+ const same = (a, b) => a.dev === b.dev && a.ino === b.ino;
12257
+ const sameFile = (actual, recorded) => actual.isFile() && same(actual, recorded) && actual.mode === recorded.mode && actual.size === recorded.size;
12258
+ const checkType = (s, display) => {
12259
+ if (s.isSymbolicLink()) fail(display, "link");
12260
+ identity(s, display);
12261
+ if (!s.isFile() && !s.isDirectory()) fail(display, "invalid_type");
12262
+ };
12263
+ const get = async (name, display, recorded = false) => {
12264
+ try {
12265
+ return await inspect(name);
12266
+ } catch (error) {
12267
+ const code = error.code;
12268
+ if (code === "ENOENT" || code === "ENOTDIR") fail(display, recorded ? "changed" : "not_found", error);
12269
+ if (code === "ELOOP") fail(display, "link", error);
12270
+ throw new UploadReadFailure(uploadReadError(error, display), error);
12271
+ }
12272
+ };
12273
+ const physicalPaths = /* @__PURE__ */ new Map();
12274
+ const physicalPath = async (name, display) => {
12275
+ const cached = physicalPaths.get(name);
12276
+ if (cached !== void 0) return cached;
12277
+ try {
12278
+ const resolved = await (dependencies.realpath ?? fs.realpath)(name);
12279
+ physicalPaths.set(name, resolved);
12280
+ return resolved;
12281
+ } catch (error) {
12282
+ const code = error.code;
12283
+ if (code === "ENOENT" || code === "ENOTDIR") fail(display, "changed", error);
12284
+ if (code === "ELOOP") fail(display, "link", error);
12285
+ throw new UploadReadFailure(uploadReadError(error, display), error);
12286
+ }
12287
+ };
12288
+ const checkPhysicalEntry = async (name, display, parent, storedName) => {
12289
+ const resolved = await physicalPath(name, display);
12290
+ if (storedName !== void 0 && storedName !== paths.basename(resolved)) fail(display, "link");
12291
+ const actualParent = await get(paths.dirname(resolved), display, true);
12292
+ checkType(actualParent, display);
12293
+ if (!actualParent.isDirectory() || !same(actualParent, parent)) fail(display, "link");
12294
+ };
12295
+ const recheck = async (entry, directory) => {
12296
+ const s = await get(entry.path, entry.display, true);
12297
+ if (s.isSymbolicLink()) fail(entry.display, "link");
12298
+ identity(s, entry.display);
12299
+ if (directory ? !s.isDirectory() || !same(s, entry.stat) : !sameFile(s, entry.stat)) fail(entry.display, "changed");
12300
+ };
12301
+ const checkChain = async (chain) => {
12302
+ for (const entry of chain) await recheck(entry, true);
12303
+ };
12304
+ let offending = input;
12305
+ try {
12306
+ const explicit = paths.isAbsolute(input) || paths.sep === "\\" && /^[a-z]:/iu.test(input);
12307
+ let selectedPath = paths.resolve(cwd, input);
12308
+ const chain = [];
12309
+ let selected;
12310
+ if (!explicit) {
12311
+ const root = await physicalPath(cwd, input);
12312
+ physicalPaths.set(root, root);
12313
+ const rootStat = await get(root, input);
12314
+ checkType(rootStat, input);
12315
+ chain.push({
12316
+ path: root,
12317
+ display: input,
12318
+ stat: rootStat
12319
+ });
12320
+ let cursor = root;
12321
+ const components = input.split(paths.sep === "\\" ? /[\\/]/u : /\//u).filter((part) => part !== "" && part !== ".");
12322
+ selected = rootStat;
12323
+ for (let index = 0; index < components.length; index++) {
12324
+ await checkChain(chain);
12325
+ cursor = paths.join(cursor, components[index]);
12326
+ selected = await get(cursor, input);
12327
+ checkType(selected, input);
12328
+ await checkPhysicalEntry(cursor, input, chain[chain.length - 1].stat);
12329
+ await checkChain(chain);
12330
+ if (index < components.length - 1) {
12331
+ if (!selected.isDirectory()) fail(input, "not_found");
12332
+ chain.push({
12333
+ path: cursor,
12334
+ display: input,
12335
+ stat: selected
12336
+ });
12337
+ }
12338
+ }
12339
+ if (components.length > 0) {
12340
+ const typed = await get(`${cwd}${cwd.endsWith(paths.sep) ? "" : paths.sep}${input}`, input);
12341
+ checkType(typed, input);
12342
+ if (!same(selected, typed)) fail(input, "outside_cwd");
12343
+ }
12344
+ selectedPath = cursor;
12345
+ } else {
12346
+ selected = await get(selectedPath, input);
12347
+ checkType(selected, input);
12348
+ const parent = await get(await physicalPath(paths.dirname(selectedPath), input), input);
12349
+ checkType(parent, input);
12350
+ await checkPhysicalEntry(selectedPath, input, parent);
12351
+ }
12352
+ if (singleFile && !selected.isFile()) fail(input, "invalid_type");
12353
+ const leaves = [];
12354
+ const visit = async (dir, parents, prefix) => {
12355
+ const current = [...parents, dir];
12356
+ await checkChain(current);
12357
+ offending = dir.display;
12358
+ let names;
12359
+ try {
12360
+ names = await (dependencies.readdir ?? fs.readdir)(dir.path);
12361
+ } catch (error) {
12362
+ const code = error.code;
12363
+ if (code === "ENOENT" || code === "ENOTDIR") fail(dir.display, "changed", error);
12364
+ if (code === "ELOOP") fail(dir.display, "link", error);
12365
+ throw error;
12366
+ }
12367
+ await checkChain(current);
12368
+ for (const name of names) {
12369
+ if (name.startsWith(".") || name === "__MACOSX" || EXCLUDED_DIR_NAMES.has(name) || IGNORED_FILENAMES.has(name)) continue;
12370
+ const display = prefix ? `${prefix}/${name}` : name;
12371
+ offending = display;
12372
+ await checkpoint("entry", paths.join(dir.path, name));
12373
+ await checkChain(current);
12374
+ const entry = {
12375
+ path: paths.join(dir.path, name),
12376
+ display,
12377
+ stat: await get(paths.join(dir.path, name), display, true)
12378
+ };
12379
+ checkType(entry.stat, display);
12380
+ await checkPhysicalEntry(entry.path, display, dir.stat, name);
12381
+ await checkChain(current);
12382
+ if (entry.stat.isDirectory()) await visit(entry, current, display);
12383
+ else leaves.push({
12384
+ ...entry,
12385
+ name: display,
12386
+ chain: current
12387
+ });
12388
+ }
12389
+ await checkChain(current);
12390
+ };
12391
+ const root = {
12392
+ path: selectedPath,
12393
+ display: input,
12394
+ stat: selected
12395
+ };
12396
+ if (selected.isDirectory()) await visit(root, chain, "");
12397
+ else leaves.push({
12398
+ ...root,
12399
+ name: paths.basename(await physicalPath(selectedPath, input)),
12400
+ chain
12401
+ });
12402
+ leaves.sort((a, b) => a.name.localeCompare(b.name));
12403
+ const files = [];
12404
+ for (const leaf of leaves) {
12405
+ offending = leaf.display;
12406
+ await checkpoint("before_open", leaf.path);
12407
+ await checkChain(leaf.chain);
12408
+ await recheck(leaf, false);
12409
+ let handle;
12410
+ try {
12411
+ handle = await (dependencies.open ?? fs.open)(leaf.path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
12412
+ } catch (error) {
12413
+ const code = error.code;
12414
+ if (code === "ELOOP") fail(leaf.display, "link", error);
12415
+ if (code === "ENOENT" || code === "ENOTDIR") fail(leaf.display, "changed", error);
12416
+ if (constants.O_NOFOLLOW && (code === "EINVAL" || code === "ENOTSUP" || code === "EOPNOTSUPP")) fail(leaf.display, "unsupported_guarantee", error, "O_NOFOLLOW open");
12417
+ throw error;
12418
+ }
12419
+ let failed = false;
12420
+ try {
12421
+ const checkHandle = async () => {
12422
+ const s = await handle.stat({ bigint: true });
12423
+ identity(s, leaf.display);
12424
+ if (!sameFile(s, leaf.stat)) fail(leaf.display, "changed");
12425
+ };
12426
+ await checkpoint("after_open", leaf.path);
12427
+ await checkHandle();
12428
+ await checkChain(leaf.chain);
12429
+ await recheck(leaf, false);
12430
+ const bytes = await handle.readFile();
12431
+ await checkpoint("after_read", leaf.path);
12432
+ await checkHandle();
12433
+ await recheck(leaf, false);
12434
+ await checkChain(leaf.chain);
12435
+ if (BigInt(bytes.byteLength) !== leaf.stat.size) fail(leaf.display, "changed");
12436
+ files.push({
12437
+ name: leaf.name,
12438
+ blob: new Blob([bytes])
12439
+ });
12440
+ } catch (error) {
12441
+ failed = true;
12442
+ throw error;
12443
+ } finally {
12444
+ if (failed) await handle.close().catch(() => {});
12445
+ else await handle.close();
12446
+ }
12447
+ }
12448
+ return {
12449
+ directory: selected.isDirectory(),
12450
+ files
12451
+ };
12452
+ } catch (error) {
12453
+ if (error instanceof UploadBoundaryError || error instanceof UploadReadFailure) throw error;
12454
+ throw new UploadReadFailure(uploadReadError(error, offending), error);
12455
+ }
12456
+ }
12457
+ //#endregion
11742
12458
  //#region src/files.ts
12459
+ var DownloadManifestError = class extends Error {
12460
+ error;
12461
+ constructor(message) {
12462
+ super(message);
12463
+ this.error = validationError(message, "Retry later. If this repeats, report the artifact ID.");
12464
+ }
12465
+ };
11743
12466
  let undiciModule;
11744
12467
  async function createUploadForm() {
11745
12468
  const { FormData } = undiciModule ??= await import("undici");
11746
12469
  return new FormData();
11747
12470
  }
11748
- async function prepareUploadPayload(targetPath, fileStat, initialForm) {
11749
- const form = initialForm ?? await createUploadForm();
11750
- if (fileStat.isDirectory()) {
11751
- let files;
11752
- try {
11753
- files = await collectDirectoryFiles(resolve(targetPath));
11754
- } catch (error) {
11755
- if (error instanceof CollectDirectoryFilesError) return { error: validationError(error.message, error.hint) };
11756
- throw error;
11757
- }
11758
- if (files.length === 0) return { error: validationError("Directory has no shareable files.", "Add index.html or index.md and retry.") };
11759
- for (const file of files) form.append("file", await blobFor(file.path), file.relativePath);
11760
- return { payload: {
11761
- form,
11762
- kind: "static_site"
11763
- } };
11764
- }
11765
- if (fileStat.isFile()) {
11766
- form.append("file", await blobFor(targetPath), basename(targetPath));
12471
+ async function prepareUploadPayload(targetPath, dependencies) {
12472
+ try {
12473
+ const selection = await prepareUploadSelection(targetPath, false, dependencies);
12474
+ if (selection.directory && selection.files.length === 0) return { error: validationError("Directory has no shareable files.", "Add index.html or index.md and retry.") };
12475
+ const form = await createUploadForm();
12476
+ for (const file of selection.files) form.append("file", file.blob.slice(0, file.blob.size, contentTypeFor(file.name)), file.name);
11767
12477
  return { payload: {
11768
12478
  form,
11769
- kind: artifactKindForFile(targetPath)
12479
+ kind: selection.directory ? "static_site" : artifactKindForFile(selection.files[0].name)
11770
12480
  } };
12481
+ } catch (error) {
12482
+ return { error: uploadReadError(error, targetPath) };
11771
12483
  }
11772
- return { error: validationError("Path must be a file or directory.", "Pass a regular file or directory.") };
11773
12484
  }
11774
- async function prepareDownloadPlan(manifest, outputPath, force) {
12485
+ async function prepareDownloadPlan(manifest, outputPath, force, boundary = new WriteBoundary(), treePreflighted = false) {
11775
12486
  if (manifest.files.length === 0) return { error: validationError("Download manifest contains no files.", "Check the artifact and retry.") };
11776
12487
  if (outputPath === "") return { error: validationError("--output requires a non-empty directory.", "Pass --output <path> or omit --output to use the artifact ID.") };
11777
12488
  const root = resolve(outputPath);
11778
- const existing = await lstat(root).catch(() => null);
11779
- if (existing?.isSymbolicLink()) return { error: validationError("Output path must not be a symbolic link.", "Choose a regular directory path and retry.") };
11780
- if (existing && !force) return { error: cliError({
12489
+ if (boundary.workspace) await boundary.record(dirname(root), true);
12490
+ else await boundary.outputParent(dirname(root));
12491
+ if (await boundary.record(root, true) && !force) return { error: cliError({
11781
12492
  code: "output_exists",
11782
12493
  message: "Output path already exists.",
11783
12494
  why: "Download will not write into an existing path unless --force is set.",
@@ -11786,22 +12497,29 @@ async function prepareDownloadPlan(manifest, outputPath, force) {
11786
12497
  requiresHuman: false,
11787
12498
  recovery: { kind: "change_input" }
11788
12499
  }) };
11789
- if (existing && !existing.isDirectory()) return { error: validationError("Output path is not a directory.", "Choose a directory path or remove the existing file.") };
12500
+ if (treePreflighted) await boundary.checkTree(root);
12501
+ else await boundary.tree(root);
11790
12502
  const seen = /* @__PURE__ */ new Set();
12503
+ const directories = /* @__PURE__ */ new Set();
12504
+ const foldCase = process.platform === "win32" || process.platform === "darwin";
11791
12505
  const relativeFiles = [];
11792
12506
  for (const file of manifest.files) {
11793
12507
  const relativePath = downloadRelativePath(file.path);
11794
- if (relativePath.error) return { error: relativePath.error };
11795
- if (seen.has(relativePath.value)) return { error: validationError("Download manifest contains duplicate file paths.", "Retry later. If this repeats, report the artifact ID.") };
11796
- seen.add(relativePath.value);
12508
+ const key = foldCase ? relativePath.toLowerCase() : relativePath;
12509
+ const prefixes = [];
12510
+ for (let slash = key.indexOf("/"); slash !== -1; slash = key.indexOf("/", slash + 1)) prefixes.push(key.slice(0, slash));
12511
+ if (seen.has(key) || directories.has(key) || prefixes.some((prefix) => seen.has(prefix))) throw new DownloadManifestError(`Download manifest contains conflicting file path ${JSON.stringify(file.path)}.`);
12512
+ seen.add(key);
12513
+ for (const prefix of prefixes) directories.add(prefix);
11797
12514
  relativeFiles.push({
11798
12515
  ...file,
11799
- relativePath: relativePath.value
12516
+ relativePath
11800
12517
  });
11801
12518
  }
11802
12519
  const parent = dirname(root);
11803
- await mkdir(parent, { recursive: true });
11804
- const tempRoot = await mkdtemp(join(parent, `.${basename(root)}.tmp-`));
12520
+ await boundary.directory(parent);
12521
+ boundary.workspace ??= await boundary.privateDirectory(parent);
12522
+ const tempRoot = await boundary.privateDirectory(boundary.workspace);
11805
12523
  const files = [];
11806
12524
  for (const file of relativeFiles) {
11807
12525
  const targetPath = resolve(tempRoot, file.relativePath);
@@ -11813,15 +12531,15 @@ async function prepareDownloadPlan(manifest, outputPath, force) {
11813
12531
  return { value: {
11814
12532
  root,
11815
12533
  tempRoot,
11816
- replaceExisting: Boolean(existing),
11817
- files
12534
+ files,
12535
+ boundary
11818
12536
  } };
11819
12537
  }
11820
12538
  function downloadRelativePath(path) {
11821
- if (!path.startsWith("/") || path.includes("\0") || path.includes("\\")) return { error: validationError("Download manifest contains an invalid file path.", "Retry later. If this repeats, report the artifact ID.") };
12539
+ if (!path.startsWith("/") || path.includes("\0") || path.includes("\\")) throw new DownloadManifestError(`Download manifest contains invalid file path ${JSON.stringify(path)}.`);
11822
12540
  const segments = path.split("/").slice(1);
11823
- if (segments.length === 0 || segments.some((segment) => segment === "" || segment === "." || segment === "..")) return { error: validationError("Download manifest contains an unsafe file path.", "Retry later. If this repeats, report the artifact ID.") };
11824
- return { value: segments.join("/") };
12541
+ if (segments.length === 0 || segments.some((segment) => segment === "" || segment === "." || segment === ".." || process.platform === "win32" && (/[:*?"<>|]/u.test(segment) || /[. ]$/u.test(segment) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(segment)))) throw new DownloadManifestError(`Download manifest contains unsafe file path ${JSON.stringify(path)}.`);
12542
+ return segments.join("/");
11825
12543
  }
11826
12544
  function verifyDownloadedBytes(file, bytes) {
11827
12545
  if (bytes.byteLength !== file.size_bytes) return { error: downloadIntegrityError(file.path, "size mismatch") };
@@ -11841,60 +12559,18 @@ function downloadIntegrityError(path, reason) {
11841
12559
  recovery: { kind: "retry_later" }
11842
12560
  });
11843
12561
  }
11844
- function backupPathFor(root) {
11845
- return join(dirname(root), `.${basename(root)}.old-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`);
11846
- }
11847
- async function pathExists(path) {
11848
- return Boolean(await lstat(path).catch(() => null));
11849
- }
11850
12562
  function downloadFileSystemError(error) {
12563
+ if (error instanceof WriteBoundaryError || error instanceof DownloadManifestError) return error.error;
11851
12564
  return cliError({
11852
12565
  code: "download_failed",
11853
- message: "Could not write downloaded files.",
11854
- why: error instanceof Error ? error.message : "The local filesystem rejected a download operation.",
12566
+ message: error instanceof WriteFileSystemError ? error.message : "Could not write downloaded files.",
12567
+ why: "The local filesystem rejected a download operation. Check retained recovery paths before retrying.",
11855
12568
  hint: "Check --output permissions and available disk space, then retry.",
11856
12569
  agentRecoverable: true,
11857
12570
  requiresHuman: false,
11858
12571
  recovery: { kind: "change_input" }
11859
12572
  });
11860
12573
  }
11861
- async function collectDirectoryFiles(root) {
11862
- const results = [];
11863
- async function visit(dir) {
11864
- for (const entry of await readdir(dir, { withFileTypes: true })) {
11865
- if (entry.name === "__MACOSX") continue;
11866
- const fullPath = join(dir, entry.name);
11867
- if (entry.isSymbolicLink()) throw new CollectDirectoryFilesError("Directory contains a symbolic link.", "Remove or replace symlinked files and directories before sharing.");
11868
- if (entry.isDirectory()) {
11869
- if (EXCLUDED_DIR_NAMES.has(entry.name) || entry.name.startsWith(".")) continue;
11870
- await visit(fullPath);
11871
- continue;
11872
- }
11873
- if (!entry.isFile() || IGNORED_FILENAMES.has(entry.name) || entry.name.startsWith(".")) continue;
11874
- const relativePath = relative(root, fullPath).split(sep).join("/");
11875
- results.push({
11876
- path: fullPath,
11877
- relativePath
11878
- });
11879
- }
11880
- }
11881
- await visit(root);
11882
- results.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
11883
- return results;
11884
- }
11885
- var CollectDirectoryFilesError = class extends Error {
11886
- hint;
11887
- constructor(message, hint) {
11888
- super(message);
11889
- this.name = "CollectDirectoryFilesError";
11890
- this.hint = hint;
11891
- }
11892
- };
11893
- async function blobFor(path) {
11894
- const chunks = [];
11895
- for await (const chunk of createReadStream(path)) chunks.push(chunk);
11896
- return new Blob(chunks, { type: contentTypeFor(path) });
11897
- }
11898
12574
  function contentTypeFor(path) {
11899
12575
  if (path.endsWith(".html")) return "text/html";
11900
12576
  if (path.endsWith(".md")) return "text/markdown";
@@ -11911,6 +12587,14 @@ function artifactKindForFile(path) {
11911
12587
  }
11912
12588
  //#endregion
11913
12589
  //#region src/command-runners/download.ts
12590
+ var DownloadFileError = class extends Error {};
12591
+ var DownloadFailure = class extends Error {
12592
+ error;
12593
+ constructor(error) {
12594
+ super(error.message);
12595
+ this.error = error;
12596
+ }
12597
+ };
11914
12598
  function fileDownloadError(error, path, notFound = false) {
11915
12599
  const message = `Could not download file "${path}".`;
11916
12600
  return {
@@ -11920,42 +12604,78 @@ function fileDownloadError(error, path, notFound = false) {
11920
12604
  hint: notFound ? `Retry the download. If it fails again, check file "${path}" in the artifact.` : `File "${path}": ${error.hint}`
11921
12605
  };
11922
12606
  }
11923
- async function readPreviousVersions(output) {
12607
+ function validateIds(entries) {
12608
+ const seen = /* @__PURE__ */ new Set();
12609
+ for (const entry of entries) {
12610
+ const id = isRecord$1(entry) ? entry.id : void 0;
12611
+ if (!isArtifactId(id) || seen.has(id.toLowerCase())) throw new WriteBoundaryError(`artifact ID ${typeof id === "string" ? JSON.stringify(id) : "(missing or non-string)"}`, "Use unique artifact IDs matching ^[a-z0-9]{10}$. Correct the endpoint or saved index and retry.");
12612
+ seen.add(id.toLowerCase());
12613
+ }
12614
+ }
12615
+ async function readPreviousVersions(output, boundary) {
12616
+ const text = await boundary.read(join(output, "index.json"));
12617
+ if (text === null) return /* @__PURE__ */ new Map();
12618
+ let parsed;
11924
12619
  try {
11925
- const parsed = JSON.parse(await readFile(join(output, "index.json"), "utf8"));
11926
- if (!Array.isArray(parsed.artifacts)) return /* @__PURE__ */ new Map();
11927
- const previous = /* @__PURE__ */ new Map();
11928
- for (const entry of parsed.artifacts) {
11929
- if (entry === null || typeof entry !== "object") return /* @__PURE__ */ new Map();
11930
- const { id, version_id } = entry;
11931
- if (typeof id !== "string") return /* @__PURE__ */ new Map();
11932
- if (typeof version_id === "string") previous.set(id, version_id);
11933
- }
11934
- return previous;
12620
+ parsed = JSON.parse(text);
11935
12621
  } catch {
11936
12622
  return /* @__PURE__ */ new Map();
11937
12623
  }
12624
+ if (!isRecord$1(parsed) || !Array.isArray(parsed.artifacts)) return /* @__PURE__ */ new Map();
12625
+ validateIds(parsed.artifacts);
12626
+ const previous = /* @__PURE__ */ new Map();
12627
+ for (const entry of parsed.artifacts) {
12628
+ if (entry.version_id !== void 0 && typeof entry.version_id !== "string") return /* @__PURE__ */ new Map();
12629
+ if (typeof entry.version_id === "string") previous.set(entry.id, entry.version_id);
12630
+ }
12631
+ return previous;
12632
+ }
12633
+ async function runDownload(parsed, mode, isRetry = false, dependencies = {}) {
12634
+ const boundary = new WriteBoundary(dependencies);
12635
+ let primary;
12636
+ let cleanup;
12637
+ try {
12638
+ await runDownloadInternal(parsed, mode, isRetry, boundary);
12639
+ } catch (error) {
12640
+ primary = error;
12641
+ }
12642
+ try {
12643
+ await boundary.cleanup();
12644
+ } catch (error) {
12645
+ cleanup = error;
12646
+ }
12647
+ const error = primary ?? cleanup;
12648
+ if (error) {
12649
+ const failure = error instanceof DownloadFailure ? error.error : downloadFileSystemError(error);
12650
+ if (primary && cleanup) failure.hint += " Cleanup could not finish safely.";
12651
+ const retained = await boundary.retainedWorkspace();
12652
+ if (retained) failure.hint += ` Recover retained data at ${retained}; inspect it before manual cleanup.`;
12653
+ writeFailure("download", failure, mode, 1);
12654
+ }
11938
12655
  }
11939
- async function runDownload(parsed, mode, isRetry = false) {
12656
+ async function runDownloadInternal(parsed, mode, isRetry = false, boundary) {
11940
12657
  const command = "download";
11941
12658
  const projectId = parsed.options.projectId?.trim();
11942
12659
  if (projectId !== void 0 || parsed.positionals.length === 0) {
11943
- if (!projectId || parsed.positionals.length > 0 || !parsed.options.output?.trim()) return writeFailure(command, validationError("Invalid project download arguments.", "Use download <target> or download --project-id <id> --output <dir>."), mode, 1);
11944
- return runProjectDownload(parsed, mode, projectId, isRetry);
12660
+ if (!projectId || parsed.positionals.length > 0 || !parsed.options.output?.trim()) throw new DownloadFailure(validationError("Invalid project download arguments.", "Use download <target> or download --project-id <id> --output <dir>."));
12661
+ return runProjectDownload(parsed, mode, projectId, isRetry, boundary);
11945
12662
  }
11946
12663
  const target = parseArtifactTarget(parsed.positionals[0], "download", "Pass an artifact ID or share URL to download.");
11947
- if (target.error) return writeFailure(command, target.error, mode, 1);
12664
+ if (target.error) throw new DownloadFailure(target.error);
11948
12665
  const artifactId = target.artifactId;
12666
+ const input = parsed.positionals[0];
12667
+ if (!/^https?:\/\//i.test(input)) validateIds([{ id: input }]);
12668
+ validateIds([{ id: artifactId }]);
11949
12669
  const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
11950
12670
  if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
11951
12671
  const request = await requestConfig(parsed.options);
11952
- if (request.error) return writeFailure(command, request.error, mode, 1);
12672
+ if (request.error) throw new DownloadFailure(request.error);
11953
12673
  const baseUrl = baseUrlOf(parsed.options);
11954
12674
  const manifestResponse = await cliFetch(apiUrl(`/api/cli/artifacts/${encodeURIComponent(artifactId)}/download`, baseUrl), {
11955
12675
  headers: { Authorization: `Bearer ${credential.token}` },
11956
12676
  ...request.init
11957
12677
  });
11958
- if ("networkError" in manifestResponse) return writeFailure(command, networkError(manifestResponse.networkError), mode, 1);
12678
+ if ("networkError" in manifestResponse) throw new DownloadFailure(networkError(manifestResponse.networkError));
11959
12679
  const body = await readJson(manifestResponse);
11960
12680
  if (!manifestResponse.ok) return handleAuthenticatedCredentialFailure(command, mapApiError(manifestResponse.status, body, {
11961
12681
  authenticated: true,
@@ -11966,64 +12686,50 @@ async function runDownload(parsed, mode, isRetry = false) {
11966
12686
  profileCredentialKind: credential.profileCredentialKind,
11967
12687
  botProfile: credential.botProfile
11968
12688
  }), credential, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
11969
- if (!downloadManifestFields(body)) return writeFailure(command, serviceError("Download manifest succeeded but the response did not include file metadata."), mode, 1);
11970
- const plan = await prepareDownloadPlan(body, parsed.options.output ?? artifactId, Boolean(parsed.options.force));
11971
- if (plan.error) return writeFailure(command, plan.error, mode, 1);
11972
- let completed = false;
11973
- let backupRoot = null;
11974
- try {
11975
- for (const file of plan.value.files) {
11976
- const fileResponse = await cliFetch(downloadFileUrl(baseUrl, artifactId, file.path), {
11977
- headers: { Authorization: `Bearer ${credential.token}` },
11978
- ...request.init
11979
- });
11980
- if ("networkError" in fileResponse) return writeFailure(command, fileDownloadError(networkError(fileResponse.networkError), file.path), mode, 1);
11981
- if (!fileResponse.ok) {
11982
- const fileBody = await readJson(fileResponse);
11983
- const apiError = isRecord$1(fileBody) ? fileBody.error : void 0;
11984
- const notFound = fileResponse.status === 404 || apiError === "not-found" || isRecord$1(apiError) && apiError.code === "not-found";
11985
- return handleAuthenticatedCredentialFailure(command, fileDownloadError(mapApiError(fileResponse.status, fileBody, {
11986
- authenticated: true,
11987
- ...!notFound ? { artifactTarget: true } : {},
11988
- baseUrl,
11989
- credentialSource: credential.source,
11990
- profile: credential.profile,
11991
- profileCredentialKind: credential.profileCredentialKind,
11992
- botProfile: credential.botProfile
11993
- }), file.path, notFound), credential, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
11994
- }
11995
- let fileBody;
11996
- try {
11997
- fileBody = await fileResponse.arrayBuffer();
11998
- } catch (error) {
11999
- return writeFailure(command, fileDownloadError(networkError(error), file.path), mode, 1);
12000
- }
12001
- const bytes = Buffer.from(fileBody);
12002
- const verified = verifyDownloadedBytes(file, bytes);
12003
- if (verified.error) return writeFailure(command, verified.error, mode, 1);
12004
- await mkdir(dirname(file.targetPath), { recursive: true });
12005
- await writeFile(file.targetPath, bytes);
12006
- }
12007
- if (plan.value.replaceExisting) {
12008
- backupRoot = backupPathFor(plan.value.root);
12009
- await rename(plan.value.root, backupRoot);
12010
- }
12011
- await rename(plan.value.tempRoot, plan.value.root);
12012
- completed = true;
12013
- if (backupRoot) await rm(backupRoot, {
12014
- recursive: true,
12015
- force: true
12016
- }).catch(() => {});
12017
- } catch (error) {
12018
- if (backupRoot && !await pathExists(plan.value.root) && await pathExists(backupRoot)) await rename(backupRoot, plan.value.root).catch(() => {});
12019
- return writeFailure(command, downloadFileSystemError(error), mode, 1);
12020
- } finally {
12021
- if (!completed) await rm(plan.value.tempRoot, {
12022
- recursive: true,
12023
- force: true
12024
- }).catch(() => {});
12689
+ if (!isRecord$1(body) || !("id" in body)) throw new DownloadFailure(serviceError("Download manifest succeeded but the response did not include file metadata."));
12690
+ validateIds([body]);
12691
+ if (isRecord$1(body) && body.id !== artifactId) throw new DownloadManifestError(`Manifest artifact ID ${JSON.stringify(body.id)} does not match ${artifactId}.`);
12692
+ if (!downloadManifestFields(body)) throw new DownloadFailure(serviceError("Download manifest succeeded but the response did not include file metadata."));
12693
+ boundary.watch(resolve(parsed.options.output ?? artifactId));
12694
+ const plan = await prepareDownloadPlan(body, parsed.options.output ?? artifactId, Boolean(parsed.options.force), boundary);
12695
+ if (plan.error) throw new DownloadFailure(plan.error);
12696
+ for (const file of plan.value.files) {
12697
+ const fileResponse = await cliFetch(downloadFileUrl(baseUrl, artifactId, file.path), {
12698
+ headers: { Authorization: `Bearer ${credential.token}` },
12699
+ ...request.init
12700
+ });
12701
+ if ("networkError" in fileResponse) throw new DownloadFailure(fileDownloadError(networkError(fileResponse.networkError), file.path));
12702
+ if (!fileResponse.ok) {
12703
+ const fileBody = await readJson(fileResponse);
12704
+ const apiError = isRecord$1(fileBody) ? fileBody.error : void 0;
12705
+ const notFound = fileResponse.status === 404 || apiError === "not-found" || isRecord$1(apiError) && apiError.code === "not-found";
12706
+ await boundary.cleanup();
12707
+ return handleAuthenticatedCredentialFailure(command, fileDownloadError(mapApiError(fileResponse.status, fileBody, {
12708
+ authenticated: true,
12709
+ ...!notFound ? { artifactTarget: true } : {},
12710
+ baseUrl,
12711
+ credentialSource: credential.source,
12712
+ profile: credential.profile,
12713
+ profileCredentialKind: credential.profileCredentialKind,
12714
+ botProfile: credential.botProfile
12715
+ }), file.path, notFound), credential, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
12716
+ }
12717
+ let fileBody;
12718
+ try {
12719
+ fileBody = await fileResponse.arrayBuffer();
12720
+ } catch (error) {
12721
+ throw new DownloadFailure(fileDownloadError(networkError(error), file.path));
12722
+ }
12723
+ const bytes = Buffer.from(fileBody);
12724
+ const verified = verifyDownloadedBytes(file, bytes);
12725
+ if (verified.error) throw new DownloadFailure(verified.error);
12726
+ await boundary.write(file.targetPath, bytes);
12025
12727
  }
12728
+ await boundary.replace(plan.value.tempRoot, plan.value.root);
12729
+ boundary.keep(plan.value.root);
12730
+ await boundary.finish();
12026
12731
  return writeSuccess(command, {
12732
+ backup_paths: boundary.backupPaths,
12027
12733
  artifact: {
12028
12734
  id: body.id,
12029
12735
  url: body.share_url,
@@ -12037,12 +12743,12 @@ async function runDownload(parsed, mode, isRetry = false) {
12037
12743
  }
12038
12744
  }, mode);
12039
12745
  }
12040
- async function runProjectDownload(parsed, mode, projectId, isRetry = false) {
12746
+ async function runProjectDownload(parsed, mode, projectId, isRetry = false, boundary) {
12041
12747
  const command = "download";
12042
12748
  const resolved = await resolveCredential(parsed.options, await resolveProjectConfig());
12043
12749
  if (!resolved.ok) return handleCredentialFailure(command, resolved, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
12044
12750
  const request = await requestConfig(parsed.options);
12045
- if (request.error) return writeFailure(command, request.error, mode, 1);
12751
+ if (request.error) throw new DownloadFailure(request.error);
12046
12752
  const baseUrl = baseUrlOf(parsed.options);
12047
12753
  let credential = resolved;
12048
12754
  let refreshAttempted = false;
@@ -12075,7 +12781,7 @@ async function runProjectDownload(parsed, mode, projectId, isRetry = false) {
12075
12781
  ...request.init
12076
12782
  });
12077
12783
  };
12078
- const output = parsed.options.output.trim();
12784
+ const output = resolve(parsed.options.output.trim());
12079
12785
  const list = async (cursor) => {
12080
12786
  const url = apiUrl("/api/cli/artifacts", baseUrl);
12081
12787
  url.searchParams.set("project_id", projectId);
@@ -12124,12 +12830,22 @@ async function runProjectDownload(parsed, mode, projectId, isRetry = false) {
12124
12830
  first = false;
12125
12831
  cursor = page.data.has_more && page.data.next_cursor ? page.data.next_cursor : void 0;
12126
12832
  } while (cursor);
12127
- if (listError && first) return writeFailure(command, listError, mode, 1);
12128
- if ((await lstat(output).catch(() => null))?.isSymbolicLink()) return writeFailure(command, validationError("Output path must not be a symbolic link.", "Choose a regular directory path and retry."), mode, 1);
12129
- const previousVersions = await readPreviousVersions(output);
12130
- await mkdir(output, { recursive: true });
12833
+ if (listError && first) throw new DownloadFailure(listError);
12834
+ validateIds(entries);
12835
+ boundary.watch(output);
12836
+ await boundary.outputParent(dirname(output));
12837
+ await boundary.record(output, true);
12838
+ const previousVersions = await readPreviousVersions(output, boundary);
12839
+ for (const item of entries) {
12840
+ const root = join(output, item.id);
12841
+ await boundary.record(root, true);
12842
+ await boundary.tree(root);
12843
+ }
12844
+ await boundary.directory(output);
12845
+ boundary.keep(output);
12846
+ boundary.workspace = await boundary.privateDirectory(output);
12131
12847
  const results = entries.map((item) => ({
12132
- id: String(item.id),
12848
+ id: item.id,
12133
12849
  title: String(item.title ?? ""),
12134
12850
  ...typeof item.owner_email === "string" ? { owner_email: item.owner_email } : {},
12135
12851
  updated_at: String(item.updated_at ?? ""),
@@ -12146,107 +12862,87 @@ async function runProjectDownload(parsed, mode, projectId, isRetry = false) {
12146
12862
  continue;
12147
12863
  }
12148
12864
  const root = join(output, result.id);
12149
- const rootStat = await lstat(root).catch(() => null);
12150
- const rootExists = rootStat !== null;
12151
- const response = await authFetch(apiUrl(`/api/cli/artifacts/${encodeURIComponent(result.id)}/download`, baseUrl));
12152
- if ("networkError" in response) {
12153
- result.reason = "network failed";
12154
- continue;
12155
- }
12156
- if (!response.ok) {
12157
- const body = await readJson(response);
12158
- if (mapApiError(response.status, body, {
12159
- authenticated: true,
12160
- baseUrl,
12161
- artifactTarget: true
12162
- }).code === "unsupported_kind") {
12163
- result.status = "skipped";
12164
- result.reason = "unsupported-kind";
12165
- } else result.reason = `download failed (${response.status})`;
12166
- continue;
12167
- }
12168
- const body = await readJson(response);
12169
- if (!downloadManifestFields(body)) {
12170
- result.reason = "invalid download manifest";
12171
- continue;
12172
- }
12173
- if (!parsed.options.force && rootStat?.isDirectory() && previousVersions.get(result.id) === body.version_id) {
12174
- result.status = "unchanged";
12175
- result.version_id = body.version_id;
12176
- result.path = root;
12177
- delete result.reason;
12178
- continue;
12179
- }
12180
- if (rootExists && !parsed.options.force) {
12181
- result.reason = "artifact output already exists";
12182
- continue;
12183
- }
12184
- const plan = await prepareDownloadPlan(body, root, Boolean(parsed.options.force));
12185
- if (plan.error) {
12186
- result.reason = plan.error.message;
12187
- continue;
12188
- }
12189
12865
  try {
12866
+ const rootExists = await boundary.record(root, true);
12867
+ const response = await authFetch(apiUrl(`/api/cli/artifacts/${encodeURIComponent(result.id)}/download`, baseUrl));
12868
+ if ("networkError" in response) {
12869
+ result.reason = "network failed";
12870
+ continue;
12871
+ }
12872
+ if (!response.ok) {
12873
+ const body = await readJson(response);
12874
+ if (mapApiError(response.status, body, {
12875
+ authenticated: true,
12876
+ baseUrl,
12877
+ artifactTarget: true
12878
+ }).code === "unsupported_kind") {
12879
+ result.status = "skipped";
12880
+ result.reason = "unsupported-kind";
12881
+ } else result.reason = `download failed (${response.status})`;
12882
+ continue;
12883
+ }
12884
+ const body = await readJson(response);
12885
+ if (!isRecord$1(body) || body.id !== result.id) throw new DownloadManifestError(`Download manifest artifact ID does not match ${result.id}.`);
12886
+ if (!downloadManifestFields(body)) throw new DownloadManifestError(`Invalid download manifest for artifact ${result.id}.`);
12887
+ if (!parsed.options.force && rootExists && previousVersions.get(result.id) === body.version_id) {
12888
+ result.status = "unchanged";
12889
+ result.version_id = body.version_id;
12890
+ result.path = root;
12891
+ delete result.reason;
12892
+ continue;
12893
+ }
12894
+ if (rootExists && !parsed.options.force) {
12895
+ result.reason = "artifact output already exists";
12896
+ continue;
12897
+ }
12898
+ const plan = await prepareDownloadPlan(body, root, Boolean(parsed.options.force), boundary, true);
12899
+ if (plan.error) {
12900
+ result.reason = plan.error.message;
12901
+ continue;
12902
+ }
12190
12903
  for (const file of plan.value.files) {
12191
12904
  const fileResponse = await authFetch(downloadFileUrl(baseUrl, result.id, file.path));
12192
- if ("networkError" in fileResponse) throw new Error(`Could not download file "${file.path}": network failed`);
12193
- if (!fileResponse.ok) throw new Error(`Could not download file "${file.path}" (${fileResponse.status})`);
12905
+ if ("networkError" in fileResponse) throw new DownloadFileError(`Could not download file "${file.path}": network failed`);
12906
+ if (!fileResponse.ok) throw new DownloadFileError(`Could not download file "${file.path}" (${fileResponse.status})`);
12194
12907
  let fileBody;
12195
12908
  try {
12196
12909
  fileBody = await fileResponse.arrayBuffer();
12197
12910
  } catch {
12198
- throw new Error(`Could not download file "${file.path}": network failed while reading response body`);
12911
+ throw new DownloadFileError(`Could not download file "${file.path}": network failed while reading response body`);
12199
12912
  }
12200
12913
  const bytes = Buffer.from(fileBody);
12201
12914
  const verified = verifyDownloadedBytes(file, bytes);
12202
- if (verified.error) throw new Error(verified.error.message);
12203
- await mkdir(dirname(file.targetPath), { recursive: true });
12204
- await writeFile(file.targetPath, bytes);
12915
+ if (verified.error) throw new DownloadFileError(verified.error.message);
12916
+ await boundary.write(file.targetPath, bytes);
12205
12917
  }
12206
- let backupRoot = null;
12207
- try {
12208
- if (plan.value.replaceExisting) {
12209
- backupRoot = backupPathFor(plan.value.root);
12210
- await rename(plan.value.root, backupRoot);
12211
- }
12212
- await rename(plan.value.tempRoot, plan.value.root);
12213
- } catch (error) {
12214
- if (backupRoot && !await pathExists(plan.value.root) && await pathExists(backupRoot)) await rename(backupRoot, plan.value.root).catch(() => {});
12215
- throw error;
12216
- }
12217
- if (backupRoot) await rm(backupRoot, {
12218
- recursive: true,
12219
- force: true
12220
- }).catch(() => {});
12918
+ await boundary.replace(plan.value.tempRoot, plan.value.root);
12919
+ boundary.keep(plan.value.root);
12221
12920
  result.status = "ok";
12222
12921
  result.version_id = body.version_id;
12223
12922
  result.path = root;
12224
12923
  delete result.reason;
12225
12924
  } catch (error) {
12226
- result.reason = error instanceof Error ? error.message : "download failed";
12227
- await rm(plan.value.tempRoot, {
12228
- recursive: true,
12229
- force: true
12230
- }).catch(() => {});
12925
+ await boundary.check(output, dirname(output), boundary.workspace);
12926
+ if (error instanceof WriteBoundaryError) throw error;
12927
+ result.reason = error instanceof DownloadManifestError ? `${error.message} ${error.error.hint}` : error instanceof DownloadFileError ? error.message : "download failed; check filesystem availability and retry";
12231
12928
  }
12232
12929
  }
12233
- try {
12234
- await writeFile(join(output, "index.json"), JSON.stringify({
12235
- project_id: projectId,
12236
- artifacts: results
12237
- }, null, 2) + "\n");
12238
- } catch (error) {
12239
- return writeFailure(command, downloadFileSystemError(error), mode, 1);
12240
- }
12930
+ await boundary.atomicWrite(join(output, "index.json"), JSON.stringify({
12931
+ project_id: projectId,
12932
+ artifacts: results
12933
+ }, null, 2) + "\n", true, boundary.workspace);
12934
+ boundary.keep(join(output, "index.json"));
12241
12935
  const counts = {
12242
12936
  ok: results.filter((r) => r.status === "ok").length,
12243
12937
  unchanged: results.filter((r) => r.status === "unchanged").length,
12244
12938
  skipped: results.filter((r) => r.status === "skipped").length,
12245
12939
  failed: results.filter((r) => r.status === "failed").length
12246
12940
  };
12941
+ await boundary.finish();
12247
12942
  process.exitCode = counts.failed > 0 ? 1 : 0;
12248
12943
  return writeSuccess(command, {
12249
12944
  project_id: projectId,
12945
+ backup_paths: boundary.backupPaths,
12250
12946
  ...counts,
12251
12947
  failures: results.filter((r) => r.status === "failed").map((r) => ({
12252
12948
  id: r.id,
@@ -12357,66 +13053,57 @@ function parseEditData(body) {
12357
13053
  }
12358
13054
  //#endregion
12359
13055
  //#region src/git-exclude.ts
12360
- async function ensureGitExclude(cwd) {
12361
- const git = await findGitDir(cwd);
12362
- if (!git) return {
12363
- applied: false,
12364
- warning: null
12365
- };
12366
- const excludePath = join(git.gitDir, "info", "exclude");
12367
- const excludeEntry = gitPattern(relative(git.workTree, resolve(cwd, PROJECT_CONFIG_LOCAL_PATH)));
13056
+ async function ensureGitExclude(cwd, dependencies = {}) {
13057
+ const boundary = new WriteBoundary(dependencies);
13058
+ let repository = resolve(cwd);
13059
+ let excludePath = join(repository, ".git", "info", "exclude");
13060
+ let line = PROJECT_CONFIG_LOCAL_PATH;
12368
13061
  try {
12369
- const existing = await readFile(excludePath, "utf8").catch(() => "");
12370
- if (excludeLines(existing).includes(excludeEntry)) return {
13062
+ while (true) {
13063
+ await boundary.record(repository, true);
13064
+ const git = join(repository, ".git");
13065
+ if (await lstat(git).catch((error) => {
13066
+ if (error.code === "ENOENT") return null;
13067
+ throw error;
13068
+ })) break;
13069
+ const parent = dirname(repository);
13070
+ if (parent === repository) return {
13071
+ applied: false,
13072
+ warning: null
13073
+ };
13074
+ repository = parent;
13075
+ }
13076
+ const git = join(repository, ".git");
13077
+ excludePath = join(git, "info", "exclude");
13078
+ line = relative(repository, resolve(cwd, PROJECT_CONFIG_LOCAL_PATH)).split("\\").join("/");
13079
+ boundary.watch(join(git, "gitdir"), join(git, "commondir"));
13080
+ await boundary.record(git, true);
13081
+ for (const name of ["gitdir", "commondir"]) if (await boundary.record(join(git, name))) throw new Error("Redirect metadata");
13082
+ await boundary.record(dirname(excludePath), true);
13083
+ const existing = await boundary.read(excludePath) ?? "";
13084
+ if (existing.split("\n").some((value) => value.trim() === line)) return {
12371
13085
  applied: false,
12372
13086
  warning: null
12373
13087
  };
12374
- await mkdir(dirname(excludePath), { recursive: true });
12375
- const prefix = existing.endsWith("\n") || existing.length === 0 ? "" : "\n";
12376
- await appendFile(excludePath, `${prefix}${excludeEntry}\n`, "utf8");
13088
+ await boundary.directory(dirname(excludePath));
13089
+ const prefix = existing.length && !existing.endsWith("\n") ? "\n" : "";
13090
+ await boundary.atomicWrite(excludePath, `${existing}${prefix}${line}\n`);
13091
+ boundary.keep(excludePath);
13092
+ await boundary.cleanup();
12377
13093
  return {
12378
13094
  applied: true,
12379
13095
  warning: null
12380
13096
  };
12381
13097
  } catch {
13098
+ try {
13099
+ await boundary.cleanup();
13100
+ } catch {}
12382
13101
  return {
12383
13102
  applied: false,
12384
- warning: `Could not update ${excludePath}; keep ${PROJECT_CONFIG_LOCAL_PATH} out of version control manually.`
12385
- };
12386
- }
12387
- }
12388
- function excludeLines(text) {
12389
- return text.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#"));
12390
- }
12391
- async function findGitDir(start) {
12392
- let current = resolve(start);
12393
- const root = resolve(current, "/");
12394
- while (true) {
12395
- const gitDir = await resolveGitDir(join(current, ".git"));
12396
- if (gitDir) return {
12397
- gitDir,
12398
- workTree: current
13103
+ warning: `Could not update ${excludePath}; add ${line} to the repository's Git excludes manually.`
12399
13104
  };
12400
- if (current === root) return null;
12401
- current = dirname(current);
12402
13105
  }
12403
13106
  }
12404
- async function resolveGitDir(gitPath) {
12405
- const info = await stat(gitPath).catch(() => null);
12406
- if (!info) return null;
12407
- if (info.isDirectory()) return gitPath;
12408
- if (!info.isFile()) return null;
12409
- const text = await readFile(gitPath, "utf8").catch(() => null);
12410
- if (!text) return null;
12411
- const gitDir = text.match(/^gitdir:\s*(.+)$/m)?.[1]?.trim();
12412
- if (!gitDir) return null;
12413
- const resolvedGitDir = resolve(dirname(gitPath), gitDir);
12414
- const commonDir = await readFile(join(resolvedGitDir, "commondir"), "utf8").then((value) => value.trim()).catch(() => null);
12415
- return commonDir ? resolve(resolvedGitDir, commonDir) : resolvedGitDir;
12416
- }
12417
- function gitPattern(path) {
12418
- return path.split("\\").join("/");
12419
- }
12420
13107
  //#endregion
12421
13108
  //#region src/command-runners/init.ts
12422
13109
  function runInit(parsed, mode) {
@@ -12467,28 +13154,50 @@ function onboardingNextSteps(signedIn) {
12467
13154
  async function runInitConfig(parsed, mode, profile, projectId) {
12468
13155
  const command = "init";
12469
13156
  if (parsed.options.dryRun === true) return writeFailure(command, validationError("--dry-run is only supported without --profile or --project-id.", "Run init --dry-run by itself to preview the skill install, or drop --dry-run to save the defaults."), mode, 1);
12470
- const resolved = await resolveProjectConfig();
12471
- if (profile) {
12472
- if (!configHome()) return writeFailure(command, configHomeUnavailableError(profile), mode, 1);
12473
- const globalConfig = await readGlobalConfig();
12474
- if (!Object.hasOwn(globalConfig?.profiles ?? {}, profile)) return writeFailure(command, profileNotFoundError(profile), mode, 1);
12475
- }
12476
- const next = {
12477
- ...await readRawLocalProjectConfig() ?? {},
12478
- ...profile ? { default_profile: profile } : {},
12479
- ...projectId ? { default_project_id: projectId } : {}
12480
- };
13157
+ const boundary = new WriteBoundary();
12481
13158
  const path = projectConfigLocalPath();
12482
- await mkdir(dirname(path), { recursive: true });
12483
- await writeFile(path, `${JSON.stringify(next, null, 2)}\n`);
12484
- const gitExclude = await ensureGitExclude(process.cwd());
12485
- const data = configData(next, resolved);
12486
- delete data.read_path;
12487
- if (gitExclude.warning) data.git_exclude_warning = gitExclude.warning;
12488
- if (gitExclude.applied) data.git_exclude_applied = true;
12489
- return writeSuccess(command, data, mode);
13159
+ try {
13160
+ await boundary.outputParent(process.cwd());
13161
+ await boundary.record(dirname(path), true);
13162
+ const localText = await boundary.read(path);
13163
+ if (profile) {
13164
+ if (!configHome()) return writeFailure(command, configHomeUnavailableError(profile), mode, 1);
13165
+ const globalConfig = await readGlobalConfig();
13166
+ if (!Object.hasOwn(globalConfig?.profiles ?? {}, profile)) return writeFailure(command, profileNotFoundError(profile), mode, 1);
13167
+ }
13168
+ let existing = {};
13169
+ if (localText !== null) try {
13170
+ const raw = JSON.parse(localText);
13171
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) existing = raw;
13172
+ } catch {}
13173
+ const next = {
13174
+ ...existing,
13175
+ ...profile ? { default_profile: profile } : {},
13176
+ ...projectId ? { default_project_id: projectId } : {}
13177
+ };
13178
+ await boundary.directory(dirname(path));
13179
+ await boundary.atomicWrite(path, `${JSON.stringify(next, null, 2)}\n`);
13180
+ boundary.keep(path);
13181
+ const gitExclude = await ensureGitExclude(process.cwd());
13182
+ const data = configData(next);
13183
+ delete data.read_path;
13184
+ if (gitExclude.warning) data.git_exclude_warning = gitExclude.warning;
13185
+ if (gitExclude.applied) data.git_exclude_applied = true;
13186
+ await boundary.cleanup();
13187
+ return writeSuccess(command, data, mode);
13188
+ } catch (error) {
13189
+ let cleanupFailed = false;
13190
+ try {
13191
+ await boundary.cleanup();
13192
+ } catch {
13193
+ cleanupFailed = true;
13194
+ }
13195
+ const failure = error instanceof WriteBoundaryError ? error.error : validationError(`Could not save config at ${path}.`, "Check directory permissions and retry.");
13196
+ if (cleanupFailed) failure.hint += ` Inspect temporary files in ${dirname(path)} before manual cleanup.`;
13197
+ return writeFailure(command, failure, mode, 1);
13198
+ }
12490
13199
  }
12491
- function configData(config, resolved) {
13200
+ function configData(config) {
12492
13201
  return {
12493
13202
  mode: "config",
12494
13203
  path: PROJECT_CONFIG_LOCAL_PATH,
@@ -12496,8 +13205,7 @@ function configData(config, resolved) {
12496
13205
  config: {
12497
13206
  default_profile: configString(config.default_profile),
12498
13207
  default_project_id: configString(config.default_project_id)
12499
- },
12500
- ...resolved.path ? { read_path: resolved.path } : {}
13208
+ }
12501
13209
  };
12502
13210
  }
12503
13211
  //#endregion
@@ -12799,7 +13507,7 @@ async function importBotTokenProfile(command, profile, token, parsed, mode) {
12799
13507
  //#endregion
12800
13508
  //#region src/command-runners/share.ts
12801
13509
  const MAX_SHARE_KEY_LENGTH = 128;
12802
- async function runShare(parsed, mode, isRetry = false) {
13510
+ async function runShare(parsed, mode, isRetry = false, prepared) {
12803
13511
  const command = "share";
12804
13512
  const targetPath = parsed.positionals[0];
12805
13513
  if (!targetPath) return writeFailure(command, validationError("Path is required.", "Pass a file or directory to share."), mode, 1);
@@ -12809,9 +13517,13 @@ async function runShare(parsed, mode, isRetry = false) {
12809
13517
  shareKey = (typeof parsed.options.key === "string" ? parsed.options.key : "").trim();
12810
13518
  if (shareKey.length === 0 || shareKey.length > MAX_SHARE_KEY_LENGTH) return writeFailure(command, validationError(`--key must be 1-${MAX_SHARE_KEY_LENGTH} characters after trimming.`, "Pass a short stable identifier, like a job name or PR number."), mode, 1);
12811
13519
  }
13520
+ const conflict = destinationConflictError(parsed.options);
13521
+ if (conflict) return writeFailure(command, conflict, mode, 1);
13522
+ const upload = prepared ?? await prepareUploadPayload(targetPath);
13523
+ if (upload.error) return writeFailure(command, upload.error, mode, 1);
12812
13524
  const project = await resolveProjectConfig();
12813
13525
  const credential = await resolveCredential(parsed.options, project);
12814
- if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runShare(parsed, mode, true), isRetry);
13526
+ if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runShare(parsed, mode, true, upload), isRetry);
12815
13527
  const baseUrl = baseUrlOf(parsed.options);
12816
13528
  const hasProjectFlag = "project" in parsed.options;
12817
13529
  let destinationOptions = parsed.options;
@@ -12819,14 +13531,10 @@ async function runShare(parsed, mode, isRetry = false) {
12819
13531
  if (hasProjectFlag) {
12820
13532
  projectName = nonEmpty(typeof parsed.options.project === "string" ? parsed.options.project : "");
12821
13533
  if (!projectName) return writeFailure(command, validationError("--project requires a value.", "Pass --project <name> and retry."), mode, 1);
12822
- const conflict = destinationConflictError(parsed.options);
12823
- if (conflict) return writeFailure(command, conflict, mode, 1);
12824
13534
  } else {
12825
13535
  const earlyDestination = resolveDestination(parsed.options, project.config);
12826
13536
  if (earlyDestination.error) return writeFailure(command, earlyDestination.error, mode, 1);
12827
13537
  }
12828
- const fileStat = await stat(targetPath).catch(() => null);
12829
- if (!fileStat) return writeFailure(command, validationError("Path was not found.", `Check the path and retry: ${targetPath}`), mode, 1);
12830
13538
  const request = await requestConfig(parsed.options);
12831
13539
  if (request.error) return writeFailure(command, request.error, mode, 1);
12832
13540
  if (hasProjectFlag && projectName) {
@@ -12838,7 +13546,7 @@ async function runShare(parsed, mode, isRetry = false) {
12838
13546
  profileCredentialKind: credential.profileCredentialKind,
12839
13547
  botProfile: credential.botProfile
12840
13548
  });
12841
- if (resolved.error) return handleAuthenticatedCredentialFailure(command, resolved.error, credential, parsed.options, mode, () => runShare(parsed, mode, true), isRetry);
13549
+ if (resolved.error) return handleAuthenticatedCredentialFailure(command, resolved.error, credential, parsed.options, mode, () => runShare(parsed, mode, true, upload), isRetry);
12842
13550
  const { project: _project, ...rest } = parsed.options;
12843
13551
  destinationOptions = {
12844
13552
  ...rest,
@@ -12848,6 +13556,7 @@ async function runShare(parsed, mode, isRetry = false) {
12848
13556
  const destination = resolveDestination(destinationOptions, project.config);
12849
13557
  if (destination.error) return writeFailure(command, destination.error, mode, 1);
12850
13558
  const initialForm = await createUploadForm();
13559
+ for (const [name, value] of upload.payload.form) initialForm.append(name, value);
12851
13560
  const grantEmails = arrayOption(parsed.options.grantEmail);
12852
13561
  const defaultVisibility = parsed.options.visibility || destination.containerId ? null : await resolveDefaultVisibility("home_audience", await resolveSharedProjectConfig());
12853
13562
  if (defaultVisibility && "error" in defaultVisibility) return writeFailure(command, defaultVisibility.error, mode, 1);
@@ -12861,8 +13570,6 @@ async function runShare(parsed, mode, isRetry = false) {
12861
13570
  const uploadQuery = {};
12862
13571
  if (shareKey !== null) uploadQuery.publish_key = shareKey;
12863
13572
  if (parsed.options.expectedVersion) uploadQuery.expected_version = parsed.options.expectedVersion;
12864
- const upload = await prepareUploadPayload(targetPath, fileStat, initialForm);
12865
- if (upload.error) return writeFailure(command, upload.error, mode, 1);
12866
13573
  if (upload.payload.kind === "static_site") {
12867
13574
  uploadQuery.artifact_kind = "static_site";
12868
13575
  if (destination.containerId) uploadQuery.container_id = destination.containerId;
@@ -12872,7 +13579,7 @@ async function runShare(parsed, mode, isRetry = false) {
12872
13579
  const uploaded = await postShareUpload({
12873
13580
  uploadUrl,
12874
13581
  token: credential.token,
12875
- form: upload.payload.form,
13582
+ form: initialForm,
12876
13583
  requestInit: request.init,
12877
13584
  errorOptions: {
12878
13585
  authenticated: true,
@@ -12889,7 +13596,7 @@ async function runShare(parsed, mode, isRetry = false) {
12889
13596
  }, baseUrl, upload.payload.kind);
12890
13597
  if ("error" in uploaded) {
12891
13598
  if (uploaded.error.code === "network_failed") return writeFailure(command, uploaded.error, mode, 1);
12892
- return handleAuthenticatedCredentialFailure(command, uploaded.error, credential, parsed.options, mode, () => runShare(parsed, mode, true), isRetry);
13599
+ return handleAuthenticatedCredentialFailure(command, uploaded.error, credential, parsed.options, mode, () => runShare(parsed, mode, true, upload), isRetry);
12893
13600
  }
12894
13601
  const { id, url, versionId, artifactKind, visibility, linkExpiresAt, created, warnings } = uploaded.body;
12895
13602
  return writeSuccess(command, {
@@ -12964,7 +13671,7 @@ async function runResolve(parsed, mode) {
12964
13671
  }
12965
13672
  //#endregion
12966
13673
  //#region src/command-runners/update.ts
12967
- async function runUpdate(parsed, mode, isRetry = false) {
13674
+ async function runUpdate(parsed, mode, isRetry = false, prepared) {
12968
13675
  const command = "update";
12969
13676
  const artifactInput = parsed.positionals[0];
12970
13677
  const targetPath = parsed.positionals[1];
@@ -12976,15 +13683,13 @@ async function runUpdate(parsed, mode, isRetry = false) {
12976
13683
  if (!artifactId) return writeFailure(command, targetResolutionError(artifactInput, "update"), mode, 1);
12977
13684
  const label = VersionLabelInputSchema.optional().safeParse(parsed.options.label);
12978
13685
  if (!label.success) return writeFailure(command, validationError("Invalid version label.", label.error.issues[0]?.message ?? "Check the label and retry."), mode, 1);
13686
+ const upload = prepared ?? await prepareUploadPayload(targetPath);
13687
+ if (upload.error) return writeFailure(command, upload.error, mode, 1);
12979
13688
  const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
12980
- if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runUpdate(parsed, mode, true), isRetry);
12981
- const fileStat = await stat(targetPath).catch(() => null);
12982
- if (!fileStat) return writeFailure(command, validationError("Path was not found.", `Check the path and retry: ${targetPath}`), mode, 1);
13689
+ if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runUpdate(parsed, mode, true, upload), isRetry);
12983
13690
  const baseUrl = baseUrlOf(parsed.options);
12984
13691
  const request = await requestConfig(parsed.options);
12985
13692
  if (request.error) return writeFailure(command, request.error, mode, 1);
12986
- const upload = await prepareUploadPayload(targetPath, fileStat);
12987
- if (upload.error) return writeFailure(command, upload.error, mode, 1);
12988
13693
  const updateQuery = label.data !== void 0 ? { label: label.data } : {};
12989
13694
  if (upload.payload.kind === "static_site") updateQuery.artifact_kind = "static_site";
12990
13695
  if (parsed.options.expectedVersion) updateQuery.expected_version = parsed.options.expectedVersion;
@@ -13007,7 +13712,7 @@ async function runUpdate(parsed, mode, isRetry = false) {
13007
13712
  profile: credential.profile,
13008
13713
  profileCredentialKind: credential.profileCredentialKind,
13009
13714
  botProfile: credential.botProfile
13010
- }), credential, parsed.options, mode, () => runUpdate(parsed, mode, true), isRetry);
13715
+ }), credential, parsed.options, mode, () => runUpdate(parsed, mode, true, upload), isRetry);
13011
13716
  const responseBody = isContract(ARTIFACT_VERSION_UPDATE_RESPONSE_SCHEMA, body) ? body : null;
13012
13717
  const id = responseBody?.id ?? artifactId;
13013
13718
  const result = {
@@ -13028,7 +13733,7 @@ async function runUpdate(parsed, mode, isRetry = false) {
13028
13733
  }
13029
13734
  //#endregion
13030
13735
  //#region src/command-runners/append.ts
13031
- async function runAppend(parsed, mode, isRetry = false) {
13736
+ async function runAppend(parsed, mode, isRetry = false, preparedContent) {
13032
13737
  const command = "append";
13033
13738
  const input = parsed.positionals[0];
13034
13739
  const path = parsed.positionals[1];
@@ -13036,17 +13741,30 @@ async function runAppend(parsed, mode, isRetry = false) {
13036
13741
  if (!path) return writeFailure(command, validationError("Path is required.", "Pass a non-empty UTF-8 file."), mode, 1);
13037
13742
  const id = resolveArtifactId(input);
13038
13743
  if (!id) return writeFailure(command, targetResolutionError(input, "append"), mode, 1);
13039
- const s = await stat(path).catch(() => null);
13040
- if (!s || !s.isFile() || s.size === 0) return writeFailure(command, validationError("Path must be a non-empty file.", "Append supports one non-empty UTF-8 file for Markdown or HTML artifacts."), mode, 1);
13041
- const bytes = await readFile(path);
13042
- let content;
13043
- try {
13044
- content = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
13045
- } catch {
13046
- return writeFailure(command, validationError("File is not valid UTF-8.", "Use a non-empty UTF-8 file and retry."), mode, 1);
13744
+ let content = preparedContent;
13745
+ if (content === void 0) {
13746
+ let selection;
13747
+ try {
13748
+ selection = await prepareUploadSelection(path, true);
13749
+ } catch (error) {
13750
+ const failure = uploadReadError(error, path);
13751
+ if (failure.details?.reason === "invalid_type") {
13752
+ failure.message = `Upload path ${path}: Path must be a non-empty file.`;
13753
+ failure.why = failure.message;
13754
+ failure.hint = "Append supports one non-empty UTF-8 file for Markdown or HTML artifacts.";
13755
+ }
13756
+ return writeFailure(command, failure, mode, 1);
13757
+ }
13758
+ const file = selection.files[0];
13759
+ if (file.blob.size === 0) return writeFailure(command, validationError("Path must be a non-empty file.", "Append supports one non-empty UTF-8 file for Markdown or HTML artifacts."), mode, 1);
13760
+ try {
13761
+ content = new TextDecoder("utf-8", { fatal: true }).decode(await file.blob.arrayBuffer());
13762
+ } catch {
13763
+ return writeFailure(command, validationError("File is not valid UTF-8.", "Use a non-empty UTF-8 file and retry."), mode, 1);
13764
+ }
13047
13765
  }
13048
13766
  const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
13049
- if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runAppend(parsed, mode, true), isRetry);
13767
+ if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runAppend(parsed, mode, true, content), isRetry);
13050
13768
  const request = await requestConfig(parsed.options);
13051
13769
  if (request.error) return writeFailure(command, request.error, mode, 1);
13052
13770
  const response = await cliFetch(apiUrl(`/api/cli/artifacts/${encodeURIComponent(id)}/append`, baseUrlOf(parsed.options)), {
@@ -13069,7 +13787,7 @@ async function runAppend(parsed, mode, isRetry = false) {
13069
13787
  profile: credential.profile,
13070
13788
  profileCredentialKind: credential.profileCredentialKind,
13071
13789
  botProfile: credential.botProfile
13072
- }), credential, parsed.options, mode, () => runAppend(parsed, mode, true), isRetry);
13790
+ }), credential, parsed.options, mode, () => runAppend(parsed, mode, true, content), isRetry);
13073
13791
  const responseBody = isContract(ARTIFACT_APPEND_RESPONSE_SCHEMA, body) ? body : null;
13074
13792
  const success = {
13075
13793
  artifact: {
@@ -13838,7 +14556,15 @@ Common failures:
13838
14556
  auth_required Set ARTIFACTSHARE_TOKEN before share
13839
14557
  self_upload_disabled Sign in with Google or Microsoft to upload your own files
13840
14558
  file_too_large Reduce file or directory size and retry
14559
+ upload_read_failed Check filesystem availability and permissions, then retry
13841
14560
  validation_failed Check file type (.html / .md for single files) and directory layout
14561
+ link Copy into the selection or pass the target by absolute path
14562
+ outside_cwd Pass an absolute path
14563
+ parent_traversal Pass a direct absolute path without any .. component
14564
+ changed The selection changed while reading; retry
14565
+ not_found Check the path and retry
14566
+ invalid_type Select a regular file or directory
14567
+ unsupported_guarantee Select a filesystem with stable dev/ino and no-follow support
13842
14568
  key_target_moved The artifact for --key moved; update it by ID or use a new key
13843
14569
  key_kind_mismatch The artifact for --key is a different kind; use a new key`
13844
14570
  });
@@ -13855,7 +14581,7 @@ const updateDefinition = define({
13855
14581
  artifactIdOrUrl: {
13856
14582
  type: "positional",
13857
14583
  toKebab: true,
13858
- description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14584
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL"
13859
14585
  },
13860
14586
  path: {
13861
14587
  type: "positional",
@@ -13872,7 +14598,7 @@ const updateDefinition = define({
13872
14598
  }
13873
14599
  },
13874
14600
  examples: `Target:
13875
- Accepts an artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL.
14601
+ Accepts an artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL.
13876
14602
  Titles and project names are not updated directly; resolve them to an ID first.
13877
14603
 
13878
14604
  Access:
@@ -13893,7 +14619,15 @@ Common failures:
13893
14619
  artifact_kind_mismatch Use a file for single-file artifacts or a directory for static sites
13894
14620
  self_upload_disabled Sign in with Google or Microsoft to upload your own files
13895
14621
  file_too_large Reduce file or directory size and retry
13896
- validation_failed Check file type (.html / .md for single files) and directory layout`
14622
+ upload_read_failed Check filesystem availability and permissions, then retry
14623
+ validation_failed Check file type (.html / .md for single files) and directory layout
14624
+ link Copy into the selection or pass the target by absolute path
14625
+ outside_cwd Pass an absolute path
14626
+ parent_traversal Pass a direct absolute path without any .. component
14627
+ changed The selection changed while reading; retry
14628
+ not_found Check the path and retry
14629
+ invalid_type Select a regular file or directory
14630
+ unsupported_guarantee Select a filesystem with stable dev/ino and no-follow support`
13897
14631
  });
13898
14632
  const appendDefinition = define({
13899
14633
  name: "append",
@@ -13911,7 +14645,18 @@ const appendDefinition = define({
13911
14645
  description: "Non-empty UTF-8 file to append"
13912
14646
  }
13913
14647
  },
13914
- examples: `Append <path> without a separator and create a new version at the existing share URL.\n\nFor Markdown, the file is added at the end of the current source. For HTML, it is inserted immediately before an ASCII case-insensitive </body> closing tag; when the tag is absent, it is added at the end.\n\nStatic sites are not supported. Use update to replace the full source instead.`
14648
+ examples: `Append <path> without a separator and create a new version at the existing share URL.\n\nFor Markdown, the file is added at the end of the current source. For HTML, it is inserted immediately before an ASCII case-insensitive </body> closing tag; when the tag is absent, it is added at the end.\n\nStatic sites are not supported. Use update to replace the full source instead.
14649
+
14650
+ Common failures:
14651
+ upload_read_failed Check filesystem availability and permissions, then retry
14652
+ validation_failed Check the selected file
14653
+ link Copy into the selection or pass the target by absolute path
14654
+ outside_cwd Pass an absolute path
14655
+ parent_traversal Pass a direct absolute path without any .. component
14656
+ changed The selection changed while reading; retry
14657
+ not_found Check the path and retry
14658
+ invalid_type Select a regular file
14659
+ unsupported_guarantee Select a filesystem with stable dev/ino and no-follow support`
13915
14660
  });
13916
14661
  const editDefinition = define({
13917
14662
  name: "edit",
@@ -13922,7 +14667,7 @@ const editDefinition = define({
13922
14667
  artifactIdOrUrl: {
13923
14668
  type: "positional",
13924
14669
  toKebab: true,
13925
- description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14670
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL"
13926
14671
  },
13927
14672
  title: {
13928
14673
  type: "string",
@@ -14000,7 +14745,7 @@ const deleteDefinition = define({
14000
14745
  artifactIdOrUrl: {
14001
14746
  type: "positional",
14002
14747
  toKebab: true,
14003
- description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14748
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL"
14004
14749
  }
14005
14750
  },
14006
14751
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare delete abc123def4 --json
@@ -14046,7 +14791,7 @@ const downloadDefinition = define({
14046
14791
  type: "positional",
14047
14792
  toKebab: true,
14048
14793
  required: false,
14049
- description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14794
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL"
14050
14795
  },
14051
14796
  projectId: {
14052
14797
  type: "string",
@@ -14061,7 +14806,7 @@ const downloadDefinition = define({
14061
14806
  force: {
14062
14807
  type: "boolean",
14063
14808
  toKebab: true,
14064
- description: "Allow writing into an existing output directory"
14809
+ description: "Replace existing output; retain backups for recovery"
14065
14810
  }
14066
14811
  },
14067
14812
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare download abc123def4 --json
@@ -14070,12 +14815,20 @@ const downloadDefinition = define({
14070
14815
 
14071
14816
  Use resolve first when a user gives a title or project name, then pass the id here.
14072
14817
  Download writes files to a directory so the result can be inspected or passed to update.
14818
+ Artifact IDs must match ^[a-z0-9]{10}$; invalid or duplicate list/index IDs fail before writes.
14819
+ Download accepts linked output parents and rechecks their resolved directory identities.
14820
+ Links in the output root, index, and every listed artifact are rejected, regardless of --force.
14821
+ Project preflight checks every listed artifact tree, including unchanged versions, but not unrelated content.
14822
+ Network failures and invalid manifest paths, bodies, or identities have individual artifact results; a boundary error aborts the remaining publications.
14823
+ Replacement retains originals and previous indexes in data.backup_paths after success; inspect them before manual cleanup.
14824
+ Identity checks detect observed swaps;
14825
+ Node path-based operations cannot guarantee atomic confinement against concurrent changes.
14073
14826
 
14074
14827
  Common failures:
14075
14828
  auth_required Set ARTIFACTSHARE_TOKEN before download
14076
14829
  target_not_found Retry with an artifact ID, share URL, or sandbox URL
14077
14830
  output_exists Choose another --output path or pass --force
14078
- validation_failed Check --output and downloaded file paths`
14831
+ validation_failed Check the named ID/path; use a regular directory without links`
14079
14832
  });
14080
14833
  const openDefinition = define({
14081
14834
  name: "open",
@@ -14086,7 +14839,7 @@ const openDefinition = define({
14086
14839
  artifactIdOrUrl: {
14087
14840
  type: "positional",
14088
14841
  toKebab: true,
14089
- description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14842
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL"
14090
14843
  }
14091
14844
  },
14092
14845
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare open https://artifactshare.com/a/abc123def4 --json
@@ -14115,7 +14868,7 @@ const moveDefinition = define({
14115
14868
  artifactIdOrUrl: {
14116
14869
  type: "positional",
14117
14870
  toKebab: true,
14118
- description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14871
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL"
14119
14872
  },
14120
14873
  projectId: {
14121
14874
  type: "string",
@@ -14150,7 +14903,7 @@ const artifactsGetDefinition = define({
14150
14903
  artifactIdOrUrl: {
14151
14904
  type: "positional",
14152
14905
  toKebab: true,
14153
- description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14906
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL"
14154
14907
  },
14155
14908
  offset: {
14156
14909
  type: "string",
@@ -14263,7 +15016,7 @@ const commentsListDefinition = define({
14263
15016
  artifactIdOrUrl: {
14264
15017
  type: "positional",
14265
15018
  toKebab: true,
14266
- description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
15019
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL"
14267
15020
  }
14268
15021
  },
14269
15022
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare comments list abc123def4 --json
@@ -14288,7 +15041,7 @@ const commentsPostDefinition = define({
14288
15041
  artifactIdOrUrl: {
14289
15042
  type: "positional",
14290
15043
  toKebab: true,
14291
- description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
15044
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL"
14292
15045
  },
14293
15046
  body: {
14294
15047
  type: "string",
@@ -14341,7 +15094,7 @@ const commentThreadActionArgs = {
14341
15094
  artifactIdOrUrl: {
14342
15095
  type: "positional",
14343
15096
  toKebab: true,
14344
- description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
15097
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL"
14345
15098
  },
14346
15099
  threadId: {
14347
15100
  type: "string",
@@ -14354,7 +15107,7 @@ const commentMessageActionArgs = {
14354
15107
  artifactIdOrUrl: {
14355
15108
  type: "positional",
14356
15109
  toKebab: true,
14357
- description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
15110
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer URL, artifactshareusercontent.com execution URL, or legacy sandbox URL"
14358
15111
  },
14359
15112
  messageId: {
14360
15113
  type: "string",
@@ -14807,7 +15560,11 @@ const projectsListDefinition = define({
14807
15560
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare projects list --json
14808
15561
 
14809
15562
  is_default marks the working-directory default project from .artifactshare/config.json.
14810
- Use a project id with share --project-id or init --project-id.`
15563
+ Use a project id with share --project-id or init --project-id.
15564
+ Only active, authorized destinations are listed. Private projects require creator access,
15565
+ team-plan owner/admin access, or a verified contributor/manager grant. Free/plus
15566
+ admin status and viewer or artifact-only grants do not authorize placement.
15567
+ Agents and bots retain their fixed-project and verified-grant limits; publishers cannot select projects.`
14811
15568
  });
14812
15569
  const projectsCreateDefinition = define({
14813
15570
  name: "create",
@@ -15078,6 +15835,9 @@ and Cursor skills. Cursor project scope is not auto-installed; use skills instal
15078
15835
  data.mode is "onboarding".
15079
15836
  With --profile or --project-id, init saves working-directory defaults to
15080
15837
  .artifactshare/config.local.json instead (data.mode is "config"); secrets are never written there.
15838
+ Config saves preserve unknown keys and refuse linked or changed paths.
15839
+ Only a regular repository .git directory can receive an info/exclude update.
15840
+ Git worktrees/submodules still save config; git_exclude_warning gives the exact line to add manually.
15081
15841
 
15082
15842
  Common failures:
15083
15843
  skill_update_conflict An unmanaged or broken skill file exists; inspect it before overwriting