@artifactshare/cli 0.22.0 → 0.23.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/CHANGELOG.md +20 -0
- package/README.md +79 -25
- package/dist/cli.js +1001 -317
- package/dist/{cursor-acp-C19O-3Za.js → cursor-acp-0XpA0raU.js} +1 -1
- package/dist/cursor-acp-entry.js +1 -1
- package/dist/{cursor-notification-Hz6fuACK.js → cursor-notification--78v1rgg.js} +1 -1
- package/package.json +3 -2
- package/skills/artifactshare/SKILL.md +67 -28
- package/skills/artifactshare/references/comments.md +15 -0
- package/skills/artifactshare/references/organize-settings.md +2 -0
- package/skills/artifactshare/references/preview.md +12 -0
- package/skills/artifactshare/references/rest-api-only.md +4 -0
- package/skills/artifactshare/references/static-sites.md +4 -0
- package/skills/artifactshare/references/version-labels.md +2 -0
package/dist/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
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
|
|
1
|
+
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--78v1rgg.js";
|
|
2
2
|
import { chmodSync, constants, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, watch, writeFileSync } from "node:fs";
|
|
3
3
|
import { fileURLToPath } from "node:url";
|
|
4
4
|
import { cli, define, lazy } from "gunshi";
|
|
@@ -29,12 +29,16 @@ const ArtifactKindSchema = z.enum([
|
|
|
29
29
|
"html_page",
|
|
30
30
|
"static_site",
|
|
31
31
|
"spa",
|
|
32
|
-
"workspace_app"
|
|
32
|
+
"workspace_app",
|
|
33
|
+
"pdf",
|
|
34
|
+
"video"
|
|
33
35
|
]);
|
|
34
36
|
const UploadArtifactKindSchema = z.enum([
|
|
35
37
|
"markdown_page",
|
|
36
38
|
"html_page",
|
|
37
|
-
"static_site"
|
|
39
|
+
"static_site",
|
|
40
|
+
"pdf",
|
|
41
|
+
"video"
|
|
38
42
|
]);
|
|
39
43
|
const VisibilitySchema = z.enum([
|
|
40
44
|
"private",
|
|
@@ -244,6 +248,7 @@ const CliDoctorResponseSchema = z.object({
|
|
|
244
248
|
});
|
|
245
249
|
z.object({
|
|
246
250
|
publish_key: z.string().optional(),
|
|
251
|
+
key_visibility: VisibilitySchema.optional(),
|
|
247
252
|
expected_version: z.string().optional(),
|
|
248
253
|
artifact_kind: z.literal("static_site").optional(),
|
|
249
254
|
container_id: z.string().optional()
|
|
@@ -339,6 +344,13 @@ z.object({
|
|
|
339
344
|
}
|
|
340
345
|
})
|
|
341
346
|
});
|
|
347
|
+
const CLI_STATIC_METADATA_HEADER = "X-ArtifactShare-Static-Metadata";
|
|
348
|
+
const CLI_ARTIFACT_KINDS_HEADER = "X-ArtifactShare-Artifact-Kinds";
|
|
349
|
+
const ArtifactVersionSummarySchema = z.object({
|
|
350
|
+
retain_versions: z.number().int().positive().nullable(),
|
|
351
|
+
version_count: z.number().int().nonnegative(),
|
|
352
|
+
total_size_bytes: z.number().int().nonnegative()
|
|
353
|
+
});
|
|
342
354
|
const ArtifactVersionSchema = z.object({
|
|
343
355
|
label: VersionLabelSchema.optional(),
|
|
344
356
|
version_id: stringId,
|
|
@@ -354,8 +366,18 @@ const ArtifactVersionSchema = z.object({
|
|
|
354
366
|
agent_profile_id: stringId.nullable()
|
|
355
367
|
}).nullable()
|
|
356
368
|
});
|
|
369
|
+
const ArtifactVersionsResponseSchema = ArtifactVersionSummarySchema.extend({
|
|
370
|
+
id: stringId,
|
|
371
|
+
versions: z.array(ArtifactVersionSchema),
|
|
372
|
+
limit: z.number().int().positive(),
|
|
373
|
+
has_more: z.boolean(),
|
|
374
|
+
next_cursor: z.string().nullable()
|
|
375
|
+
});
|
|
357
376
|
const ArtifactReadResponseSchema = z.object({
|
|
377
|
+
...ArtifactVersionSummarySchema.partial().shape,
|
|
358
378
|
id: stringId,
|
|
379
|
+
title: z.string(),
|
|
380
|
+
visibility: VisibilitySchema,
|
|
359
381
|
share_url: url,
|
|
360
382
|
version_id: stringId,
|
|
361
383
|
format: z.enum(["html", "markdown"]),
|
|
@@ -370,9 +392,13 @@ const ArtifactReadResponseSchema = z.object({
|
|
|
370
392
|
comments: z.array(z.lazy(() => CommentThreadSchema)).optional(),
|
|
371
393
|
comments_has_more: z.boolean().optional()
|
|
372
394
|
});
|
|
373
|
-
const PublisherSingleFileReadResponseSchema = ArtifactReadResponseSchema.
|
|
395
|
+
const PublisherSingleFileReadResponseSchema = ArtifactReadResponseSchema.omit({
|
|
396
|
+
version_count: true,
|
|
397
|
+
total_size_bytes: true
|
|
398
|
+
}).extend({ visibility: VisibilitySchema });
|
|
374
399
|
const PublisherStaticSiteReadResponseSchema = z.object({
|
|
375
400
|
id: stringId,
|
|
401
|
+
title: z.string(),
|
|
376
402
|
share_url: url,
|
|
377
403
|
version_id: stringId,
|
|
378
404
|
artifact_kind: z.literal("static_site"),
|
|
@@ -381,6 +407,7 @@ const PublisherStaticSiteReadResponseSchema = z.object({
|
|
|
381
407
|
link_expires_at: nullableTimestamp,
|
|
382
408
|
retain_versions: z.number().int().min(1).nullable()
|
|
383
409
|
});
|
|
410
|
+
const ArtifactGetResponseSchema = z.union([ArtifactReadResponseSchema, PublisherStaticSiteReadResponseSchema.extend(ArtifactVersionSummarySchema.omit({ retain_versions: true }).partial().shape)]);
|
|
384
411
|
z.union([PublisherSingleFileReadResponseSchema, PublisherStaticSiteReadResponseSchema]);
|
|
385
412
|
z.object({ retain_versions: z.number().int().min(1).nullable() }).strict();
|
|
386
413
|
z.object({ publisher_client_id: stringId }).strict();
|
|
@@ -415,6 +442,7 @@ const DownloadManifestResponseSchema = z.object({
|
|
|
415
442
|
project_id: stringId.nullable().optional()
|
|
416
443
|
});
|
|
417
444
|
const ArtifactsListEntrySchema = z.object({
|
|
445
|
+
...ArtifactVersionSummarySchema.partial().shape,
|
|
418
446
|
id: ArtifactIdSchema,
|
|
419
447
|
title: z.string(),
|
|
420
448
|
share_url: url,
|
|
@@ -434,9 +462,18 @@ const ArtifactsListResponseSchema = z.object({
|
|
|
434
462
|
const CommentAnchorSchema = z.union([z.object({
|
|
435
463
|
kind: z.literal("artifact"),
|
|
436
464
|
quoted_text: z.null(),
|
|
437
|
-
state: z.null()
|
|
438
|
-
|
|
465
|
+
state: z.null(),
|
|
466
|
+
page_number: z.number().int().min(1).max(1e5).optional(),
|
|
467
|
+
version_id: z.string().nullable().optional(),
|
|
468
|
+
version_number: z.number().int().positive().nullable().optional()
|
|
469
|
+
}).refine((anchor) => [
|
|
470
|
+
anchor.page_number,
|
|
471
|
+
anchor.version_id,
|
|
472
|
+
anchor.version_number
|
|
473
|
+
].every((value) => value === void 0) || anchor.page_number !== void 0 && anchor.version_id !== void 0 && anchor.version_number !== void 0, { message: "page_number, version_id and version_number go together" }), z.object({
|
|
439
474
|
kind: z.literal("text"),
|
|
475
|
+
page_number: z.never().optional(),
|
|
476
|
+
version_number: z.never().optional(),
|
|
440
477
|
quoted_text: z.string(),
|
|
441
478
|
state: z.enum(["attached", "orphaned"]),
|
|
442
479
|
position_state: z.enum([
|
|
@@ -451,6 +488,7 @@ const CommentAnchorSchema = z.union([z.object({
|
|
|
451
488
|
block_text: z.string().max(600)
|
|
452
489
|
}).optional(),
|
|
453
490
|
version_id: z.string().nullable().optional(),
|
|
491
|
+
target_path: z.string().optional(),
|
|
454
492
|
ambiguous_at_creation: z.boolean().optional()
|
|
455
493
|
})]);
|
|
456
494
|
const CommentMessageSchema = z.object({
|
|
@@ -853,6 +891,7 @@ const COMMAND_NAMES = /* @__PURE__ */ new Set([
|
|
|
853
891
|
"download",
|
|
854
892
|
"move",
|
|
855
893
|
"artifacts",
|
|
894
|
+
"artifacts versions",
|
|
856
895
|
"comments",
|
|
857
896
|
"whoami",
|
|
858
897
|
"doctor",
|
|
@@ -873,6 +912,7 @@ const SUBCOMMANDS = {
|
|
|
873
912
|
artifacts: [
|
|
874
913
|
"list",
|
|
875
914
|
"get",
|
|
915
|
+
"versions",
|
|
876
916
|
"delete"
|
|
877
917
|
],
|
|
878
918
|
comments: [
|
|
@@ -965,6 +1005,31 @@ function apiError(body) {
|
|
|
965
1005
|
}
|
|
966
1006
|
function mapApiError(status, body, options = {}) {
|
|
967
1007
|
const { code: apiCode, message: apiMessage } = apiError(body);
|
|
1008
|
+
if (status === 409 && apiCode === "key-visibility-mismatch" && options.artifactTarget && options.operation === "share") {
|
|
1009
|
+
const raw = isRecord$1(body) && isRecord$1(body.error) ? body.error : void 0;
|
|
1010
|
+
const details = raw && isRecord$1(raw.details) ? raw.details : void 0;
|
|
1011
|
+
const requested = VisibilitySchema.safeParse(details?.requested_visibility);
|
|
1012
|
+
const current = VisibilitySchema.safeParse(details?.current_visibility);
|
|
1013
|
+
if (details && typeof details.artifact_id === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(details.artifact_id) && requested.success && current.success) {
|
|
1014
|
+
const expiry = options.linkExpiresAt;
|
|
1015
|
+
const expiryOption = requested.data !== "link" ? "" : expiry !== void 0 ? ` --link-expires-at ${/^[A-Za-z0-9:.-]+$/.test(expiry) ? expiry : "'" + expiry.replaceAll("'", "'\\''") + "'"}` : options.noLinkExpiry === true ? " --no-link-expiry" : "";
|
|
1016
|
+
const command = `${CLI_INVOCATION} edit ${details.artifact_id} --visibility ${requested.data}${expiryOption} --json`;
|
|
1017
|
+
const requiresHuman = details.requires_human === true;
|
|
1018
|
+
return cliError({
|
|
1019
|
+
code: "key_visibility_mismatch",
|
|
1020
|
+
message: "Resending does not change visibility. No version was created.",
|
|
1021
|
+
why: `The artifact visibility is ${current.data}; --visibility requested ${requested.data}.`,
|
|
1022
|
+
hint: requiresHuman ? `Ask a person with a human credential to run ${command}` : `To change visibility intentionally, run ${command}`,
|
|
1023
|
+
agentRecoverable: !requiresHuman,
|
|
1024
|
+
requiresHuman,
|
|
1025
|
+
recovery: requiresHuman ? { kind: "ask_human" } : {
|
|
1026
|
+
kind: "run_command",
|
|
1027
|
+
command
|
|
1028
|
+
},
|
|
1029
|
+
details
|
|
1030
|
+
});
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
968
1033
|
if (apiCode === "rate-limited" || apiCode === "thread-capacity") {
|
|
969
1034
|
const raw = isRecord$1(body) && isRecord$1(body.error) ? body.error : void 0;
|
|
970
1035
|
const details = raw && isRecord$1(raw.details) ? raw.details : void 0;
|
|
@@ -1129,8 +1194,8 @@ function mapApiError(status, body, options = {}) {
|
|
|
1129
1194
|
if (options.artifactTarget && apiCode === "unsupported-kind") return cliError({
|
|
1130
1195
|
code: "unsupported_kind",
|
|
1131
1196
|
message: apiMessage ?? "This artifact cannot be read as a single source file.",
|
|
1132
|
-
why: "Static sites
|
|
1133
|
-
hint: "
|
|
1197
|
+
why: "Static sites, other multi-file artifacts, PDFs and videos do not have one Markdown or HTML source to read back.",
|
|
1198
|
+
hint: "Run download <artifact> to save the original files (a PDF or video downloads as its original .pdf or .mp4), or open the share URL in a browser.",
|
|
1134
1199
|
agentRecoverable: true,
|
|
1135
1200
|
requiresHuman: false,
|
|
1136
1201
|
recovery: { kind: "change_input" }
|
|
@@ -1797,6 +1862,7 @@ const TARGET_COMMAND_LABELS = {
|
|
|
1797
1862
|
update: "Update",
|
|
1798
1863
|
open: "Open",
|
|
1799
1864
|
"artifacts get": "Artifacts get",
|
|
1865
|
+
"artifacts versions": "Artifacts versions",
|
|
1800
1866
|
download: "Download",
|
|
1801
1867
|
"comments list": "Comments list",
|
|
1802
1868
|
"comments post": "Comments post",
|
|
@@ -2072,244 +2138,6 @@ function createArgumentParser(catalog) {
|
|
|
2072
2138
|
};
|
|
2073
2139
|
}
|
|
2074
2140
|
//#endregion
|
|
2075
|
-
//#region src/output.ts
|
|
2076
|
-
function outputModeFromArgv(argv) {
|
|
2077
|
-
return outputMode({ json: argv.includes("--json") });
|
|
2078
|
-
}
|
|
2079
|
-
function outputMode(options) {
|
|
2080
|
-
return { json: Boolean(options.json) || process.env.CI === "true" || !process.stdout.isTTY };
|
|
2081
|
-
}
|
|
2082
|
-
function writeSuccess(command, data, mode) {
|
|
2083
|
-
if (!mode.json && command === "share" && !shareSuccessFields(data)) return writeFailure(command, serviceError("Share succeeded but the response did not include an artifact id and URL."), mode, 1);
|
|
2084
|
-
const payload = {
|
|
2085
|
-
schema_version: 2,
|
|
2086
|
-
ok: true,
|
|
2087
|
-
command,
|
|
2088
|
-
data
|
|
2089
|
-
};
|
|
2090
|
-
if (mode.json) {
|
|
2091
|
-
process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
|
|
2092
|
-
return;
|
|
2093
|
-
}
|
|
2094
|
-
process.stdout.write(humanSuccess(command, data));
|
|
2095
|
-
}
|
|
2096
|
-
/** Emit a success envelope as a single line. `preview` keeps running after it
|
|
2097
|
-
* reports readiness, so a launcher cannot wait for EOF to parse the payload;
|
|
2098
|
-
* one line lets it read the envelope and move on. */
|
|
2099
|
-
function writeSuccessLine(command, data, mode) {
|
|
2100
|
-
const payload = {
|
|
2101
|
-
schema_version: 2,
|
|
2102
|
-
ok: true,
|
|
2103
|
-
command,
|
|
2104
|
-
data
|
|
2105
|
-
};
|
|
2106
|
-
if (mode.json) {
|
|
2107
|
-
process.stdout.write(`${JSON.stringify(payload)}\n`);
|
|
2108
|
-
return;
|
|
2109
|
-
}
|
|
2110
|
-
process.stdout.write(`${JSON.stringify(data)}\n`);
|
|
2111
|
-
}
|
|
2112
|
-
function dataWithSkillAutoUpdate(data, autoUpdate) {
|
|
2113
|
-
if (!autoUpdate || autoUpdate.targets.length === 0) return data;
|
|
2114
|
-
if (!isRecord$1(data)) return data;
|
|
2115
|
-
const existingSkills = isRecord$1(data.skills) ? data.skills : {};
|
|
2116
|
-
return {
|
|
2117
|
-
...data,
|
|
2118
|
-
skills: {
|
|
2119
|
-
...existingSkills,
|
|
2120
|
-
auto_update: autoUpdate
|
|
2121
|
-
}
|
|
2122
|
-
};
|
|
2123
|
-
}
|
|
2124
|
-
function writeFailure(command, error, mode, exitCode) {
|
|
2125
|
-
const payload = {
|
|
2126
|
-
schema_version: 2,
|
|
2127
|
-
ok: false,
|
|
2128
|
-
command,
|
|
2129
|
-
error
|
|
2130
|
-
};
|
|
2131
|
-
if (mode.json) process.stderr.write(`${JSON.stringify(payload, null, 2)}\n`);
|
|
2132
|
-
else {
|
|
2133
|
-
const upgradeRequest = isRecord$1(error.details?.upgrade_request) ? error.details.upgrade_request : null;
|
|
2134
|
-
const upgradeHint = upgradeRequest?.kind === "contact" && typeof upgradeRequest.request_message === "string" ? upgradeRequest.request_message : upgradeRequest?.kind === "billing" && typeof upgradeRequest.upgrade_url === "string" ? upgradeRequest.upgrade_url : upgradeRequest?.kind === "support" && typeof upgradeRequest.support_url === "string" ? upgradeRequest.support_url : null;
|
|
2135
|
-
process.stderr.write(`Error: ${error.message}\nWhy: ${error.why}\nHint: ${error.hint}${upgradeHint ? `\n${upgradeHint}` : ""}\n`);
|
|
2136
|
-
}
|
|
2137
|
-
process.exitCode = exitCode;
|
|
2138
|
-
}
|
|
2139
|
-
function writeText(text) {
|
|
2140
|
-
process.stdout.write(text);
|
|
2141
|
-
}
|
|
2142
|
-
function writeEvent(data) {
|
|
2143
|
-
process.stderr.write(`${JSON.stringify(data)}\n`);
|
|
2144
|
-
}
|
|
2145
|
-
function humanSuccess(command, data) {
|
|
2146
|
-
const suffix = skillAutoUpdateHumanOutput(data);
|
|
2147
|
-
if (command === "share") {
|
|
2148
|
-
const fields = shareSuccessFields(data);
|
|
2149
|
-
if (!fields) return `${JSON.stringify(data, null, 2)}\n`;
|
|
2150
|
-
const output = [
|
|
2151
|
-
"Shared",
|
|
2152
|
-
`Artifact ID: ${fields.artifactId}`,
|
|
2153
|
-
`URL: ${fields.url}`,
|
|
2154
|
-
`Destination: ${fields.destinationType}${fields.projectId ? ` (${fields.projectId})` : ""}`,
|
|
2155
|
-
`Visibility: ${fields.visibility}`,
|
|
2156
|
-
...fields.visibilityHint ? [`Note: ${fields.visibilityHint}`] : [],
|
|
2157
|
-
""
|
|
2158
|
-
].join("\n");
|
|
2159
|
-
const warnings = shareWarnings(data);
|
|
2160
|
-
const withWarnings = warnings.length ? `${output}${warnings.map((message) => `Warning: ${message}`).join("\n")}\n` : output;
|
|
2161
|
-
return suffix ? `${withWarnings}${suffix}` : withWarnings;
|
|
2162
|
-
}
|
|
2163
|
-
if (command === "download" && isRecord$1(data) && Array.isArray(data.backup_paths)) {
|
|
2164
|
-
const recovery = data.backup_paths.map((path) => `Original data retained at ${String(path)}; inspect it before manual cleanup.`).join("\n");
|
|
2165
|
-
return `${JSON.stringify(data, null, 2)}\n${recovery ? `${recovery}\n` : ""}`;
|
|
2166
|
-
}
|
|
2167
|
-
if (command === "doctor") return doctorHumanOutput(data);
|
|
2168
|
-
if (command === "open") return openHumanOutput(data);
|
|
2169
|
-
if (command === "init") return initHumanOutput(data);
|
|
2170
|
-
if (command === "artifacts list" && isRecord$1(data) && data.has_more === true && typeof data.next_cursor === "string") return `${JSON.stringify(data, null, 2)}\nContinue with --cursor ${data.next_cursor}\n`;
|
|
2171
|
-
if (command === "changelog") return changelogHumanOutput(data);
|
|
2172
|
-
if (command === "login" || command === "whoami") return credentialLifetimeHumanOutput(data);
|
|
2173
|
-
const output = `${JSON.stringify(data, null, 2)}\n`;
|
|
2174
|
-
return suffix ? `${output}${suffix}` : output;
|
|
2175
|
-
}
|
|
2176
|
-
function credentialLifetimeHumanOutput(data) {
|
|
2177
|
-
const body = `${JSON.stringify(data, null, 2)}`;
|
|
2178
|
-
if (!isRecord$1(data) || !isRecord$1(data.renewal)) return `${body}\n`;
|
|
2179
|
-
const lines = [body];
|
|
2180
|
-
if ("session_expires_at" in data) lines.push(`Session expires: ${typeof data.session_expires_at === "string" ? data.session_expires_at : "unknown"}`);
|
|
2181
|
-
if ("refresh_credential_expires_at" in data) lines.push(`Refresh credential expires: ${typeof data.refresh_credential_expires_at === "string" ? data.refresh_credential_expires_at : "unknown"}`);
|
|
2182
|
-
if (data.renewal.kind === "automatic") lines.push("Renewal: normal CLI use automatically renews an unauthorized session while the refresh credential remains valid.");
|
|
2183
|
-
return `${lines.join("\n")}\n`;
|
|
2184
|
-
}
|
|
2185
|
-
function shareWarnings(data) {
|
|
2186
|
-
if (!isRecord$1(data) || !Array.isArray(data.warnings)) return [];
|
|
2187
|
-
return data.warnings.flatMap((warning) => isRecord$1(warning) && warning.code === "slack_reauthorization_required" && typeof warning.message === "string" ? [warning.message] : []);
|
|
2188
|
-
}
|
|
2189
|
-
function skillAutoUpdateHumanOutput(data) {
|
|
2190
|
-
if (!isRecord$1(data)) return "";
|
|
2191
|
-
const skills = data.skills;
|
|
2192
|
-
if (!isRecord$1(skills)) return "";
|
|
2193
|
-
const autoUpdate = skills.auto_update;
|
|
2194
|
-
if (!isRecord$1(autoUpdate) || !Array.isArray(autoUpdate.targets)) return "";
|
|
2195
|
-
const lines = autoUpdate.targets.filter(isRecord$1).map((target) => {
|
|
2196
|
-
const label = Array.isArray(target.aliases) ? target.aliases.filter(isRecord$1).map((alias) => `${alias.tool}:${alias.scope}`).join(", ") : typeof target.tool === "string" && typeof target.scope === "string" ? `${target.tool}:${target.scope}` : "unknown";
|
|
2197
|
-
if (target.action === "update_recommended") {
|
|
2198
|
-
const advice = [target.update_command, target.hint].filter((value) => typeof value === "string").join("; ");
|
|
2199
|
-
return `Skill update recommended: ${label}${advice ? ` (${advice})` : ""}`;
|
|
2200
|
-
}
|
|
2201
|
-
return `Skill updated: ${label}`;
|
|
2202
|
-
});
|
|
2203
|
-
return lines.length > 0 ? `${lines.join("\n")}\n` : "";
|
|
2204
|
-
}
|
|
2205
|
-
function initHumanOutput(data) {
|
|
2206
|
-
const body = `${JSON.stringify(data, null, 2)}`;
|
|
2207
|
-
const nextCommand = initNextCommand(data);
|
|
2208
|
-
if (!nextCommand) return `${body}\n`;
|
|
2209
|
-
return `${body}\nNext command: ${nextCommand}\n`;
|
|
2210
|
-
}
|
|
2211
|
-
function initNextCommand(data) {
|
|
2212
|
-
if (!isRecord$1(data) || data.mode !== "onboarding") return null;
|
|
2213
|
-
const steps = data.next_steps;
|
|
2214
|
-
if (!Array.isArray(steps)) return null;
|
|
2215
|
-
const pending = steps.find((step) => isRecord$1(step) && step.done !== true && typeof step.command === "string");
|
|
2216
|
-
return isRecord$1(pending) && typeof pending.command === "string" ? pending.command : null;
|
|
2217
|
-
}
|
|
2218
|
-
function openHumanOutput(data) {
|
|
2219
|
-
const body = `${JSON.stringify(data, null, 2)}`;
|
|
2220
|
-
const nextCommand = openNextCommand(data);
|
|
2221
|
-
if (!nextCommand) return `${body}\n`;
|
|
2222
|
-
return `${body}\nNext command: ${nextCommand}\n`;
|
|
2223
|
-
}
|
|
2224
|
-
function openNextCommand(data) {
|
|
2225
|
-
if (!isOpenData(data)) return null;
|
|
2226
|
-
return data.open.kind === "download_required" ? data.open.next_command : null;
|
|
2227
|
-
}
|
|
2228
|
-
function isOpenData(data) {
|
|
2229
|
-
if (!isRecord$1(data)) return false;
|
|
2230
|
-
const open = data.open;
|
|
2231
|
-
if (!isRecord$1(open)) return false;
|
|
2232
|
-
if (open.kind === "read") return true;
|
|
2233
|
-
return open.kind === "download_required" && typeof open.next_command === "string";
|
|
2234
|
-
}
|
|
2235
|
-
function doctorHumanOutput(data) {
|
|
2236
|
-
const nextCommand = doctorNextCommand(data);
|
|
2237
|
-
const body = `${JSON.stringify(data, null, 2)}`;
|
|
2238
|
-
if (!nextCommand) return `${body}\n`;
|
|
2239
|
-
return `${body}\n${nextCommand}\n`;
|
|
2240
|
-
}
|
|
2241
|
-
function doctorNextCommand(data) {
|
|
2242
|
-
if (!isRecord$1(data) || !("next_command" in data)) return null;
|
|
2243
|
-
return typeof data.next_command === "string" ? data.next_command : null;
|
|
2244
|
-
}
|
|
2245
|
-
function changelogHumanOutput(data) {
|
|
2246
|
-
if (!isRecord$1(data)) return `${JSON.stringify(data, null, 2)}\n`;
|
|
2247
|
-
const version = typeof data.version === "string" ? data.version : "";
|
|
2248
|
-
const updatesUrl = typeof data.updates_url === "string" ? data.updates_url : "";
|
|
2249
|
-
const lines = [
|
|
2250
|
-
`Artifact Share CLI ${version}`,
|
|
2251
|
-
"",
|
|
2252
|
-
`Updates: ${updatesUrl}`
|
|
2253
|
-
];
|
|
2254
|
-
const latest = data.latest;
|
|
2255
|
-
if (isRecord$1(latest) && typeof latest.body === "string" && latest.body) {
|
|
2256
|
-
const latestVersion = typeof latest.version === "string" ? latest.version : version;
|
|
2257
|
-
const latestDate = typeof latest.date === "string" ? latest.date : "";
|
|
2258
|
-
lines.push("", `Changes in ${latestVersion} (${latestDate}):`, latest.body);
|
|
2259
|
-
}
|
|
2260
|
-
return `${lines.join("\n")}\n`;
|
|
2261
|
-
}
|
|
2262
|
-
function shareSuccessFields(data) {
|
|
2263
|
-
if (!isRecord$1(data)) return null;
|
|
2264
|
-
const artifact = data.artifact;
|
|
2265
|
-
const destination = data.destination;
|
|
2266
|
-
const share = data.share;
|
|
2267
|
-
if (!isRecord$1(artifact) || !isRecord$1(destination) || !isRecord$1(share)) return null;
|
|
2268
|
-
if (typeof artifact.id !== "string" || typeof artifact.url !== "string" || typeof destination.type !== "string" || typeof share.visibility !== "string") return null;
|
|
2269
|
-
return {
|
|
2270
|
-
artifactId: artifact.id,
|
|
2271
|
-
url: artifact.url,
|
|
2272
|
-
destinationType: destination.type,
|
|
2273
|
-
visibilityHint: typeof share.visibility_hint === "string" ? share.visibility_hint : null,
|
|
2274
|
-
projectId: typeof destination.project_id === "string" ? destination.project_id : null,
|
|
2275
|
-
visibility: share.visibility
|
|
2276
|
-
};
|
|
2277
|
-
}
|
|
2278
|
-
function updateSuccessFields(data) {
|
|
2279
|
-
if (!isRecord$1(data)) return null;
|
|
2280
|
-
const artifact = data.artifact;
|
|
2281
|
-
const version = data.version;
|
|
2282
|
-
if (!isRecord$1(artifact) || !isRecord$1(version)) return null;
|
|
2283
|
-
if (typeof artifact.id !== "string" || typeof artifact.url !== "string" || typeof version.id !== "string") return null;
|
|
2284
|
-
return {
|
|
2285
|
-
artifactId: artifact.id,
|
|
2286
|
-
url: artifact.url,
|
|
2287
|
-
versionId: version.id
|
|
2288
|
-
};
|
|
2289
|
-
}
|
|
2290
|
-
function resolveSuccessFields(data) {
|
|
2291
|
-
return isContract(RESOLVE_RESPONSE_SCHEMA, data);
|
|
2292
|
-
}
|
|
2293
|
-
function artifactGetSuccessFields(data) {
|
|
2294
|
-
if (isContract(ARTIFACT_READ_RESPONSE_SCHEMA, data)) return true;
|
|
2295
|
-
if (!isRecord$1(data)) return false;
|
|
2296
|
-
return typeof data.id === "string" && typeof data.share_url === "string" && typeof data.version_id === "string" && (data.format === "html" || data.format === "markdown") && typeof data.content === "string" && typeof data.size_bytes === "number" && typeof data.truncated === "boolean" && (typeof data.next_offset === "number" || data.next_offset === null) && (data.link_expires_at === void 0 || typeof data.link_expires_at === "string" || data.link_expires_at === null);
|
|
2297
|
-
}
|
|
2298
|
-
function artifactsListSuccessFields(data) {
|
|
2299
|
-
return isContract(ARTIFACTS_LIST_RESPONSE_SCHEMA, data);
|
|
2300
|
-
}
|
|
2301
|
-
function deleteSuccessFields(data) {
|
|
2302
|
-
return isContract(ARTIFACT_DELETE_RESPONSE_SCHEMA, data);
|
|
2303
|
-
}
|
|
2304
|
-
function downloadManifestFields(data) {
|
|
2305
|
-
if (isContract(DOWNLOAD_MANIFEST_RESPONSE_SCHEMA, data)) return true;
|
|
2306
|
-
if (!isRecord$1(data)) return false;
|
|
2307
|
-
return typeof data.id === "string" && typeof data.share_url === "string" && typeof data.version_id === "string" && typeof data.artifact_kind === "string" && Array.isArray(data.files) && data.files.every((file) => {
|
|
2308
|
-
if (!isRecord$1(file)) return false;
|
|
2309
|
-
return typeof file.path === "string" && typeof file.size_bytes === "number" && typeof file.content_type === "string" && typeof file.sha256 === "string";
|
|
2310
|
-
}) && typeof data.total_size_bytes === "number" && (data.project_id === void 0 || typeof data.project_id === "string" || data.project_id === null);
|
|
2311
|
-
}
|
|
2312
|
-
//#endregion
|
|
2313
2141
|
//#region src/api.ts
|
|
2314
2142
|
let insecureLocalhostDispatcher;
|
|
2315
2143
|
let undiciModule$1;
|
|
@@ -2327,8 +2155,17 @@ function requestConfig(options) {
|
|
|
2327
2155
|
return { init: { insecureLocalhost: true } };
|
|
2328
2156
|
}
|
|
2329
2157
|
async function cliFetch(input, init = {}) {
|
|
2330
|
-
const { insecureLocalhost, ...
|
|
2158
|
+
const { insecureLocalhost, ...requested } = init;
|
|
2331
2159
|
const { fetch, Agent } = await loadUndici();
|
|
2160
|
+
const given = requested.headers;
|
|
2161
|
+
const headers = {
|
|
2162
|
+
...Array.isArray(given) ? Object.fromEntries(given) : given && typeof given.entries === "function" ? Object.fromEntries(given.entries()) : given,
|
|
2163
|
+
[CLI_ARTIFACT_KINDS_HEADER]: "pdf, video"
|
|
2164
|
+
};
|
|
2165
|
+
const fetchInit = {
|
|
2166
|
+
...requested,
|
|
2167
|
+
headers
|
|
2168
|
+
};
|
|
2332
2169
|
const requestInit = insecureLocalhost ? {
|
|
2333
2170
|
...fetchInit,
|
|
2334
2171
|
dispatcher: insecureLocalhostDispatcher ??= new Agent({ connect: { rejectUnauthorized: false } })
|
|
@@ -3608,11 +3445,255 @@ async function resolveEffectiveDefaultProfile(projectInput = null) {
|
|
|
3608
3445
|
path: null
|
|
3609
3446
|
};
|
|
3610
3447
|
return {
|
|
3611
|
-
profile: null,
|
|
3612
|
-
source: "none",
|
|
3613
|
-
path: null
|
|
3448
|
+
profile: null,
|
|
3449
|
+
source: "none",
|
|
3450
|
+
path: null
|
|
3451
|
+
};
|
|
3452
|
+
}
|
|
3453
|
+
//#endregion
|
|
3454
|
+
//#region src/output.ts
|
|
3455
|
+
function outputModeFromArgv(argv) {
|
|
3456
|
+
return outputMode({ json: argv.includes("--json") });
|
|
3457
|
+
}
|
|
3458
|
+
function outputMode(options) {
|
|
3459
|
+
return { json: Boolean(options.json) || process.env.CI === "true" || !process.stdout.isTTY };
|
|
3460
|
+
}
|
|
3461
|
+
function writeSuccess(command, data, mode) {
|
|
3462
|
+
if (!mode.json && command === "share" && !shareSuccessFields(data)) return writeFailure(command, serviceError("Share succeeded but the response did not include an artifact id and URL."), mode, 1);
|
|
3463
|
+
const payload = {
|
|
3464
|
+
schema_version: 2,
|
|
3465
|
+
ok: true,
|
|
3466
|
+
command,
|
|
3467
|
+
data
|
|
3468
|
+
};
|
|
3469
|
+
if (mode.json) {
|
|
3470
|
+
process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
|
|
3471
|
+
return;
|
|
3472
|
+
}
|
|
3473
|
+
process.stdout.write(humanSuccess(command, data));
|
|
3474
|
+
}
|
|
3475
|
+
/** Emit a success envelope as a single line. `preview` keeps running after it
|
|
3476
|
+
* reports readiness, so a launcher cannot wait for EOF to parse the payload;
|
|
3477
|
+
* one line lets it read the envelope and move on. */
|
|
3478
|
+
function writeSuccessLine(command, data, mode) {
|
|
3479
|
+
const payload = {
|
|
3480
|
+
schema_version: 2,
|
|
3481
|
+
ok: true,
|
|
3482
|
+
command,
|
|
3483
|
+
data
|
|
3484
|
+
};
|
|
3485
|
+
if (mode.json) {
|
|
3486
|
+
process.stdout.write(`${JSON.stringify(payload)}\n`);
|
|
3487
|
+
return;
|
|
3488
|
+
}
|
|
3489
|
+
process.stdout.write(`${JSON.stringify(data)}\n`);
|
|
3490
|
+
}
|
|
3491
|
+
function dataWithSkillAutoUpdate(data, autoUpdate) {
|
|
3492
|
+
if (!autoUpdate || autoUpdate.targets.length === 0) return data;
|
|
3493
|
+
if (!isRecord$1(data)) return data;
|
|
3494
|
+
const existingSkills = isRecord$1(data.skills) ? data.skills : {};
|
|
3495
|
+
return {
|
|
3496
|
+
...data,
|
|
3497
|
+
skills: {
|
|
3498
|
+
...existingSkills,
|
|
3499
|
+
auto_update: autoUpdate
|
|
3500
|
+
}
|
|
3501
|
+
};
|
|
3502
|
+
}
|
|
3503
|
+
function writeFailure(command, error, mode, exitCode) {
|
|
3504
|
+
const payload = {
|
|
3505
|
+
schema_version: 2,
|
|
3506
|
+
ok: false,
|
|
3507
|
+
command,
|
|
3508
|
+
error
|
|
3509
|
+
};
|
|
3510
|
+
if (mode.json) process.stderr.write(`${JSON.stringify(payload, null, 2)}\n`);
|
|
3511
|
+
else {
|
|
3512
|
+
const upgradeRequest = isRecord$1(error.details?.upgrade_request) ? error.details.upgrade_request : null;
|
|
3513
|
+
const upgradeHint = upgradeRequest?.kind === "contact" && typeof upgradeRequest.request_message === "string" ? upgradeRequest.request_message : upgradeRequest?.kind === "billing" && typeof upgradeRequest.upgrade_url === "string" ? upgradeRequest.upgrade_url : upgradeRequest?.kind === "support" && typeof upgradeRequest.support_url === "string" ? upgradeRequest.support_url : null;
|
|
3514
|
+
process.stderr.write(`Error: ${error.message}\nWhy: ${error.why}\nHint: ${error.hint}${upgradeHint ? `\n${upgradeHint}` : ""}\n`);
|
|
3515
|
+
}
|
|
3516
|
+
process.exitCode = exitCode;
|
|
3517
|
+
}
|
|
3518
|
+
function writeText(text) {
|
|
3519
|
+
process.stdout.write(text);
|
|
3520
|
+
}
|
|
3521
|
+
function writeEvent(data) {
|
|
3522
|
+
process.stderr.write(`${JSON.stringify(data)}\n`);
|
|
3523
|
+
}
|
|
3524
|
+
function humanSuccess(command, data) {
|
|
3525
|
+
const suffix = skillAutoUpdateHumanOutput(data);
|
|
3526
|
+
if (command === "share") {
|
|
3527
|
+
const fields = shareSuccessFields(data);
|
|
3528
|
+
if (!fields) return `${JSON.stringify(data, null, 2)}\n`;
|
|
3529
|
+
const output = [
|
|
3530
|
+
"Shared",
|
|
3531
|
+
`Artifact ID: ${fields.artifactId}`,
|
|
3532
|
+
`URL: ${fields.url}`,
|
|
3533
|
+
`Destination: ${fields.destinationType}${fields.projectId ? ` (${fields.projectId})` : ""}`,
|
|
3534
|
+
`Visibility: ${fields.visibility}`,
|
|
3535
|
+
...fields.visibilityHint ? [`Note: ${fields.visibilityHint}`] : [],
|
|
3536
|
+
""
|
|
3537
|
+
].join("\n");
|
|
3538
|
+
const warnings = shareWarnings(data);
|
|
3539
|
+
const withWarnings = warnings.length ? `${output}${warnings.map((message) => `Warning: ${message}`).join("\n")}\n` : output;
|
|
3540
|
+
return suffix ? `${withWarnings}${suffix}` : withWarnings;
|
|
3541
|
+
}
|
|
3542
|
+
if (command === "download" && isRecord$1(data) && Array.isArray(data.backup_paths)) {
|
|
3543
|
+
const recovery = data.backup_paths.map((path) => `Original data retained at ${String(path)}; inspect it before manual cleanup.`).join("\n");
|
|
3544
|
+
return `${JSON.stringify(data, null, 2)}\n${recovery ? `${recovery}\n` : ""}`;
|
|
3545
|
+
}
|
|
3546
|
+
if (command === "doctor") return doctorHumanOutput(data);
|
|
3547
|
+
if (command === "open") return openHumanOutput(data);
|
|
3548
|
+
if (command === "init") return initHumanOutput(data);
|
|
3549
|
+
if (command === "artifacts list" && isRecord$1(data) && data.has_more === true && typeof data.next_cursor === "string") return `${JSON.stringify(data, null, 2)}\nContinue with --cursor ${data.next_cursor}\n`;
|
|
3550
|
+
if (command === "changelog") return changelogHumanOutput(data);
|
|
3551
|
+
if (command === "login" || command === "whoami") return credentialLifetimeHumanOutput(data);
|
|
3552
|
+
const output = `${JSON.stringify(data, null, 2)}\n`;
|
|
3553
|
+
return suffix ? `${output}${suffix}` : output;
|
|
3554
|
+
}
|
|
3555
|
+
function credentialLifetimeHumanOutput(data) {
|
|
3556
|
+
const body = `${JSON.stringify(data, null, 2)}`;
|
|
3557
|
+
if (!isRecord$1(data) || !isRecord$1(data.renewal)) return `${body}\n`;
|
|
3558
|
+
const lines = [body];
|
|
3559
|
+
if ("session_expires_at" in data) lines.push(`Session expires: ${typeof data.session_expires_at === "string" ? data.session_expires_at : "unknown"}`);
|
|
3560
|
+
if ("refresh_credential_expires_at" in data) lines.push(`Refresh credential expires: ${typeof data.refresh_credential_expires_at === "string" ? data.refresh_credential_expires_at : "unknown"}`);
|
|
3561
|
+
if (data.renewal.kind === "automatic") lines.push("Renewal: normal CLI use automatically renews an unauthorized session while the refresh credential remains valid.");
|
|
3562
|
+
return `${lines.join("\n")}\n`;
|
|
3563
|
+
}
|
|
3564
|
+
function shareWarnings(data) {
|
|
3565
|
+
if (!isRecord$1(data) || !Array.isArray(data.warnings)) return [];
|
|
3566
|
+
return data.warnings.flatMap((warning) => isRecord$1(warning) && warning.code === "slack_reauthorization_required" && typeof warning.message === "string" ? [warning.message] : []);
|
|
3567
|
+
}
|
|
3568
|
+
function skillAutoUpdateHumanOutput(data) {
|
|
3569
|
+
if (!isRecord$1(data)) return "";
|
|
3570
|
+
const skills = data.skills;
|
|
3571
|
+
if (!isRecord$1(skills)) return "";
|
|
3572
|
+
const autoUpdate = skills.auto_update;
|
|
3573
|
+
if (!isRecord$1(autoUpdate) || !Array.isArray(autoUpdate.targets)) return "";
|
|
3574
|
+
const lines = autoUpdate.targets.filter(isRecord$1).map((target) => {
|
|
3575
|
+
const label = Array.isArray(target.aliases) ? target.aliases.filter(isRecord$1).map((alias) => `${alias.tool}:${alias.scope}`).join(", ") : typeof target.tool === "string" && typeof target.scope === "string" ? `${target.tool}:${target.scope}` : "unknown";
|
|
3576
|
+
if (target.action === "update_recommended") {
|
|
3577
|
+
const advice = [target.update_command, target.hint].filter((value) => typeof value === "string").join("; ");
|
|
3578
|
+
return `Skill update recommended: ${label}${advice ? ` (${advice})` : ""}`;
|
|
3579
|
+
}
|
|
3580
|
+
return `Skill updated: ${label}`;
|
|
3581
|
+
});
|
|
3582
|
+
return lines.length > 0 ? `${lines.join("\n")}\n` : "";
|
|
3583
|
+
}
|
|
3584
|
+
function initHumanOutput(data) {
|
|
3585
|
+
const body = `${JSON.stringify(data, null, 2)}`;
|
|
3586
|
+
const nextCommand = initNextCommand(data);
|
|
3587
|
+
if (!nextCommand) return `${body}\n`;
|
|
3588
|
+
return `${body}\nNext command: ${nextCommand}\n`;
|
|
3589
|
+
}
|
|
3590
|
+
function initNextCommand(data) {
|
|
3591
|
+
if (!isRecord$1(data) || data.mode !== "onboarding") return null;
|
|
3592
|
+
const steps = data.next_steps;
|
|
3593
|
+
if (!Array.isArray(steps)) return null;
|
|
3594
|
+
const pending = steps.find((step) => isRecord$1(step) && step.done !== true && typeof step.command === "string");
|
|
3595
|
+
return isRecord$1(pending) && typeof pending.command === "string" ? pending.command : null;
|
|
3596
|
+
}
|
|
3597
|
+
function openHumanOutput(data) {
|
|
3598
|
+
const body = `${JSON.stringify(data, null, 2)}`;
|
|
3599
|
+
const nextCommand = openNextCommand(data);
|
|
3600
|
+
if (!nextCommand) return `${body}\n`;
|
|
3601
|
+
return `${body}\nNext command: ${nextCommand}\n`;
|
|
3602
|
+
}
|
|
3603
|
+
function openNextCommand(data) {
|
|
3604
|
+
if (!isOpenData(data)) return null;
|
|
3605
|
+
return data.open.kind === "download_required" ? data.open.next_command : null;
|
|
3606
|
+
}
|
|
3607
|
+
function isOpenData(data) {
|
|
3608
|
+
if (!isRecord$1(data)) return false;
|
|
3609
|
+
const open = data.open;
|
|
3610
|
+
if (!isRecord$1(open)) return false;
|
|
3611
|
+
if (open.kind === "read") return true;
|
|
3612
|
+
return open.kind === "download_required" && typeof open.next_command === "string";
|
|
3613
|
+
}
|
|
3614
|
+
function doctorHumanOutput(data) {
|
|
3615
|
+
const nextCommand = doctorNextCommand(data);
|
|
3616
|
+
const body = `${JSON.stringify(data, null, 2)}`;
|
|
3617
|
+
if (!nextCommand) return `${body}\n`;
|
|
3618
|
+
return `${body}\n${nextCommand}\n`;
|
|
3619
|
+
}
|
|
3620
|
+
function doctorNextCommand(data) {
|
|
3621
|
+
if (!isRecord$1(data) || !("next_command" in data)) return null;
|
|
3622
|
+
return typeof data.next_command === "string" ? data.next_command : null;
|
|
3623
|
+
}
|
|
3624
|
+
function changelogHumanOutput(data) {
|
|
3625
|
+
if (!isRecord$1(data)) return `${JSON.stringify(data, null, 2)}\n`;
|
|
3626
|
+
const version = typeof data.version === "string" ? data.version : "";
|
|
3627
|
+
const updatesUrl = typeof data.updates_url === "string" ? data.updates_url : "";
|
|
3628
|
+
const lines = [
|
|
3629
|
+
`Artifact Share CLI ${version}`,
|
|
3630
|
+
"",
|
|
3631
|
+
`Updates: ${updatesUrl}`
|
|
3632
|
+
];
|
|
3633
|
+
const latest = data.latest;
|
|
3634
|
+
if (isRecord$1(latest) && typeof latest.body === "string" && latest.body) {
|
|
3635
|
+
const latestVersion = typeof latest.version === "string" ? latest.version : version;
|
|
3636
|
+
const latestDate = typeof latest.date === "string" ? latest.date : "";
|
|
3637
|
+
lines.push("", `Changes in ${latestVersion} (${latestDate}):`, latest.body);
|
|
3638
|
+
}
|
|
3639
|
+
return `${lines.join("\n")}\n`;
|
|
3640
|
+
}
|
|
3641
|
+
function shareSuccessFields(data) {
|
|
3642
|
+
if (!isRecord$1(data)) return null;
|
|
3643
|
+
const artifact = data.artifact;
|
|
3644
|
+
const destination = data.destination;
|
|
3645
|
+
const share = data.share;
|
|
3646
|
+
if (!isRecord$1(artifact) || !isRecord$1(destination) || !isRecord$1(share)) return null;
|
|
3647
|
+
if (typeof artifact.id !== "string" || typeof artifact.url !== "string" || typeof destination.type !== "string" || typeof share.visibility !== "string") return null;
|
|
3648
|
+
return {
|
|
3649
|
+
artifactId: artifact.id,
|
|
3650
|
+
url: artifact.url,
|
|
3651
|
+
destinationType: destination.type,
|
|
3652
|
+
visibilityHint: typeof share.visibility_hint === "string" ? share.visibility_hint : null,
|
|
3653
|
+
projectId: typeof destination.project_id === "string" ? destination.project_id : null,
|
|
3654
|
+
visibility: share.visibility
|
|
3655
|
+
};
|
|
3656
|
+
}
|
|
3657
|
+
function updateSuccessFields(data) {
|
|
3658
|
+
if (!isRecord$1(data)) return null;
|
|
3659
|
+
const artifact = data.artifact;
|
|
3660
|
+
const version = data.version;
|
|
3661
|
+
if (!isRecord$1(artifact) || !isRecord$1(version)) return null;
|
|
3662
|
+
if (typeof artifact.id !== "string" || typeof artifact.url !== "string" || typeof version.id !== "string") return null;
|
|
3663
|
+
return {
|
|
3664
|
+
artifactId: artifact.id,
|
|
3665
|
+
url: artifact.url,
|
|
3666
|
+
versionId: version.id
|
|
3614
3667
|
};
|
|
3615
3668
|
}
|
|
3669
|
+
function resolveSuccessFields(data) {
|
|
3670
|
+
return isContract(RESOLVE_RESPONSE_SCHEMA, data);
|
|
3671
|
+
}
|
|
3672
|
+
function artifactGetSuccessFields(data) {
|
|
3673
|
+
return isContract(ArtifactGetResponseSchema, data) || artifactSourceSuccessFields(data);
|
|
3674
|
+
}
|
|
3675
|
+
function artifactVersionsSuccessFields(data) {
|
|
3676
|
+
return isContract(ArtifactVersionsResponseSchema, data);
|
|
3677
|
+
}
|
|
3678
|
+
function artifactSourceSuccessFields(data) {
|
|
3679
|
+
if (isContract(ARTIFACT_READ_RESPONSE_SCHEMA, data)) return true;
|
|
3680
|
+
if (!isRecord$1(data)) return false;
|
|
3681
|
+
return typeof data.id === "string" && typeof data.share_url === "string" && typeof data.version_id === "string" && (data.format === "html" || data.format === "markdown") && typeof data.content === "string" && typeof data.size_bytes === "number" && typeof data.truncated === "boolean" && (typeof data.next_offset === "number" || data.next_offset === null) && (data.link_expires_at === void 0 || typeof data.link_expires_at === "string" || data.link_expires_at === null);
|
|
3682
|
+
}
|
|
3683
|
+
function artifactsListSuccessFields(data) {
|
|
3684
|
+
return isContract(ARTIFACTS_LIST_RESPONSE_SCHEMA, data);
|
|
3685
|
+
}
|
|
3686
|
+
function deleteSuccessFields(data) {
|
|
3687
|
+
return isContract(ARTIFACT_DELETE_RESPONSE_SCHEMA, data);
|
|
3688
|
+
}
|
|
3689
|
+
function downloadManifestFields(data) {
|
|
3690
|
+
if (isContract(DOWNLOAD_MANIFEST_RESPONSE_SCHEMA, data)) return true;
|
|
3691
|
+
if (!isRecord$1(data)) return false;
|
|
3692
|
+
return typeof data.id === "string" && typeof data.share_url === "string" && typeof data.version_id === "string" && typeof data.artifact_kind === "string" && Array.isArray(data.files) && data.files.every((file) => {
|
|
3693
|
+
if (!isRecord$1(file)) return false;
|
|
3694
|
+
return typeof file.path === "string" && typeof file.size_bytes === "number" && typeof file.content_type === "string" && typeof file.sha256 === "string";
|
|
3695
|
+
}) && typeof data.total_size_bytes === "number" && (data.project_id === void 0 || typeof data.project_id === "string" || data.project_id === null);
|
|
3696
|
+
}
|
|
3616
3697
|
//#endregion
|
|
3617
3698
|
//#region src/command-runners/login.ts
|
|
3618
3699
|
async function performDeviceLogin(profile, options, mode, loginInput = {}) {
|
|
@@ -4179,6 +4260,45 @@ async function handleJsonPendingAuth(command, credential, options, mode, rerun)
|
|
|
4179
4260
|
return writeFailure(command, authRequiredWithDeviceAuthError(baseUrl, pending, extraDetails), mode, 1);
|
|
4180
4261
|
}
|
|
4181
4262
|
//#endregion
|
|
4263
|
+
//#region src/command-runners/artifacts-versions.ts
|
|
4264
|
+
async function runArtifactsVersions(parsed, mode, isRetry = false) {
|
|
4265
|
+
const command = "artifacts versions";
|
|
4266
|
+
const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL to list versions.");
|
|
4267
|
+
if (target.error) return writeFailure(command, target.error, mode, 1);
|
|
4268
|
+
const cursor = parsed.options.cursor?.trim();
|
|
4269
|
+
if (parsed.options.cursor !== void 0 && !cursor) return writeFailure(command, validationError("--cursor must not be empty.", "Restart without --cursor."), mode, 1);
|
|
4270
|
+
const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
|
|
4271
|
+
if (!credential.ok) {
|
|
4272
|
+
if (!mode.json) return writeFailure(command, credential.error, mode, 1);
|
|
4273
|
+
return handleCredentialFailure(command, credential, parsed.options, mode, () => runArtifactsVersions(parsed, mode, true), isRetry);
|
|
4274
|
+
}
|
|
4275
|
+
const request = await requestConfig(parsed.options);
|
|
4276
|
+
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
4277
|
+
const url = apiUrl(`/api/cli/artifacts/${encodeURIComponent(target.artifactId)}/versions`, baseUrlOf(parsed.options));
|
|
4278
|
+
if (cursor) url.searchParams.set("cursor", cursor);
|
|
4279
|
+
const result = await runAuthenticatedApi(credential, parsed.options, async (current) => {
|
|
4280
|
+
const response = await cliFetch(url, {
|
|
4281
|
+
headers: { Authorization: `Bearer ${current.token}` },
|
|
4282
|
+
...request.init
|
|
4283
|
+
});
|
|
4284
|
+
if ("networkError" in response) return { error: networkError(response.networkError) };
|
|
4285
|
+
const body = await readJson(response);
|
|
4286
|
+
if (!response.ok) return { error: mapApiError(response.status, body, {
|
|
4287
|
+
authenticated: true,
|
|
4288
|
+
artifactTarget: true,
|
|
4289
|
+
baseUrl: baseUrlOf(parsed.options),
|
|
4290
|
+
credentialSource: current.source,
|
|
4291
|
+
profile: current.profile,
|
|
4292
|
+
profileCredentialKind: current.profileCredentialKind,
|
|
4293
|
+
botProfile: current.botProfile
|
|
4294
|
+
}) };
|
|
4295
|
+
if (!artifactVersionsSuccessFields(body)) return { error: serviceError("Versions response did not include history metadata.") };
|
|
4296
|
+
return { data: body };
|
|
4297
|
+
});
|
|
4298
|
+
if (result.error) return handleAuthenticatedCredentialFailure(command, result.error, credential, parsed.options, mode, () => runArtifactsVersions(parsed, mode, true), isRetry);
|
|
4299
|
+
return writeSuccess(command, result.data, mode);
|
|
4300
|
+
}
|
|
4301
|
+
//#endregion
|
|
4182
4302
|
//#region src/command-runners/artifacts-get.ts
|
|
4183
4303
|
async function runArtifactsGet(parsed, mode, isRetry = false) {
|
|
4184
4304
|
const command = "artifacts get";
|
|
@@ -4218,7 +4338,10 @@ async function fetchArtifact(parsed, target, credential) {
|
|
|
4218
4338
|
if (target.offset !== void 0) url.searchParams.set("offset", target.offset);
|
|
4219
4339
|
for (const item of target.include) url.searchParams.append("include", item);
|
|
4220
4340
|
const response = await cliFetch(url, {
|
|
4221
|
-
headers: {
|
|
4341
|
+
headers: {
|
|
4342
|
+
Authorization: `Bearer ${credential.token}`,
|
|
4343
|
+
...parsed.command === "artifacts get" ? { [CLI_STATIC_METADATA_HEADER]: "1" } : {}
|
|
4344
|
+
},
|
|
4222
4345
|
...request.init
|
|
4223
4346
|
});
|
|
4224
4347
|
if ("networkError" in response) return { error: networkError(response.networkError) };
|
|
@@ -5811,6 +5934,13 @@ async function runOpen(parsed, mode, isRetry = false) {
|
|
|
5811
5934
|
if (result.error.code === "auth_required") return handleAuthenticatedCredentialFailure(command, result.error, credential, parsed.options, mode, () => runOpen(parsed, mode, true), isRetry);
|
|
5812
5935
|
return writeFailure(command, result.error, mode, 1);
|
|
5813
5936
|
}
|
|
5937
|
+
if (!("content" in result.data)) return writeSuccess(command, {
|
|
5938
|
+
skills,
|
|
5939
|
+
open: {
|
|
5940
|
+
kind: "download_required",
|
|
5941
|
+
next_command: agentDownloadCommand(target.artifactId)
|
|
5942
|
+
}
|
|
5943
|
+
}, mode);
|
|
5814
5944
|
return writeSuccess(command, {
|
|
5815
5945
|
skills,
|
|
5816
5946
|
open: {
|
|
@@ -6040,7 +6170,12 @@ function createPreviewStore(annotationsPath) {
|
|
|
6040
6170
|
summary: null
|
|
6041
6171
|
};
|
|
6042
6172
|
annotations.push(annotation);
|
|
6043
|
-
|
|
6173
|
+
try {
|
|
6174
|
+
save();
|
|
6175
|
+
} catch (error) {
|
|
6176
|
+
annotations.pop();
|
|
6177
|
+
throw error;
|
|
6178
|
+
}
|
|
6044
6179
|
return annotation;
|
|
6045
6180
|
},
|
|
6046
6181
|
deleteDraft(thread) {
|
|
@@ -6561,6 +6696,7 @@ async function postShareUpload(args, baseUrl, fallbackKind) {
|
|
|
6561
6696
|
//#region src/preview/messages.generated.ts
|
|
6562
6697
|
const PREVIEW_MESSAGES = {
|
|
6563
6698
|
en: {
|
|
6699
|
+
"preview.annotationSaveFailed": "Could not save the comment. Your comment is still here. Try again.",
|
|
6564
6700
|
"preview.isolationNotice": "Preview runs scripts in an isolated frame. localStorage, IndexedDB and other same-origin features are unavailable. Preview isolation cannot be disabled.",
|
|
6565
6701
|
"preview.localBadge": "Local preview",
|
|
6566
6702
|
"preview.watching": "Watching for changes",
|
|
@@ -6651,6 +6787,7 @@ const PREVIEW_MESSAGES = {
|
|
|
6651
6787
|
"preview.shareDialog.snapshotFailed": "The file could not be read, so sharing is disabled. Reopen this dialog once it is available."
|
|
6652
6788
|
},
|
|
6653
6789
|
ja: {
|
|
6790
|
+
"preview.annotationSaveFailed": "コメントを保存できませんでした。入力内容は残っています。もう一度お試しください。",
|
|
6654
6791
|
"preview.isolationNotice": "プレビューのスクリプトは隔離されたフレームで実行されます。localStorage、IndexedDB など、同一オリジンを必要とする機能は使えません。この隔離は解除できません。",
|
|
6655
6792
|
"preview.localBadge": "ローカルプレビュー",
|
|
6656
6793
|
"preview.watching": "変更を監視中",
|
|
@@ -7178,7 +7315,7 @@ function renderPage(options) {
|
|
|
7178
7315
|
--muted-foreground: rgba(55,53,47,0.86); --faint: rgba(55,53,47,0.45);
|
|
7179
7316
|
--border: rgba(55,53,47,0.1); --border-strong: rgba(55,53,47,0.22);
|
|
7180
7317
|
--accent: rgba(55,53,47,0.04); --link: #116bb1; --primary: #1766ad;
|
|
7181
|
-
--card: #ffffff; --r-md: 6px; --r-lg: 8px;
|
|
7318
|
+
--badge-on-link: #ffffff; --card: #ffffff; --r-md: 6px; --r-lg: 8px;
|
|
7182
7319
|
--shadow-lg: rgba(15,15,15,0.05) 0 0 0 1px, rgba(15,15,15,0.1) 0 8px 24px;
|
|
7183
7320
|
}
|
|
7184
7321
|
@media (prefers-color-scheme: dark) {
|
|
@@ -7187,7 +7324,7 @@ function renderPage(options) {
|
|
|
7187
7324
|
--muted-foreground: rgba(231,226,216,0.77); --faint: rgba(231,226,216,0.4);
|
|
7188
7325
|
--border: rgba(231,226,216,0.13); --border-strong: rgba(231,226,216,0.28);
|
|
7189
7326
|
--accent: rgba(231,226,216,0.07); --link: #7db7ff; --primary: #7db7ff;
|
|
7190
|
-
--card: #191c1f;
|
|
7327
|
+
--badge-on-link: #111315; --card: #191c1f;
|
|
7191
7328
|
--shadow-lg: rgba(0,0,0,0.4) 0 0 0 1px, rgba(0,0,0,0.5) 0 8px 24px;
|
|
7192
7329
|
}
|
|
7193
7330
|
}
|
|
@@ -7212,7 +7349,9 @@ function renderPage(options) {
|
|
|
7212
7349
|
border-radius: var(--r-md); background: var(--background); color: var(--foreground);
|
|
7213
7350
|
padding: 5px 12px; }
|
|
7214
7351
|
.btn:hover { background: var(--accent); }
|
|
7215
|
-
.btn-primary { background: var(--primary); border-color: var(--primary); color:
|
|
7352
|
+
.btn-primary { background: var(--primary); border-color: var(--primary); color: var(--badge-on-link); }
|
|
7353
|
+
.btn-primary:not(:disabled):hover, .btn-primary:not(:disabled):focus { background: var(--primary); }
|
|
7354
|
+
.btn-primary:disabled:hover { background: var(--primary); }
|
|
7216
7355
|
.btn[disabled] { opacity: 0.5; cursor: default; }
|
|
7217
7356
|
.url-box { display: flex; gap: 8px; margin-bottom: 12px; }
|
|
7218
7357
|
.url-box input { flex: 1; font: inherit; font-size: 13px; padding: 6px 8px;
|
|
@@ -7329,9 +7468,20 @@ function renderPage(options) {
|
|
|
7329
7468
|
el('shareBtn').disabled = true;
|
|
7330
7469
|
}
|
|
7331
7470
|
|
|
7332
|
-
|
|
7471
|
+
var snapshotPending = false;
|
|
7472
|
+
function refreshSnapshot() {
|
|
7473
|
+
if (snapshotPending || shareInFlight || el('dialog').className !== 'dialog') return;
|
|
7474
|
+
snapshotPending = true;
|
|
7475
|
+
snapshotFailed = false;
|
|
7476
|
+
snapshotId = null;
|
|
7477
|
+
if (el('shareError').textContent === t('snapshotFailed') ||
|
|
7478
|
+
el('shareError').textContent === t('visibilityUnknown')) {
|
|
7479
|
+
el('shareError').style.display = 'none';
|
|
7480
|
+
}
|
|
7481
|
+
syncVisibility();
|
|
7482
|
+
post('/api/snapshot')
|
|
7333
7483
|
.then(function (result) {
|
|
7334
|
-
if (!result.ok) {
|
|
7484
|
+
if (!result.ok || typeof result.body.snapshot_id !== 'string') {
|
|
7335
7485
|
reportSnapshotFailure();
|
|
7336
7486
|
return;
|
|
7337
7487
|
}
|
|
@@ -7340,7 +7490,16 @@ function renderPage(options) {
|
|
|
7340
7490
|
el('snapshotNote').textContent =
|
|
7341
7491
|
t('snapshotNote').replace('{time}', takenAt.toLocaleTimeString());
|
|
7342
7492
|
})
|
|
7343
|
-
.catch(reportSnapshotFailure)
|
|
7493
|
+
.catch(reportSnapshotFailure)
|
|
7494
|
+
.finally(function () { snapshotPending = false; syncVisibility(); });
|
|
7495
|
+
}
|
|
7496
|
+
window.addEventListener('message', function (event) {
|
|
7497
|
+
if (event.source !== window.opener || event.origin !== bootstrap.artifactOrigin) return;
|
|
7498
|
+
var data = event.data;
|
|
7499
|
+
if (!data || Object.keys(data).length !== 2 || data.source !== 'artifactshare-preview' || data.kind !== 'refresh-snapshot') return;
|
|
7500
|
+
refreshSnapshot();
|
|
7501
|
+
});
|
|
7502
|
+
refreshSnapshot();
|
|
7344
7503
|
|
|
7345
7504
|
function loadContext() {
|
|
7346
7505
|
return fetch('/api/context')
|
|
@@ -7383,7 +7542,7 @@ function renderPage(options) {
|
|
|
7383
7542
|
// A project destination carries its own audience, so an unresolved home
|
|
7384
7543
|
// default only blocks home shares.
|
|
7385
7544
|
var audienceUnknown = !projectSelected && !context.default_visibility;
|
|
7386
|
-
el('shareBtn').disabled = audienceUnknown || shareInFlight || snapshotFailed;
|
|
7545
|
+
el('shareBtn').disabled = audienceUnknown || shareInFlight || snapshotFailed || snapshotPending || !snapshotId;
|
|
7387
7546
|
if (snapshotFailed) {
|
|
7388
7547
|
// Nothing about the destination can make an unreadable file shareable.
|
|
7389
7548
|
el('shareError').textContent = t('snapshotFailed');
|
|
@@ -7415,7 +7574,7 @@ function renderPage(options) {
|
|
|
7415
7574
|
el('visibility').addEventListener('change', syncVisibility);
|
|
7416
7575
|
|
|
7417
7576
|
function share() {
|
|
7418
|
-
if (!snapshotId || shareInFlight) return;
|
|
7577
|
+
if (!snapshotId || shareInFlight || snapshotPending || el('dialog').className !== 'dialog') return;
|
|
7419
7578
|
shareInFlight = true;
|
|
7420
7579
|
el('shareBtn').disabled = true;
|
|
7421
7580
|
el('shareError').style.display = 'none';
|
|
@@ -7598,7 +7757,7 @@ function pickShareMessages(locale) {
|
|
|
7598
7757
|
}
|
|
7599
7758
|
//#endregion
|
|
7600
7759
|
//#region ../viewer-kit/src/reporter.generated.ts
|
|
7601
|
-
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, strings = {\n stringReplace: (value, pattern, replacement) => value.replace(pattern, replacement),\n stringTrim: (value) => value.trim(),\n stringSlice: (value, start, end) => value.slice(start, end),\n createRange: (document) => document.createRange(),\n rangeSetStart: (range, node, offset) => range.setStart(node, offset),\n rangeSetEnd: (range, node, offset) => range.setEnd(node, offset),\n rangeCollapse: (range, toStart) => range.collapse(toStart),\n rangeComparePoint: (range, node, offset) => range.comparePoint(node, offset)\n }) {\n const document = root.ownerDocument;\n const units = [];\n let text = \"\";\n let previousBlock = null;\n const blockTagNames = \"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\";\n const blockTags = new Set();\n let blockTag = \"\";\n for (let i = 0; i <= blockTagNames.length; i++) {\n if (i === blockTagNames.length || blockTagNames[i] === \" \") {\n blockTags.add(blockTag);\n blockTag = \"\";\n } else blockTag += blockTagNames[i];\n }\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 = strings.createRange(document);\n strings.rangeSetStart(range, segment.node, segment.start);\n strings.rangeSetEnd(range, 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 = strings.createRange(document);\n strings.rangeSetStart(point, boundaryNode, offset);\n strings.rangeCollapse(point, 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 = strings.rangeComparePoint(point, 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: strings.stringSlice(text, start, end)\n };\n }\n function locus(range) {\n const mapped = mappedSlice(range);\n if (!mapped) return undefined;\n const path = [];\n const startPoint = strings.createRange(document);\n strings.rangeSetStart(startPoint, range.startContainer, range.startOffset);\n const candidates = root.querySelectorAll(\"h1,h2,h3,h4,h5,h6\");\n for (let i = 0; i < candidates.length; i++) {\n const heading = candidates[i];\n if (strings.rangeComparePoint(startPoint, heading, 0) > 0) break;\n if (heading.namespaceURI !== \"http://www.w3.org/1999/xhtml\" || heading.closest(TEXT_ANCHOR_EXCLUDED_SELECTOR)) continue;\n const rank = Number(heading.localName[1]);\n while (path.length && path[path.length - 1].rank >= rank) path.length--;\n path[path.length] = {\n rank,\n element: heading\n };\n }\n const headings = [];\n for (let i = 0; i < path.length; i++) {\n headings[i] = strings.stringSlice(strings.stringTrim(strings.stringReplace(path[i].element.textContent || \"\", /\\s+/g, \" \")), 0, 120);\n }\n let block = range.commonAncestorContainer.nodeType === 1 ? range.commonAncestorContainer : range.commonAncestorContainer.parentElement;\n while (block && block !== root && !blockTags.has(block.localName)) block = block.parentElement;\n block = block || root;\n const nodes = document.createTreeWalker(block, 4);\n let first;\n let last;\n let blockNode;\n while (blockNode = nodes.nextNode()) {\n const offsets = sourceIndexes.get(blockNode);\n if (!offsets) continue;\n let start;\n for (let i = 0; i < offsets.length; i++) {\n if (offsets[i] !== undefined) {\n start = offsets[i];\n break;\n }\n }\n if (start === undefined) continue;\n first ??= start;\n last = offsets[offsets.length - 1] + 1;\n }\n if (first === undefined || last === undefined) return undefined;\n const start = Math.max(first, Math.min(Math.floor((mapped.textStart + mapped.textEnd) / 2) - 300, last - 600));\n return {\n headings,\n block_text: strings.stringSlice(text, start, Math.min(last, start + 600))\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 = strings.stringSlice(text, Math.max(0, start - size), start);\n suffix = strings.stringSlice(text, 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 locus,\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 badgeScale(ctx, badge, base) {\n let style = ctx.win.getComputedStyle(badge);\n let width = parseFloat(style.width);\n let height = parseFloat(style.height);\n if (style.boxSizing !== \"border-box\") {\n width += parseFloat(style.paddingLeft) + parseFloat(style.paddingRight) + parseFloat(style.borderLeftWidth) + parseFloat(style.borderRightWidth);\n height += parseFloat(style.paddingTop) + parseFloat(style.paddingBottom) + parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth);\n }\n let scaleX = width && isFinite(width) ? base.width / width : 1;\n let scaleY = height && isFinite(height) ? base.height / height : 1;\n if (!scaleX || !isFinite(scaleX)) scaleX = 1;\n if (!scaleY || !isFinite(scaleY)) scaleY = 1;\n return {\n scaleX,\n scaleY\n };\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, scaleY } = badgeScale(ctx, badge, base);\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, scaleY } = badgeScale(ctx, badge, base);\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), ctx.primordials);\n let selector = engine.describe(range);\n if (!selector) {\n send(ctx, { kind: \"text-selection-cleared\" });\n return;\n }\n let locus;\n try {\n locus = engine.locus(range);\n } catch {}\n let rect = range.getBoundingClientRect();\n send(ctx, {\n kind: \"text-selection\",\n locus,\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 if (key === \"locus\" && message[key] === undefined) continue;\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 createRange = win.Function.prototype.call.bind(win.Document.prototype.createRange);\n const rangeSetStart = win.Function.prototype.call.bind(win.Range.prototype.setStart);\n const rangeSetEnd = win.Function.prototype.call.bind(win.Range.prototype.setEnd);\n const rangeCollapse = win.Function.prototype.call.bind(win.Range.prototype.collapse);\n const rangeComparePoint = win.Function.prototype.call.bind(win.Range.prototype.comparePoint);\n const stringReplace = win.Function.prototype.call.bind(win.String.prototype.replace);\n const stringTrim = win.Function.prototype.call.bind(win.String.prototype.trim);\n const stringSlice = win.Function.prototype.call.bind(win.String.prototype.slice);\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 createRange,\n rangeSetStart,\n rangeSetEnd,\n rangeCollapse,\n rangeComparePoint,\n arrayMap,\n stringReplace,\n stringTrim,\n stringSlice,\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})();";
|
|
7760
|
+
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 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\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, strings = {\n stringReplace: (value, pattern, replacement) => value.replace(pattern, replacement),\n stringTrim: (value) => value.trim(),\n stringSlice: (value, start, end) => value.slice(start, end),\n createRange: (document) => document.createRange(),\n rangeSetStart: (range, node, offset) => range.setStart(node, offset),\n rangeSetEnd: (range, node, offset) => range.setEnd(node, offset),\n rangeCollapse: (range, toStart) => range.collapse(toStart),\n rangeComparePoint: (range, node, offset) => range.comparePoint(node, offset)\n }) {\n const document = root.ownerDocument;\n const units = [];\n let text = \"\";\n let previousBlock = null;\n const blockTagNames = \"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\";\n const blockTags = new Set();\n let blockTag = \"\";\n for (let i = 0; i <= blockTagNames.length; i++) {\n if (i === blockTagNames.length || blockTagNames[i] === \" \") {\n blockTags.add(blockTag);\n blockTag = \"\";\n } else blockTag += blockTagNames[i];\n }\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 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 = strings.createRange(document);\n strings.rangeSetStart(range, segment.node, segment.start);\n strings.rangeSetEnd(range, 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 = strings.createRange(document);\n strings.rangeSetStart(point, boundaryNode, offset);\n strings.rangeCollapse(point, 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 = strings.rangeComparePoint(point, 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: strings.stringSlice(text, start, end)\n };\n }\n function locus(range) {\n const mapped = mappedSlice(range);\n if (!mapped) return undefined;\n const path = [];\n const startPoint = strings.createRange(document);\n strings.rangeSetStart(startPoint, range.startContainer, range.startOffset);\n const candidates = root.querySelectorAll(\"h1,h2,h3,h4,h5,h6\");\n for (let i = 0; i < candidates.length; i++) {\n const heading = candidates[i];\n if (strings.rangeComparePoint(startPoint, heading, 0) > 0) break;\n if (heading.namespaceURI !== \"http://www.w3.org/1999/xhtml\" || heading.closest(TEXT_ANCHOR_EXCLUDED_SELECTOR)) continue;\n const rank = Number(heading.localName[1]);\n while (path.length && path[path.length - 1].rank >= rank) path.length--;\n path[path.length] = {\n rank,\n element: heading\n };\n }\n const headings = [];\n for (let i = 0; i < path.length; i++) {\n headings[i] = strings.stringSlice(strings.stringTrim(strings.stringReplace(path[i].element.textContent || \"\", /\\s+/g, \" \")), 0, 120);\n }\n let block = range.commonAncestorContainer.nodeType === 1 ? range.commonAncestorContainer : range.commonAncestorContainer.parentElement;\n while (block && block !== root && !blockTags.has(block.localName)) block = block.parentElement;\n block = block || root;\n const nodes = document.createTreeWalker(block, 4);\n let first;\n let last;\n let blockNode;\n while (blockNode = nodes.nextNode()) {\n const offsets = sourceIndexes.get(blockNode);\n if (!offsets) continue;\n let start;\n for (let i = 0; i < offsets.length; i++) {\n if (offsets[i] !== undefined) {\n start = offsets[i];\n break;\n }\n }\n if (start === undefined) continue;\n first ??= start;\n last = offsets[offsets.length - 1] + 1;\n }\n if (first === undefined || last === undefined) return undefined;\n const start = Math.max(first, Math.min(Math.floor((mapped.textStart + mapped.textEnd) / 2) - 300, last - 600));\n return {\n headings,\n block_text: strings.stringSlice(text, start, Math.min(last, start + 600))\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 = strings.stringSlice(text, Math.max(0, start - size), start);\n suffix = strings.stringSlice(text, 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 locus,\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 badgeScale(ctx, badge, base) {\n let style = ctx.win.getComputedStyle(badge);\n let width = parseFloat(style.width);\n let height = parseFloat(style.height);\n if (style.boxSizing !== \"border-box\") {\n width += parseFloat(style.paddingLeft) + parseFloat(style.paddingRight) + parseFloat(style.borderLeftWidth) + parseFloat(style.borderRightWidth);\n height += parseFloat(style.paddingTop) + parseFloat(style.paddingBottom) + parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth);\n }\n let scaleX = width && isFinite(width) ? base.width / width : 1;\n let scaleY = height && isFinite(height) ? base.height / height : 1;\n if (!scaleX || !isFinite(scaleX)) scaleX = 1;\n if (!scaleY || !isFinite(scaleY)) scaleY = 1;\n return {\n scaleX,\n scaleY\n };\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, scaleY } = badgeScale(ctx, badge, base);\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, scaleY } = badgeScale(ctx, badge, base);\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), ctx.primordials);\n let selector = engine.describe(range);\n if (!selector) {\n send(ctx, { kind: \"text-selection-cleared\" });\n return;\n }\n let locus;\n try {\n locus = engine.locus(range);\n } catch {}\n let targetPath = ctx.locationScoped ? liveCommentLocation(ctx) : undefined;\n if (ctx.locationScoped && !targetPath) {\n send(ctx, { kind: \"text-selection-cleared\" });\n return;\n }\n let rect = range.getBoundingClientRect();\n send(ctx, {\n kind: \"text-selection\",\n targetPath,\n locus,\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) + (text.length > 25 ? \"\\u2026\" : \"\"));\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.ownTextHash === undefined && !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 const text = ownText(ctx, peers[i]);\n if (anchor.ownTextHash !== undefined ? text.length > 16e3 && textHash(text) === anchor.ownTextHash : text === 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 ...elementTextIdentity(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 /** Keep normal captures byte-compatible; only oversized text needs hashing. */\n function elementTextIdentity(text) {\n return text.length <= 16e3 ? { ownText: text } : {\n ownTextHash: textHash(text),\n ownTextExcerpt: text.slice(0, 16e3)\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 if (ctx.locationScoped && ctx.displayedPath !== liveCommentLocation(ctx)) list = [];\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 completePendingScroll(ctx);\n }\n function completePendingScroll(ctx) {\n let id = ctx.pendingScrollThreadId;\n if (!id) return;\n let targeted = ctx.pendingHighlights.some(function(highlight) {\n return highlight.threadId === id && highlight.target;\n });\n if (!targeted) {\n ctx.pendingScrollThreadId = null;\n return;\n }\n if (ctx.paintedAnchors.some(function(entry) {\n return entry.highlight.threadId === id;\n })) scrollToThread(ctx, id);\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 ctx.pendingScrollThreadId = painted && painted.ranges.length ? null : id;\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\") continue;\n if (result.svg === \"\") {\n pre.classList.add(\"mermaid-error\");\n delete ctx.mermaidBlocks[result.id];\n continue;\n }\n if (!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.tabIndex = 0;\n container.setAttribute(\"role\", \"region\");\n container.setAttribute(\"aria-label\", \"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 if ((key === \"locus\" || key === \"targetPath\") && message[key] === undefined) continue;\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 ctx.locationScoped = data.locationScoped === true;\n ctx.fallbackToIndex = data.fallbackToIndex === true;\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 ctx.locationScoped = data.locationScoped === true;\n ctx.fallbackToIndex = data.fallbackToIndex === true;\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 const MAX_COMMENT_LOCATION_LENGTH = 1e3;\n function hasControlCharacter(value) {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index);\n if (code <= 31 || code === 127) return true;\n }\n return false;\n }\n /** A decoded pathname in the form delivery serves, or null when unservable. */\n function canonicalCommentPathname(decoded, fallbackToIndex = false) {\n if (typeof decoded !== \"string\" || decoded[0] !== \"/\") return null;\n if (decoded.startsWith(\"//\") || decoded.startsWith(\"/\\\\\")) return null;\n if (hasControlCharacter(decoded) || /[#?]/.test(decoded)) return null;\n try {\n encodeURIComponent(decoded);\n } catch {\n return null;\n }\n const parts = decoded.replaceAll(\"\\\\\", \"/\").split(\"/\");\n if (parts.includes(\"..\")) return null;\n if (/\\.(?:exe|sh|php|py|rb|bat|cmd|dll|so)$/i.test(decoded)) return null;\n const segments = parts.filter((segment) => segment !== \"\" && segment !== \".\");\n if (segments.length === 0) return fallbackToIndex ? \"/\" : \"/index.html\";\n if (segments.length === 1) {\n const lower = segments[0].toLowerCase();\n if (lower === \"index.html\" || lower === \"index.md\") segments[0] = lower;\n }\n return `/${segments.join(\"/\")}`.normalize(\"NFC\");\n }\n /** Decodes once and re-encodes, or null for malformed or unencodable text. */\n function recodeComponent(component) {\n try {\n const decoded = decodeURIComponent(component);\n if (hasControlCharacter(decoded)) return null;\n return encodeURIComponent(decoded);\n } catch {\n return null;\n }\n }\n /** Recodes each piece between literal separators, keeping the separators. */\n function recodeJoined(value, separators) {\n if (!separators) return recodeComponent(value);\n const parts = [];\n for (const part of value.split(separators[0])) {\n const recoded = recodeJoined(part, separators.slice(1));\n if (recoded === null) return null;\n parts.push(recoded);\n }\n return parts.join(separators[0]);\n }\n /**\n * The canonical route fragment, '' for in-page (native) fragments, or null\n * for a route fragment with a malformed percent escape or unencodable text.\n * A literal `?` starts the route's query, whose `&`, `=` and `+` stay literal,\n * so reopening the location gives the router the same path and query.\n */\n function canonicalCommentRouteHash(hash) {\n if (typeof hash !== \"string\") return null;\n const prefix = hash.startsWith(\"#/\") ? \"#/\" : hash.startsWith(\"#!/\") ? \"#!/\" : \"\";\n if (!prefix) return \"\";\n const route = hash.slice(prefix.length);\n const queryIndex = route.indexOf(\"?\");\n const path = recodeJoined(queryIndex === -1 ? route : route.slice(0, queryIndex), \"/\");\n if (path === null) return null;\n if (queryIndex === -1) return prefix + path;\n const query = recodeJoined(route.slice(queryIndex + 1), \"&=+\");\n return query === null ? null : `${prefix}${path}?${query}`;\n }\n /** The location for a browser URL's pathname (encoded) and hash. */\n function commentLocationFromUrl(pathname, hash, fallbackToIndex = false) {\n let decoded;\n try {\n decoded = decodeURIComponent(pathname);\n } catch {\n return null;\n }\n const path = canonicalCommentPathname(decoded, fallbackToIndex);\n const route = canonicalCommentRouteHash(hash);\n if (path === null || route === null) return null;\n const location = path + route;\n return location.length <= 1e3 ? location : null;\n }\n /** Splits a stored or posted location into its canonical parts. */\n function parseCommentLocation(location, fallbackToIndex = false) {\n if (typeof location !== \"string\" || !location || location.length > 1e3) return null;\n const hashIndex = location.indexOf(\"#\");\n const pathname = canonicalCommentPathname(hashIndex === -1 ? location : location.slice(0, hashIndex), fallbackToIndex);\n const hash = canonicalCommentRouteHash(hashIndex === -1 ? \"\" : location.slice(hashIndex));\n if (pathname === null || hash === null) return null;\n return {\n pathname,\n hash,\n location: pathname + hash\n };\n }\n /** The in-frame URL path (pathname plus route hash) that opens a location. */\n function commentLocationHref(location, fallbackToIndex = false) {\n const parsed = parseCommentLocation(location, fallbackToIndex);\n if (!parsed) return null;\n const pathname = parsed.pathname.split(\"/\").map((segment) => encodeURIComponent(segment)).join(\"/\");\n return pathname + parsed.hash;\n }\n function hasCommentPathExtension(pathname) {\n const lastSegment = pathname.split(\"/\").at(-1) ?? \"\";\n return /\\.[^./]+$/.test(lastSegment);\n }\n /** A location is served by a version file or, with fallback, by its index. */\n function isCommentLocationServed(location, files, fallbackToIndex) {\n const parsed = parseCommentLocation(location, fallbackToIndex);\n if (!parsed || parsed.location !== location) return false;\n return files.has(parsed.pathname) || fallbackToIndex && files.has(\"/index.html\") && !hasCommentPathExtension(parsed.pathname);\n }\n\n/** The location comments on this document belong to, or null if unusable. */\n function liveCommentLocation(ctx) {\n if (!ctx.locationScoped) return ctx.displayedPath;\n try {\n return commentLocationFromUrl(ctx.win.location.pathname, ctx.win.location.hash, ctx.fallbackToIndex);\n } catch (e) {\n return null;\n }\n }\n function retireStaleLocation(ctx) {\n if (!ctx.locationScoped) return;\n let location = liveCommentLocation(ctx);\n if (location === ctx.lastLocation) return;\n let previous = ctx.lastLocation;\n ctx.lastLocation = location;\n ctx.locationGeneration++;\n if (previous !== null) {\n let selection = ctx.win.getSelection();\n if (selection && selection.rangeCount) selection.removeAllRanges();\n }\n if (ctx.displayedPath === location) return;\n ctx.pendingHighlights = [];\n ctx.pendingScrollThreadId = null;\n ctx.checkingHighlights = [];\n ctx.checkingDeadlines = {};\n ctx.lastResolutionSignature = \"\";\n clearMarks(ctx);\n scheduleChecking(ctx);\n }\n function reportHash(ctx, force = false) {\n try {\n retireStaleLocation(ctx);\n } catch (e) {}\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 ctx.primordials.addEventListener(ctx.win, \"popstate\", () => 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 body = ctx.doc.body;\n if (!body || !body.hasAttribute(\"data-artifact-markdown\") || body.hasAttribute(\"data-md-outline-version\")) return;\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 const READY_MARK = \"data-md-outline-ready\";\n function installMarkdownOutline(ctx) {\n ctx.doc.documentElement.setAttribute(READY_MARK, \"\");\n if (ctx.doc.readyState === \"loading\") {\n ctx.doc.addEventListener(\"DOMContentLoaded\", () => startMarkdownOutline(ctx), { once: true });\n } else {\n startMarkdownOutline(ctx);\n }\n }\n function startMarkdownOutline(ctx) {\n const doc = ctx.doc;\n const win = ctx.win;\n const body = doc.body;\n const notReady = () => doc.documentElement.removeAttribute(READY_MARK);\n if (!body || !body.hasAttribute(\"data-artifact-markdown\") || body.getAttribute(\"data-md-outline-version\") !== \"2\") return notReady();\n const railNav = doc.querySelector(\"[data-md-outline=\\\"rail\\\"]\");\n const panelNav = doc.querySelector(\"[data-md-outline=\\\"panel\\\"]\");\n const dialog = doc.querySelector(\"dialog.md-outline-panel\");\n const row = doc.querySelector(\".md-position\");\n const rowButton = doc.querySelector(\".md-position-button\");\n const rowTitle = doc.querySelector(\".md-position-current\");\n const sidebar = doc.querySelector(\".md-sidebar\");\n const header = doc.querySelector(\".md-outline-header\");\n const closeButton = doc.querySelector(\"[data-md-outline-close]\");\n const article = doc.querySelector(\"article.md\");\n if (!railNav || !panelNav || !dialog || !row || !rowButton || !rowTitle || !sidebar || !header || !closeButton || !article) return notReady();\n const items = [];\n const itemsById = new Map();\n const railLinks = railNav.querySelectorAll(\"a[href^=\\\"#\\\"]\");\n for (let index = 0; index < railLinks.length; index++) {\n const link = railLinks[index];\n const id = link.getAttribute(\"href\").slice(1);\n const heading = doc.getElementById(id);\n if (!heading || itemsById.has(id)) continue;\n const item = {\n id,\n heading,\n fine: link.parentElement.hasAttribute(\"data-fine\"),\n links: []\n };\n items.push(item);\n itemsById.set(id, item);\n }\n if (!items.length) return notReady();\n const allLinks = doc.querySelectorAll(\"[data-md-outline] a[href^=\\\"#\\\"]\");\n for (let index = 0; index < allLinks.length; index++) {\n const item = itemsById.get(allLinks[index].getAttribute(\"href\").slice(1));\n if (item) item.links.push(allLinks[index]);\n }\n const reducedMotion = win.matchMedia(\"(prefers-reduced-motion: reduce)\");\n const toggles = doc.querySelectorAll(\"[data-md-outline-details]\");\n let showDetails = false;\n for (let index = 0; index < toggles.length; index++) if (toggles[index].checked) showDetails = true;\n let tracking = items.filter((item) => showDetails || !item.fine);\n let activeId = \"\";\n let frame = 0;\n let jumpPosition = null;\n let openY = 0;\n let restoreOnClose = false;\n let geometryChanged = false;\n let titleAnimation = null;\n const switchMargin = 12;\n const indicators = [];\n for (const root of [railNav, panelNav]) {\n const svg = root.querySelector(\".md-outline-rail\");\n const track = root.querySelector(\".md-outline-track\");\n const marker = root.querySelector(\".md-outline-progress\");\n if (svg && track && marker) indicators.push({\n root,\n svg,\n track,\n marker,\n placed: false,\n dirty: true,\n width: 0,\n total: 0,\n spans: new Map()\n });\n }\n const shown = (element) => win.getComputedStyle(element).display !== \"none\";\n const contentTop = () => shown(row) ? Math.max(0, row.getBoundingClientRect().bottom) : 0;\n const surface = () => dialog.open ? panelNav : shown(sidebar) ? railNav : panelNav;\n const applyCurrent = () => {\n const current = surface();\n for (const item of items) {\n for (const link of item.links) {\n if (item.id === activeId && current.contains(link)) link.setAttribute(\"aria-current\", \"location\");\n else link.removeAttribute(\"aria-current\");\n }\n }\n };\n const buildRail = (indicator) => {\n const { root, svg, track, marker } = indicator;\n const box = root.getBoundingClientRect();\n const links = Array.from(root.querySelectorAll(\"a\")).filter((link) => link.getClientRects().length > 0);\n if (!box.width || !box.height || !links.length) {\n svg.setAttribute(\"hidden\", \"\");\n return false;\n }\n const points = links.map((link) => {\n const rect = link.getBoundingClientRect();\n return {\n id: link.getAttribute(\"href\").slice(1),\n top: rect.top - box.top + root.scrollTop,\n bottom: rect.bottom - box.top + root.scrollTop\n };\n });\n const top = points[0].top;\n const bottom = points[points.length - 1].bottom;\n const path = `M 4 ${top} L 4 ${bottom}`;\n indicator.spans.clear();\n for (const point of points) indicator.spans.set(point.id, {\n start: point.top - top,\n length: point.bottom - point.top\n });\n track.setAttribute(\"d\", path);\n marker.setAttribute(\"d\", path);\n svg.style.height = bottom + \"px\";\n svg.removeAttribute(\"hidden\");\n indicator.width = box.width;\n indicator.total = bottom - top;\n indicator.dirty = false;\n return true;\n };\n const syncIndicators = (animate) => {\n for (const indicator of indicators) {\n const { root, svg, marker } = indicator;\n const box = root.getBoundingClientRect();\n if (!box.width || !box.height) {\n svg.setAttribute(\"hidden\", \"\");\n indicator.dirty = true;\n continue;\n }\n const rebuild = indicator.dirty || Math.abs(indicator.width - box.width) > .5;\n if (rebuild && !buildRail(indicator)) continue;\n const span = indicator.spans.get(activeId);\n if (!span) {\n marker.setAttribute(\"hidden\", \"\");\n continue;\n }\n const moving = animate && indicator.placed && !rebuild && !reducedMotion.matches;\n if (!moving) marker.style.transition = \"none\";\n marker.removeAttribute(\"hidden\");\n marker.style.strokeDasharray = `${span.length} ${indicator.total + 1}`;\n marker.style.strokeDashoffset = String(-span.start);\n if (!moving) {\n void marker.getBoundingClientRect();\n marker.style.removeProperty(\"transition\");\n }\n indicator.placed = true;\n }\n };\n const refreshGeometry = () => {\n for (const indicator of indicators) indicator.dirty = true;\n syncIndicators(false);\n };\n const reveal = (container, center) => {\n const link = container.querySelector(\"[aria-current]\");\n if (!link || container.scrollHeight <= container.clientHeight) return;\n const outer = container.getBoundingClientRect();\n const rect = link.getBoundingClientRect();\n const inset = container === sidebar ? header.offsetHeight + 8 : 12;\n const clippedAbove = rect.top < outer.top + inset;\n const clippedBelow = rect.bottom > outer.bottom - 12;\n if (!clippedAbove && !clippedBelow) return;\n if (center) {\n container.scrollTo({\n top: container.scrollTop + rect.top - outer.top - (container.clientHeight - rect.height) / 2,\n behavior: \"instant\"\n });\n return;\n }\n container.scrollTo({\n top: clippedAbove ? container.scrollTop - (outer.top + inset - rect.top) : container.scrollTop + rect.bottom - outer.bottom + 12,\n behavior: reducedMotion.matches ? \"instant\" : \"smooth\"\n });\n };\n const setActive = (item, animate = true) => {\n if (item.id === activeId) return;\n const previous = items.findIndex((candidate) => candidate.id === activeId);\n const direction = Math.sign(items.indexOf(item) - previous);\n activeId = item.id;\n applyCurrent();\n if (titleAnimation) titleAnimation.cancel();\n titleAnimation = null;\n rowTitle.textContent = item.heading.textContent;\n if (previous >= 0 && !reducedMotion.matches && shown(row) && typeof rowTitle.animate === \"function\") titleAnimation = rowTitle.animate([{\n opacity: .4,\n transform: `translateY(${direction * 4}px)`\n }, {\n opacity: 1,\n transform: \"translateY(0)\"\n }], {\n duration: 160,\n easing: \"cubic-bezier(0.16, 1, 0.3, 1)\"\n });\n syncIndicators(animate);\n if (shown(sidebar)) reveal(sidebar, false);\n };\n const update = () => {\n frame = 0;\n const animate = !geometryChanged;\n geometryChanged = false;\n if (jumpPosition !== null) {\n if (Math.abs(win.scrollY - jumpPosition) <= 1) return;\n jumpPosition = null;\n }\n const rendered = tracking.filter((item) => !item.heading.closest(\"details:not([open])\"));\n if (!rendered.length) return;\n const root = doc.scrollingElement || doc.documentElement;\n if (root.scrollHeight > win.innerHeight + 2 && root.scrollTop > 0 && root.scrollTop + win.innerHeight >= root.scrollHeight - 2) {\n setActive(rendered[rendered.length - 1], animate);\n return;\n }\n const top = contentTop();\n const line = top + (win.innerHeight - top) / 4;\n let index = Math.max(0, rendered.findIndex((item) => item.id === activeId));\n while (index + 1 < rendered.length && rendered[index + 1].heading.getBoundingClientRect().top <= line - switchMargin) index++;\n while (index > 0 && rendered[index].heading.getBoundingClientRect().top > line + switchMargin) index--;\n setActive(rendered[index], animate);\n };\n const schedule = () => {\n if (!frame) frame = win.requestAnimationFrame(update);\n };\n const scheduleGeometry = () => {\n geometryChanged = true;\n schedule();\n };\n const ownerOf = (item) => {\n const position = items.indexOf(item);\n let owner = tracking[0];\n for (const candidate of tracking) if (items.indexOf(candidate) <= position) owner = candidate;\n return owner;\n };\n const jump = (item) => {\n const heading = item.heading;\n for (let ancestor = heading.parentElement; ancestor; ancestor = ancestor.parentElement) if (ancestor.tagName === \"DETAILS\" && !ancestor.open) ancestor.open = true;\n win.scrollTo({\n top: Math.max(0, win.scrollY + heading.getBoundingClientRect().top - contentTop() - 16),\n behavior: \"instant\"\n });\n jumpPosition = win.scrollY;\n if (!heading.hasAttribute(\"tabindex\")) heading.setAttribute(\"tabindex\", \"-1\");\n heading.focus({ preventScroll: true });\n setActive(ownerOf(item));\n try {\n if (decodeURIComponent(win.location.hash) !== \"#\" + item.id) win.history.pushState(null, \"\", \"#\" + item.id);\n } catch (error) {}\n };\n const openPanel = () => {\n if (dialog.open) return;\n openY = win.scrollY;\n restoreOnClose = true;\n dialog.showModal();\n rowButton.setAttribute(\"aria-expanded\", \"true\");\n closeButton.focus({ preventScroll: true });\n applyCurrent();\n refreshGeometry();\n reveal(panelNav, true);\n };\n rowButton.addEventListener(\"pointerdown\", (event) => event.preventDefault());\n rowButton.addEventListener(\"click\", openPanel);\n const cancelPanel = () => {\n if (dialog.open) dialog.close();\n restoreOnClose = false;\n rowButton.setAttribute(\"aria-expanded\", \"false\");\n applyCurrent();\n rowButton.focus({ preventScroll: true });\n win.scrollTo({\n top: openY,\n behavior: \"instant\"\n });\n schedule();\n };\n closeButton.addEventListener(\"click\", cancelPanel);\n dialog.addEventListener(\"close\", () => {\n if (!dialog.open && restoreOnClose) cancelPanel();\n });\n for (const item of items) {\n for (const link of item.links) {\n link.addEventListener(\"click\", (event) => {\n if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;\n event.preventDefault();\n if (dialog.open) {\n restoreOnClose = false;\n dialog.close();\n rowButton.setAttribute(\"aria-expanded\", \"false\");\n applyCurrent();\n }\n jump(item);\n });\n }\n }\n for (let index = 0; index < toggles.length; index++) {\n const toggle = toggles[index];\n toggle.addEventListener(\"change\", () => {\n showDetails = toggle.checked;\n for (let other = 0; other < toggles.length; other++) toggles[other].checked = showDetails;\n tracking = items.filter((item) => showDetails || !item.fine);\n jumpPosition = null;\n activeId = \"\";\n for (const indicator of indicators) indicator.dirty = true;\n update();\n if (dialog.open) reveal(panelNav, true);\n });\n }\n win.addEventListener(\"scroll\", schedule, { passive: true });\n const followHistory = () => {\n let id = \"\";\n try {\n id = decodeURIComponent(win.location.hash.slice(1));\n } catch (error) {}\n const item = itemsById.get(id);\n if (!item) {\n jumpPosition = null;\n schedule();\n return;\n }\n jumpPosition = win.scrollY;\n setActive(ownerOf(item));\n };\n win.addEventListener(\"popstate\", followHistory);\n win.addEventListener(\"hashchange\", followHistory);\n win.addEventListener(\"resize\", () => {\n if (dialog.open && shown(sidebar)) cancelPanel();\n applyCurrent();\n refreshGeometry();\n scheduleGeometry();\n });\n if (doc.fonts && doc.fonts.addEventListener) doc.fonts.addEventListener(\"loadingdone\", () => {\n refreshGeometry();\n scheduleGeometry();\n });\n const articleObserver = new win.ResizeObserver(scheduleGeometry);\n articleObserver.observe(article);\n const outlineObserver = new win.ResizeObserver(refreshGeometry);\n outlineObserver.observe(railNav);\n outlineObserver.observe(panelNav);\n reducedMotion.addEventListener(\"change\", () => {\n if (titleAnimation) titleAnimation.cancel();\n syncIndicators(false);\n });\n win.addEventListener(\"pagehide\", (event) => {\n if (event.persisted) return;\n win.cancelAnimationFrame(frame);\n frame = 0;\n articleObserver.disconnect();\n outlineObserver.disconnect();\n });\n win.addEventListener(\"pageshow\", (event) => {\n if (!event.persisted) return;\n refreshGeometry();\n scheduleGeometry();\n });\n update();\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 createRange = win.Function.prototype.call.bind(win.Document.prototype.createRange);\n const rangeSetStart = win.Function.prototype.call.bind(win.Range.prototype.setStart);\n const rangeSetEnd = win.Function.prototype.call.bind(win.Range.prototype.setEnd);\n const rangeCollapse = win.Function.prototype.call.bind(win.Range.prototype.collapse);\n const rangeComparePoint = win.Function.prototype.call.bind(win.Range.prototype.comparePoint);\n const stringReplace = win.Function.prototype.call.bind(win.String.prototype.replace);\n const stringTrim = win.Function.prototype.call.bind(win.String.prototype.trim);\n const stringSlice = win.Function.prototype.call.bind(win.String.prototype.slice);\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 createRange,\n rangeSetStart,\n rangeSetEnd,\n rangeCollapse,\n rangeComparePoint,\n arrayMap,\n stringReplace,\n stringTrim,\n stringSlice,\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 locationScoped: false,\n fallbackToIndex: false,\n lastLocation: null,\n locationGeneration: 0,\n pendingScrollThreadId: 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 const queueSelection = function() {\n let generation = ctx.locationGeneration;\n ctx.win.setTimeout(() => {\n if (generation === ctx.locationGeneration) sendSelection(ctx);\n }, 0);\n };\n ctx.doc.addEventListener(\"mouseup\", queueSelection);\n ctx.doc.addEventListener(\"keyup\", queueSelection);\n installCodeCopy(ctx);\n installMarkdownOutline(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})();";
|
|
7602
7761
|
//#endregion
|
|
7603
7762
|
//#region ../viewer-kit/src/reporter-constants.ts
|
|
7604
7763
|
const READY_CHECK_MESSAGE_SOURCE = "artifactshare-parent";
|
|
@@ -10186,23 +10345,27 @@ function highlightTanStackCode(code, language) {
|
|
|
10186
10345
|
//#endregion
|
|
10187
10346
|
//#region ../viewer-kit/src/markdown-renderer.ts
|
|
10188
10347
|
const markdownExtensions = [markdownDisclosureExtension, httpAutolinkExtension];
|
|
10189
|
-
function renderMarkdownBody(source) {
|
|
10348
|
+
function renderMarkdownBody(source, options = {}) {
|
|
10190
10349
|
return embedYouTube(highlightCode(renderHtml(parseMarkdown(source, {
|
|
10191
10350
|
allowHtml: true,
|
|
10192
10351
|
extensions: markdownExtensions,
|
|
10193
|
-
headingIds: uniqueHeadingId()
|
|
10352
|
+
headingIds: uniqueHeadingId(options.headingIds === "unique")
|
|
10194
10353
|
}), {
|
|
10195
10354
|
allowHtml: false,
|
|
10196
10355
|
extensions: markdownExtensions
|
|
10197
10356
|
})));
|
|
10198
10357
|
}
|
|
10199
|
-
function uniqueHeadingId() {
|
|
10358
|
+
function uniqueHeadingId(documentUnique) {
|
|
10200
10359
|
const counts = /* @__PURE__ */ new Map();
|
|
10360
|
+
const used = /* @__PURE__ */ new Set();
|
|
10201
10361
|
return (text) => {
|
|
10202
10362
|
const base = text.normalize("NFKC").toLowerCase().replace(/[^\p{Letter}\p{Number}]+/gu, "-").replace(/^-|-$/g, "") || "section";
|
|
10203
|
-
|
|
10363
|
+
let count = (counts.get(base) ?? 0) + 1;
|
|
10364
|
+
let id = count === 1 ? base : `${base}-${count}`;
|
|
10365
|
+
while (documentUnique && used.has(id)) id = `${base}-${++count}`;
|
|
10204
10366
|
counts.set(base, count);
|
|
10205
|
-
|
|
10367
|
+
used.add(id);
|
|
10368
|
+
return id;
|
|
10206
10369
|
};
|
|
10207
10370
|
}
|
|
10208
10371
|
function highlightCode(html) {
|
|
@@ -10235,17 +10398,7 @@ const MARKDOWN_HIGHLIGHT_CSS = TANSTACK_HIGHLIGHT_CSS;
|
|
|
10235
10398
|
function renderMarkdownDocument(source, options = {}) {
|
|
10236
10399
|
const startedAt = performance.now();
|
|
10237
10400
|
const markdown = splitFrontmatter(source);
|
|
10238
|
-
const
|
|
10239
|
-
const navigation = markdownNavigation(markdown.metadata, body);
|
|
10240
|
-
const document = `<!doctype html>
|
|
10241
|
-
<html lang="en">
|
|
10242
|
-
<head>
|
|
10243
|
-
<meta charset="utf-8">
|
|
10244
|
-
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
10245
|
-
<style>${MD_STYLES}${MARKDOWN_HIGHLIGHT_CSS}</style>
|
|
10246
|
-
</head>
|
|
10247
|
-
<body data-artifact-markdown><div class="md-shell">${navigation}<article class="md" data-comment-content>${body}</article></div></body>
|
|
10248
|
-
</html>`;
|
|
10401
|
+
const document = options.mode === "export" ? legacyDocument(markdown) : outlineDocument(markdown);
|
|
10249
10402
|
if (options.logTiming !== false) console.info("markdown_render_completed", {
|
|
10250
10403
|
renderer: "tanstack",
|
|
10251
10404
|
durationMs: Math.round((performance.now() - startedAt) * 10) / 10
|
|
@@ -10263,15 +10416,119 @@ function splitFrontmatter(source) {
|
|
|
10263
10416
|
body: source.slice(match[0].length)
|
|
10264
10417
|
};
|
|
10265
10418
|
}
|
|
10266
|
-
function
|
|
10267
|
-
const
|
|
10268
|
-
|
|
10269
|
-
|
|
10419
|
+
function legacyDocument(markdown) {
|
|
10420
|
+
const body = renderMarkdownBody(markdown.body);
|
|
10421
|
+
const navigation = legacyNavigation(markdown.metadata, body);
|
|
10422
|
+
return `<!doctype html>
|
|
10423
|
+
<html lang="en">
|
|
10424
|
+
<head>
|
|
10425
|
+
<meta charset="utf-8">
|
|
10426
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
10427
|
+
<style>${MD_TOKEN_STYLES}${LEGACY_LAYOUT_STYLES}${MD_CONTENT_STYLES}${MARKDOWN_HIGHLIGHT_CSS}</style>
|
|
10428
|
+
</head>
|
|
10429
|
+
<body data-artifact-markdown><div class="md-shell">${navigation}<article class="md" data-comment-content>${body}</article></div></body>
|
|
10430
|
+
</html>`;
|
|
10431
|
+
}
|
|
10432
|
+
const OUTLINE_LABELS = {
|
|
10433
|
+
ja: {
|
|
10434
|
+
contents: "目次",
|
|
10435
|
+
onThisPage: "このページ",
|
|
10436
|
+
overview: "概要",
|
|
10437
|
+
finer: "細かい見出しも表示",
|
|
10438
|
+
close: "閉じる"
|
|
10439
|
+
},
|
|
10440
|
+
en: {
|
|
10441
|
+
contents: "Contents",
|
|
10442
|
+
onThisPage: "On this page",
|
|
10443
|
+
overview: "Overview",
|
|
10444
|
+
finer: "Show finer headings",
|
|
10445
|
+
close: "Close"
|
|
10446
|
+
}
|
|
10447
|
+
};
|
|
10448
|
+
const PANEL_ID = "md_outline_panel";
|
|
10449
|
+
function outlineDocument(markdown) {
|
|
10450
|
+
const body = renderMarkdownBody(markdown.body, { headingIds: "unique" });
|
|
10451
|
+
const lang = documentLanguage(markdown.metadata, markdown.body);
|
|
10452
|
+
const labels = /^ja(?:-|$)/i.test(lang) ? OUTLINE_LABELS.ja : OUTLINE_LABELS.en;
|
|
10453
|
+
const outline = renderOutline(extractHeadings(body), labels);
|
|
10454
|
+
return `<!doctype html>
|
|
10455
|
+
<html lang="${escapeHtml$1(lang)}">
|
|
10456
|
+
<head>
|
|
10457
|
+
<meta charset="utf-8">
|
|
10458
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
10459
|
+
<style>${MD_TOKEN_STYLES}${MD_CONTENT_STYLES}${OUTLINE_LAYOUT_STYLES}${MARKDOWN_HIGHLIGHT_CSS}</style>
|
|
10460
|
+
</head>
|
|
10461
|
+
<body data-artifact-markdown data-md-outline-version="2">${outline.row}<div class="md-shell">${outline.sidebar}${frontmatterDisclosure(markdown.metadata, "md-frontmatter")}<article class="md" data-comment-content>${body}</article></div>${outline.panel}</body>
|
|
10462
|
+
</html>`;
|
|
10463
|
+
}
|
|
10464
|
+
/**
|
|
10465
|
+
* A frontmatter `lang` wins; otherwise kana in the body means Japanese. Kanji
|
|
10466
|
+
* alone does not: Chinese text and English mentioning a kanji word stay `en`.
|
|
10467
|
+
*/
|
|
10468
|
+
function documentLanguage(metadata, body) {
|
|
10469
|
+
for (const line of metadata) {
|
|
10470
|
+
const tag = line.match(/^lang\s*:\s*(['"]?)([^'"]*)\1\s*$/)?.[2]?.trim() ?? "";
|
|
10471
|
+
if (/^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*$/.test(tag)) return tag;
|
|
10472
|
+
}
|
|
10473
|
+
return /[\p{Script=Hiragana}\p{Script=Katakana}]/u.test(body) ? "ja" : "en";
|
|
10474
|
+
}
|
|
10475
|
+
function extractHeadings(body) {
|
|
10476
|
+
return Array.from(body.matchAll(/<h([1-6]) id="([^"]+)">([\s\S]*?)<\/h\1>/g), ([, level, id, text]) => ({
|
|
10477
|
+
level: Number(level),
|
|
10478
|
+
id: id ?? "",
|
|
10479
|
+
label: plainText(text ?? "")
|
|
10480
|
+
}));
|
|
10481
|
+
}
|
|
10482
|
+
function renderOutline(headings, labels) {
|
|
10483
|
+
if (!headings.length) return {
|
|
10484
|
+
row: "",
|
|
10485
|
+
sidebar: "",
|
|
10486
|
+
panel: ""
|
|
10487
|
+
};
|
|
10488
|
+
const hasTitle = headings[0]?.level === 1 && headings.filter((h) => h.level === 1).length === 1;
|
|
10489
|
+
const sectionLevels = headings.filter((h) => !hasTitle || h.level !== 1).map((h) => h.level);
|
|
10490
|
+
const maxLevel = Math.min(6, Math.max(4, sectionLevels.length ? Math.min(...sectionLevels) : 2));
|
|
10491
|
+
const roots = [];
|
|
10492
|
+
const stack = [];
|
|
10493
|
+
for (const heading of headings) {
|
|
10494
|
+
while (stack.length && stack.at(-1).level >= heading.level) stack.pop();
|
|
10495
|
+
const entry = {
|
|
10496
|
+
...heading,
|
|
10497
|
+
indent: Math.min(5, Math.max(0, stack.length - (hasTitle && heading.level !== 1 ? 1 : 0))),
|
|
10498
|
+
overview: hasTitle && heading.level === 1,
|
|
10499
|
+
fine: heading.level > maxLevel,
|
|
10500
|
+
children: []
|
|
10501
|
+
};
|
|
10502
|
+
(stack.at(-1)?.children ?? roots).push(entry);
|
|
10503
|
+
stack.push(entry);
|
|
10504
|
+
}
|
|
10505
|
+
const list = renderOutlineList(roots, labels);
|
|
10506
|
+
const toggle = headings.some((h) => h.level > maxLevel) ? `<label class="md-outline-detail"><input type="checkbox" data-md-outline-details>${escapeHtml$1(labels.finer)}</label>` : "";
|
|
10507
|
+
const rail = "<svg class=\"md-outline-rail\" aria-hidden=\"true\" hidden><path class=\"md-outline-track\"/><path class=\"md-outline-progress\" hidden/></svg>";
|
|
10508
|
+
const current = headings.find((h) => h.level <= maxLevel) ?? headings[0];
|
|
10509
|
+
return {
|
|
10510
|
+
row: `<div class="md-position" data-comment-ui data-anchor-ignore><button type="button" class="md-position-button" aria-haspopup="dialog" aria-controls="${PANEL_ID}" aria-expanded="false"><span class="md-position-label">${escapeHtml$1(labels.contents)}</span><span class="md-position-current">${current.label}</span><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg></button></div>`,
|
|
10511
|
+
sidebar: `<aside class="md-sidebar" data-comment-ui data-anchor-ignore><nav class="md-outline" data-md-outline="rail" aria-labelledby="md_outline_title"><div class="md-outline-header"><h2 id="md_outline_title">${escapeHtml$1(labels.onThisPage)}</h2>${toggle}</div>${list}${rail}</nav></aside>`,
|
|
10512
|
+
panel: `<dialog id="${PANEL_ID}" class="md-outline-panel" aria-labelledby="md_outline_panel_title" data-comment-ui data-anchor-ignore><div class="md-outline-sheet"><div class="md-outline-panel-head"><h2 id="md_outline_panel_title">${escapeHtml$1(labels.contents)}</h2><button type="button" class="md-outline-close" data-md-outline-close>${escapeHtml$1(labels.close)}</button></div>${toggle}<nav class="md-outline md-outline-list" data-md-outline="panel" aria-labelledby="md_outline_panel_title">${list}${rail}</nav></div></dialog>`
|
|
10513
|
+
};
|
|
10514
|
+
}
|
|
10515
|
+
function renderOutlineList(entries, labels) {
|
|
10516
|
+
return `<ol>${entries.map((entry) => `<li data-level="${entry.level}" data-indent="${entry.indent}"${entry.fine ? " data-fine" : ""}${entry.overview ? " data-overview" : ""}><a href="#${escapeHtml$1(entry.id)}">${entry.overview ? escapeHtml$1(labels.overview) : entry.label}</a>${entry.children.length ? renderOutlineList(entry.children, labels) : ""}</li>`).join("")}</ol>`;
|
|
10517
|
+
}
|
|
10518
|
+
function frontmatterDisclosure(metadata, wrapper) {
|
|
10519
|
+
if (!metadata.length) return "";
|
|
10520
|
+
const details = `<details class="md-metadata" aria-label="Frontmatter"><summary>Frontmatter</summary><dl>${metadata.map((line) => {
|
|
10270
10521
|
const separator = line.indexOf(":");
|
|
10271
10522
|
const key = separator < 0 ? line : line.slice(0, separator);
|
|
10272
10523
|
const value = separator < 0 ? "" : line.slice(separator + 1).trim();
|
|
10273
10524
|
return `<div><dt>${escapeHtml$1(key)}</dt><dd>${escapeHtml$1(value)}</dd></div>`;
|
|
10274
|
-
}).join("")}</dl></details
|
|
10525
|
+
}).join("")}</dl></details>`;
|
|
10526
|
+
return wrapper ? `<div class="${wrapper}" data-comment-ui>${details}</div>` : details;
|
|
10527
|
+
}
|
|
10528
|
+
function legacyNavigation(metadata, body) {
|
|
10529
|
+
const headings = Array.from(body.matchAll(/<h([1-6]) id="([^"]+)">([\s\S]*?)<\/h\1>/g));
|
|
10530
|
+
if (metadata.length === 0 && headings.length === 0) return "";
|
|
10531
|
+
const frontmatter = frontmatterDisclosure(metadata);
|
|
10275
10532
|
const tocItems = headings.map(([, level, id, text]) => `<li class="level-${level}"><a href="#${escapeHtml$1(id ?? "")}">${plainText(text ?? "")}</a></li>`).join("");
|
|
10276
10533
|
return `<aside class="md-sidebar" data-comment-ui>${headings.length ? `<nav class="md-toc md-toc-desktop" aria-label="Table of contents"><h2>Contents</h2><ol>${tocItems}</ol></nav><details class="md-toc-mobile"><summary>Contents</summary><nav class="md-toc" aria-label="Table of contents"><ol>${tocItems}</ol></nav></details>` : ""}${frontmatter}</aside>`;
|
|
10277
10534
|
}
|
|
@@ -10288,7 +10545,7 @@ function plainText(value) {
|
|
|
10288
10545
|
function escapeHtml$1(value) {
|
|
10289
10546
|
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """).replaceAll("'", "'");
|
|
10290
10547
|
}
|
|
10291
|
-
const
|
|
10548
|
+
const MD_TOKEN_STYLES = `
|
|
10292
10549
|
:root {
|
|
10293
10550
|
color-scheme: light dark;
|
|
10294
10551
|
--md-text: #37352f;
|
|
@@ -10331,7 +10588,8 @@ const MD_STYLES = `
|
|
|
10331
10588
|
--md-shadow-sm: rgba(0, 0, 0, 0.32) 0 0 0 1px, rgba(0, 0, 0, 0.22) 0 1px 2px;
|
|
10332
10589
|
}
|
|
10333
10590
|
}
|
|
10334
|
-
|
|
10591
|
+
`;
|
|
10592
|
+
const LEGACY_LAYOUT_STYLES = `* { box-sizing: border-box; }
|
|
10335
10593
|
html, body { margin: 0; padding: 0; }
|
|
10336
10594
|
html { scroll-behavior: smooth; }
|
|
10337
10595
|
body {
|
|
@@ -10494,7 +10752,8 @@ body {
|
|
|
10494
10752
|
.md h4 { font-size: 1em; }
|
|
10495
10753
|
.md h5 { font-size: 0.875em; }
|
|
10496
10754
|
.md h6 { font-size: 0.85em; color: var(--md-muted); }
|
|
10497
|
-
|
|
10755
|
+
`;
|
|
10756
|
+
const MD_CONTENT_STYLES = `.md p, .md ul, .md ol, .md blockquote, .md table { margin: 0 0 16px; }
|
|
10498
10757
|
.md a { color: var(--md-link); text-decoration: none; text-underline-offset: 0.15em; }
|
|
10499
10758
|
.md {
|
|
10500
10759
|
overflow-wrap: anywhere;
|
|
@@ -10617,8 +10876,10 @@ body {
|
|
|
10617
10876
|
}
|
|
10618
10877
|
.md-video { position: relative; aspect-ratio: 16 / 9; margin: 0 0 16px; }
|
|
10619
10878
|
.md-video iframe { width: 100%; height: 100%; border: 0; }
|
|
10620
|
-
.mermaid-diagram { margin: 0 0 16px; overflow: auto; text-align: center; }
|
|
10621
|
-
.mermaid-diagram
|
|
10879
|
+
.mermaid-diagram { margin: 0 0 16px; padding: 16px; overflow: auto; background: #fff; color: #333; text-align: center; }
|
|
10880
|
+
.mermaid-diagram:focus-visible { outline: 2px solid #333; outline-offset: -2px; }
|
|
10881
|
+
.md-code-block .mermaid-diagram { margin: 0; }
|
|
10882
|
+
.mermaid-diagram svg { display: block; max-width: none; height: auto; margin: 0 auto; }
|
|
10622
10883
|
.mermaid-error { border: 1px solid #cf222e; }
|
|
10623
10884
|
.md hr {
|
|
10624
10885
|
height: 0.25em;
|
|
@@ -10636,6 +10897,250 @@ body {
|
|
|
10636
10897
|
}
|
|
10637
10898
|
.md input[type="checkbox"] { margin-right: 0.4em; }
|
|
10638
10899
|
`;
|
|
10900
|
+
const OUTLINE_LAYOUT_STYLES = `* { box-sizing: border-box; }
|
|
10901
|
+
html, body { margin: 0; padding: 0; }
|
|
10902
|
+
html { scroll-behavior: auto; }
|
|
10903
|
+
.md [id] { scroll-margin-top: 72px; }
|
|
10904
|
+
html:has(.md-outline-panel[open]) { overflow: hidden; scrollbar-gutter: stable; }
|
|
10905
|
+
body {
|
|
10906
|
+
background: var(--md-bg);
|
|
10907
|
+
color: var(--md-text);
|
|
10908
|
+
font: 400 18px/1.85 ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
|
|
10909
|
+
"Segoe UI", "Hiragino Sans", "Hiragino Kaku Gothic ProN", "Noto Sans JP",
|
|
10910
|
+
"Yu Gothic UI", Meiryo, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
|
|
10911
|
+
font-synthesis: none;
|
|
10912
|
+
line-break: strict;
|
|
10913
|
+
-webkit-font-smoothing: antialiased;
|
|
10914
|
+
}
|
|
10915
|
+
.md-shell { max-width: 1112px; margin: 0 auto; padding: 40px 28px 80px; }
|
|
10916
|
+
.md-shell:not(:has(> .md-sidebar)) { max-width: 776px; }
|
|
10917
|
+
.md-shell:has(> .md-sidebar) {
|
|
10918
|
+
display: grid;
|
|
10919
|
+
grid-template-columns: minmax(0, 720px) 288px;
|
|
10920
|
+
grid-template-rows: auto 1fr;
|
|
10921
|
+
column-gap: 48px;
|
|
10922
|
+
}
|
|
10923
|
+
.md { grid-column: 1; grid-row: 2; width: 100%; max-width: 720px; min-width: 0; margin: 0; }
|
|
10924
|
+
.md > :first-child { margin-top: 0; }
|
|
10925
|
+
.md > :last-child { margin-bottom: 0; }
|
|
10926
|
+
.md blockquote > :last-child { margin-bottom: 0; }
|
|
10927
|
+
.md h1, .md h2, .md h3, .md h4, .md h5, .md h6 {
|
|
10928
|
+
margin: 28px 0 12px;
|
|
10929
|
+
font-weight: 700;
|
|
10930
|
+
font-feature-settings: normal;
|
|
10931
|
+
letter-spacing: normal;
|
|
10932
|
+
line-height: 1.6;
|
|
10933
|
+
text-wrap: balance;
|
|
10934
|
+
}
|
|
10935
|
+
.md h1 { font-size: 30px; margin-bottom: 24px; }
|
|
10936
|
+
.md h2 { font-size: 24px; margin-top: 44px; }
|
|
10937
|
+
.md h3 { font-size: 21px; margin-top: 34px; }
|
|
10938
|
+
.md h4 { font-size: 19px; }
|
|
10939
|
+
.md h5 { font-size: 17px; }
|
|
10940
|
+
.md h6 { font-size: 16px; color: var(--md-muted); }
|
|
10941
|
+
.md p, .md ul, .md ol { margin-bottom: 24px; }
|
|
10942
|
+
.md strong, .md b, .md th { font-weight: 700; }
|
|
10943
|
+
.md :is(h1, h2, h3, h4, h5, h6)[tabindex="-1"]:focus { outline: none; }
|
|
10944
|
+
.md-frontmatter { grid-column: 1; grid-row: 1; margin: 0 0 24px; color: var(--md-muted); font-size: 14px; line-height: 1.6; }
|
|
10945
|
+
.md-frontmatter summary {
|
|
10946
|
+
padding: 8px 12px;
|
|
10947
|
+
border: 1px solid var(--md-border);
|
|
10948
|
+
border-radius: var(--md-radius-md);
|
|
10949
|
+
background: var(--md-surface);
|
|
10950
|
+
color: var(--md-text);
|
|
10951
|
+
cursor: pointer;
|
|
10952
|
+
font-weight: 700;
|
|
10953
|
+
}
|
|
10954
|
+
.md-frontmatter details[open] > summary { border-radius: var(--md-radius-md) var(--md-radius-md) 0 0; }
|
|
10955
|
+
.md-frontmatter summary:focus-visible { outline: 2px solid var(--md-link); outline-offset: 2px; }
|
|
10956
|
+
.md-frontmatter dl {
|
|
10957
|
+
margin: 0;
|
|
10958
|
+
padding: 10px 12px;
|
|
10959
|
+
border: 1px solid var(--md-border);
|
|
10960
|
+
border-top: 0;
|
|
10961
|
+
border-radius: 0 0 var(--md-radius-md) var(--md-radius-md);
|
|
10962
|
+
background: var(--md-muted-bg);
|
|
10963
|
+
}
|
|
10964
|
+
.md-frontmatter dl div { display: grid; grid-template-columns: minmax(4.5rem,auto) minmax(0,1fr); gap: 12px; padding: 4px 0; }
|
|
10965
|
+
.md-frontmatter dt { color: var(--md-faint); font-size: 12px; font-weight: 700; }
|
|
10966
|
+
.md-frontmatter dd { margin: 0; color: var(--md-text); overflow-wrap: anywhere; }
|
|
10967
|
+
.md-sidebar {
|
|
10968
|
+
grid-column: 2;
|
|
10969
|
+
grid-row: 1 / 3;
|
|
10970
|
+
position: sticky;
|
|
10971
|
+
top: 24px;
|
|
10972
|
+
align-self: start;
|
|
10973
|
+
max-height: calc(100dvh - 48px);
|
|
10974
|
+
overflow: auto;
|
|
10975
|
+
color: var(--md-muted);
|
|
10976
|
+
font-size: 13px;
|
|
10977
|
+
overscroll-behavior: contain;
|
|
10978
|
+
scrollbar-gutter: stable;
|
|
10979
|
+
scrollbar-color: var(--md-border) transparent;
|
|
10980
|
+
}
|
|
10981
|
+
.md-outline { position: relative; }
|
|
10982
|
+
.md-sidebar .md-outline { padding: 0 8px 0 0; }
|
|
10983
|
+
.md-outline-header { position: sticky; top: 0; z-index: 3; padding: 0 0 10px; background: var(--md-bg); }
|
|
10984
|
+
.md-outline-header h2 { margin: 0; color: var(--md-text); font-size: 14px; line-height: 1.7; font-weight: 700; }
|
|
10985
|
+
.md-outline-detail {
|
|
10986
|
+
display: flex;
|
|
10987
|
+
align-items: center;
|
|
10988
|
+
gap: 6px;
|
|
10989
|
+
min-height: 28px;
|
|
10990
|
+
color: var(--md-muted);
|
|
10991
|
+
font-size: 12px;
|
|
10992
|
+
line-height: 1.6;
|
|
10993
|
+
cursor: pointer;
|
|
10994
|
+
}
|
|
10995
|
+
.md-outline-detail input { flex-shrink: 0; margin: 0; accent-color: var(--md-link); }
|
|
10996
|
+
.md-outline ol { margin: 0; padding: 0; list-style: none; }
|
|
10997
|
+
.md-outline li { margin: 0; padding: 0; }
|
|
10998
|
+
.md-outline li[data-level="2"] { margin-block-start: 8px; }
|
|
10999
|
+
.md-outline li > a {
|
|
11000
|
+
display: block;
|
|
11001
|
+
padding: 4px 6px 4px 20px;
|
|
11002
|
+
border-radius: 4px;
|
|
11003
|
+
color: var(--md-muted);
|
|
11004
|
+
background: transparent;
|
|
11005
|
+
font-size: 13px;
|
|
11006
|
+
line-height: 1.6;
|
|
11007
|
+
font-weight: 400;
|
|
11008
|
+
text-decoration: none;
|
|
11009
|
+
overflow-wrap: anywhere;
|
|
11010
|
+
word-break: auto-phrase;
|
|
11011
|
+
line-break: strict;
|
|
11012
|
+
transition: color 160ms ease-out, background-color 160ms ease-out;
|
|
11013
|
+
}
|
|
11014
|
+
.md-outline li[data-indent="1"] > a { padding-left: 32px; }
|
|
11015
|
+
.md-outline li[data-indent="2"] > a { padding-left: 44px; }
|
|
11016
|
+
.md-outline li[data-indent="3"] > a { padding-left: 56px; }
|
|
11017
|
+
.md-outline li[data-indent="4"] > a { padding-left: 68px; }
|
|
11018
|
+
.md-outline li[data-indent="5"] > a { padding-left: 80px; }
|
|
11019
|
+
.md-outline li > a:hover { color: var(--md-text); background: var(--md-accent-bg); }
|
|
11020
|
+
.md-outline li > a[aria-current] { color: var(--md-link); background: color-mix(in srgb, var(--md-link) 3%, transparent); }
|
|
11021
|
+
.md-outline li[data-level="2"] > a, .md-outline li[data-level="1"]:not([data-overview]) > a { color: var(--md-text); font-weight: 700; }
|
|
11022
|
+
.md-outline li[data-level="2"] > a[aria-current], .md-outline li[data-level="1"] > a[aria-current] { color: var(--md-link); }
|
|
11023
|
+
:root:not(:has([data-md-outline-details]:checked)) .md-outline li[data-fine] { display: none; }
|
|
11024
|
+
.md-outline-rail {
|
|
11025
|
+
position: absolute;
|
|
11026
|
+
top: 0;
|
|
11027
|
+
left: 0;
|
|
11028
|
+
z-index: 1;
|
|
11029
|
+
width: 100%;
|
|
11030
|
+
overflow: visible;
|
|
11031
|
+
fill: none;
|
|
11032
|
+
pointer-events: none;
|
|
11033
|
+
}
|
|
11034
|
+
.md-outline-track { stroke: var(--md-border-strong); stroke-opacity: 0.5; stroke-width: 1; stroke-linecap: round; }
|
|
11035
|
+
.md-outline-progress {
|
|
11036
|
+
stroke: var(--md-link);
|
|
11037
|
+
stroke-width: 2;
|
|
11038
|
+
stroke-linecap: round;
|
|
11039
|
+
transition: stroke-dasharray 280ms cubic-bezier(0.16, 1, 0.3, 1), stroke-dashoffset 280ms cubic-bezier(0.16, 1, 0.3, 1);
|
|
11040
|
+
}
|
|
11041
|
+
.md-outline-rail[hidden], .md-outline-progress[hidden] { display: none; }
|
|
11042
|
+
.md-position {
|
|
11043
|
+
display: none;
|
|
11044
|
+
position: sticky;
|
|
11045
|
+
top: 0;
|
|
11046
|
+
z-index: 10;
|
|
11047
|
+
border-bottom: 1px solid var(--md-border);
|
|
11048
|
+
background: var(--md-bg);
|
|
11049
|
+
}
|
|
11050
|
+
.md-position-button {
|
|
11051
|
+
display: flex;
|
|
11052
|
+
align-items: center;
|
|
11053
|
+
gap: 10px;
|
|
11054
|
+
width: 100%;
|
|
11055
|
+
min-height: 44px;
|
|
11056
|
+
padding: 8px 20px;
|
|
11057
|
+
border: 0;
|
|
11058
|
+
background: transparent;
|
|
11059
|
+
color: var(--md-text);
|
|
11060
|
+
font: inherit;
|
|
11061
|
+
font-size: 13px;
|
|
11062
|
+
line-height: 1.7;
|
|
11063
|
+
text-align: left;
|
|
11064
|
+
cursor: pointer;
|
|
11065
|
+
}
|
|
11066
|
+
.md-position-button:hover { background: var(--md-accent-bg); }
|
|
11067
|
+
.md-position-label { flex-shrink: 0; color: var(--md-link); }
|
|
11068
|
+
.md-position-current { flex: 1; min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
|
11069
|
+
.md-position-button svg { flex-shrink: 0; width: 16px; height: 16px; }
|
|
11070
|
+
.md-outline-panel {
|
|
11071
|
+
position: fixed;
|
|
11072
|
+
inset: 0 0 0 auto;
|
|
11073
|
+
width: 380px;
|
|
11074
|
+
max-width: 100%;
|
|
11075
|
+
height: 100dvh;
|
|
11076
|
+
max-height: 100dvh;
|
|
11077
|
+
margin: 0;
|
|
11078
|
+
padding: 0;
|
|
11079
|
+
border: 0;
|
|
11080
|
+
border-left: 1px solid var(--md-border);
|
|
11081
|
+
background: var(--md-bg);
|
|
11082
|
+
color: var(--md-text);
|
|
11083
|
+
overflow: hidden;
|
|
11084
|
+
}
|
|
11085
|
+
.md-outline-panel::backdrop { background: rgba(20, 22, 24, 0.26); }
|
|
11086
|
+
.md-outline-sheet { display: flex; flex-direction: column; height: 100%; }
|
|
11087
|
+
.md-outline-panel-head {
|
|
11088
|
+
display: flex;
|
|
11089
|
+
flex-shrink: 0;
|
|
11090
|
+
align-items: center;
|
|
11091
|
+
justify-content: space-between;
|
|
11092
|
+
min-height: 56px;
|
|
11093
|
+
padding: 20px 20px 6px;
|
|
11094
|
+
border-bottom: 1px solid var(--md-border);
|
|
11095
|
+
}
|
|
11096
|
+
.md-outline-panel-head h2 { margin: 0; font-size: 16px; line-height: 1.7; font-weight: 700; }
|
|
11097
|
+
.md-outline-close {
|
|
11098
|
+
min-width: 44px;
|
|
11099
|
+
min-height: 44px;
|
|
11100
|
+
border: 0;
|
|
11101
|
+
background: transparent;
|
|
11102
|
+
color: inherit;
|
|
11103
|
+
font: inherit;
|
|
11104
|
+
font-size: 14px;
|
|
11105
|
+
cursor: pointer;
|
|
11106
|
+
}
|
|
11107
|
+
.md-outline-sheet > .md-outline-detail { flex-shrink: 0; min-height: 44px; padding: 0 20px; }
|
|
11108
|
+
.md-outline-list {
|
|
11109
|
+
flex: 1;
|
|
11110
|
+
min-height: 0;
|
|
11111
|
+
overflow: auto;
|
|
11112
|
+
overscroll-behavior: contain;
|
|
11113
|
+
padding: 16px 20px calc(24px + env(safe-area-inset-bottom));
|
|
11114
|
+
scrollbar-color: var(--md-border) transparent;
|
|
11115
|
+
}
|
|
11116
|
+
.md-outline-list > .md-outline-rail { left: 20px; width: calc(100% - 20px); }
|
|
11117
|
+
.md-outline-list li > a { min-height: 44px; padding-top: 6px; padding-bottom: 6px; font-size: 14px; line-height: 1.65; }
|
|
11118
|
+
.md-outline-list li[data-level="2"] > a, .md-outline-list li[data-level="1"]:not([data-overview]) > a { font-size: 15px; }
|
|
11119
|
+
.md-outline a:focus-visible, .md-outline-detail input:focus-visible, .md-position-button:focus-visible, .md-outline-panel button:focus-visible {
|
|
11120
|
+
outline: 2px solid var(--md-link);
|
|
11121
|
+
outline-offset: -2px;
|
|
11122
|
+
}
|
|
11123
|
+
@media (max-width: 1119px) {
|
|
11124
|
+
.md-shell, .md-shell:has(> .md-sidebar) { display: block; max-width: 760px; padding: 28px 20px 64px; }
|
|
11125
|
+
/* Without the outline controller (no reporter), the list itself stays
|
|
11126
|
+
usable at the top of the document with plain fragment links. */
|
|
11127
|
+
.md-sidebar { position: static; max-height: none; overflow: visible; margin: 0 0 24px; }
|
|
11128
|
+
.md-outline-header { position: static; }
|
|
11129
|
+
:root[data-md-outline-ready] .md-sidebar { display: none; }
|
|
11130
|
+
:root[data-md-outline-ready] .md-position { display: block; }
|
|
11131
|
+
.md h1 { font-size: 28px; }
|
|
11132
|
+
.md h2 { font-size: 23px; }
|
|
11133
|
+
.md-outline-panel { width: 100%; border: 0; }
|
|
11134
|
+
}
|
|
11135
|
+
@media (pointer: coarse) {
|
|
11136
|
+
.md-sidebar .md-outline li > a { min-height: 44px; padding-top: 8px; padding-bottom: 8px; }
|
|
11137
|
+
.md-outline-detail { min-height: 44px; }
|
|
11138
|
+
}
|
|
11139
|
+
@media (prefers-reduced-motion: reduce) {
|
|
11140
|
+
.md-outline-progress { transition: none; }
|
|
11141
|
+
.md-outline li > a { transition: color 80ms linear, background-color 80ms linear; }
|
|
11142
|
+
}
|
|
11143
|
+
`;
|
|
10639
11144
|
//#endregion
|
|
10640
11145
|
//#region src/preview/reporter-protocol.ts
|
|
10641
11146
|
/** Self-contained so the exact validator can also run in the local shell.
|
|
@@ -10676,10 +11181,10 @@ function validPreviewObservation(value) {
|
|
|
10676
11181
|
"selector",
|
|
10677
11182
|
"label",
|
|
10678
11183
|
"contextText",
|
|
10679
|
-
"ownText",
|
|
11184
|
+
...Object.hasOwn(value, "ownTextHash") ? ["ownTextHash", "ownTextExcerpt"] : ["ownText"],
|
|
10680
11185
|
"tagName",
|
|
10681
11186
|
"rect"
|
|
10682
|
-
]) && str(value.selector, 4096) && str(value.label, 1024) && str(value.contextText, 4096) && str(value.ownText, 1e6) && str(value.tagName, 128) && rect(value.rect);
|
|
11187
|
+
]) && str(value.selector, 4096) && str(value.label, 1024) && str(value.contextText, 4096) && (Object.hasOwn(value, "ownTextHash") ? typeof value.ownTextHash === "string" && /^[a-f0-9]{64}$/.test(value.ownTextHash) && str(value.ownTextExcerpt, 16e3) : str(value.ownText, 1e6)) && str(value.tagName, 128) && rect(value.rect);
|
|
10683
11188
|
case "text-selection": return keys(value, [
|
|
10684
11189
|
...base,
|
|
10685
11190
|
"token",
|
|
@@ -10720,6 +11225,10 @@ function scriptJson(value) {
|
|
|
10720
11225
|
}
|
|
10721
11226
|
function renderPreviewShell(options) {
|
|
10722
11227
|
const { fileName, resumeCommand, shareOrigin, messages } = options;
|
|
11228
|
+
const extensionAt = fileName.lastIndexOf(".");
|
|
11229
|
+
const stem = extensionAt > 0 ? fileName.slice(0, extensionAt) : fileName;
|
|
11230
|
+
const extension = extensionAt > 0 ? fileName.slice(extensionAt) : "";
|
|
11231
|
+
const isMarkdown = /\.(md|markdown)$/i.test(fileName);
|
|
10723
11232
|
const config = scriptJson({
|
|
10724
11233
|
fileName,
|
|
10725
11234
|
resumeCommand,
|
|
@@ -10770,8 +11279,11 @@ function renderPreviewShell(options) {
|
|
|
10770
11279
|
position: sticky; top: 0; z-index: 40; }
|
|
10771
11280
|
.brand { width: 20px; height: 20px; border-radius: 5px; background: var(--coral);
|
|
10772
11281
|
color: #fff; font-weight: 700; font-size: 11px; display: grid; place-items: center; }
|
|
10773
|
-
.file-name {
|
|
11282
|
+
.topbar > :not(.file-name):not(.spacer) { flex-shrink: 0; white-space: nowrap; }
|
|
11283
|
+
.file-name { display: flex; font-weight: 600; font-size: 13px; min-width: 0;
|
|
10774
11284
|
overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
11285
|
+
.file-stem { overflow: hidden; text-overflow: ellipsis; }
|
|
11286
|
+
.file-extension { flex-shrink: 0; }
|
|
10775
11287
|
.local-badge { font-size: 11px; color: var(--muted-foreground);
|
|
10776
11288
|
border: 1px solid var(--border); border-radius: var(--r-full);
|
|
10777
11289
|
padding: 1px 8px; background: var(--accent); }
|
|
@@ -10783,12 +11295,13 @@ function renderPreviewShell(options) {
|
|
|
10783
11295
|
border-radius: var(--r-md); background: var(--background); color: var(--foreground);
|
|
10784
11296
|
padding: 5px 12px; }
|
|
10785
11297
|
.btn:hover { background: var(--accent); }
|
|
10786
|
-
.btn-primary { background: var(--primary); border-color: var(--primary); color:
|
|
11298
|
+
.btn-primary { background: var(--primary); border-color: var(--primary); color: var(--badge-on-link); }
|
|
11299
|
+
.btn-primary:not(:disabled):hover, .btn-primary:not(:disabled):focus { background: var(--primary); }
|
|
10787
11300
|
.btn:disabled { cursor: default; opacity: 0.5; }
|
|
10788
11301
|
.btn-primary:disabled:hover { background: var(--primary); }
|
|
10789
11302
|
.layout { display: flex; height: calc(100vh - 46px); }
|
|
10790
11303
|
.doc-wrap { flex: 1; display: flex; position: relative; }
|
|
10791
|
-
#artifactFrame { flex: 1; width: 100%; height: 100%; border: 0; background:
|
|
11304
|
+
#artifactFrame { flex: 1; width: 100%; height: 100%; border: 0; background: #ffffff;${isMarkdown ? "" : " color-scheme: light;"} }
|
|
10792
11305
|
.mode-toggle { font: inherit; color: inherit; border: 0; position: fixed; right: 320px; bottom: 20px; z-index: 60;
|
|
10793
11306
|
display: flex; align-items: center; gap: 8px; background: var(--card);
|
|
10794
11307
|
border-radius: var(--r-full); box-shadow: var(--shadow-lg);
|
|
@@ -10812,6 +11325,8 @@ function renderPreviewShell(options) {
|
|
|
10812
11325
|
border-radius: var(--r-md); font: inherit; font-size: 13px; padding: 7px 9px;
|
|
10813
11326
|
resize: none; background: var(--background); color: var(--foreground); }
|
|
10814
11327
|
.popover textarea:focus { outline: 2px solid var(--link); outline-offset: -1px; }
|
|
11328
|
+
#popError { color: var(--foreground); font-size: 13px; line-height: 1.4; }
|
|
11329
|
+
#popError:not(:empty) { margin-top: 8px; }
|
|
10815
11330
|
.popover .row { display: flex; justify-content: flex-end; gap: 6px; margin-top: 8px; }
|
|
10816
11331
|
.panel { width: 300px; border-left: 1px solid var(--border); background: var(--background);
|
|
10817
11332
|
padding: 14px; display: flex; flex-direction: column; gap: 10px; overflow-y: auto; }
|
|
@@ -10886,7 +11401,7 @@ function renderPreviewShell(options) {
|
|
|
10886
11401
|
height: min(42vh, 340px); overflow-y: auto;
|
|
10887
11402
|
border-left: none; border-top: 1px solid var(--border);
|
|
10888
11403
|
box-shadow: var(--shadow-lg); z-index: 55; border-radius: 12px 12px 0 0; }
|
|
10889
|
-
.local-badge { display: none; }
|
|
11404
|
+
.local-badge, .watch-label { display: none; }
|
|
10890
11405
|
.mode-toggle { right: 20px; bottom: calc(min(42vh, 340px) + 14px); }
|
|
10891
11406
|
.toast { bottom: calc(min(42vh, 340px) + 60px); }
|
|
10892
11407
|
}
|
|
@@ -10895,7 +11410,7 @@ function renderPreviewShell(options) {
|
|
|
10895
11410
|
<body class="annotate">
|
|
10896
11411
|
<header class="topbar">
|
|
10897
11412
|
<div class="brand">as</div>
|
|
10898
|
-
<span class="file-name">${escapeHtml(
|
|
11413
|
+
<span class="file-name"><span class="file-stem">${escapeHtml(stem)}</span><span class="file-extension">${escapeHtml(extension)}</span></span>
|
|
10899
11414
|
<span class="local-badge" data-msg="preview.localBadge" aria-hidden="true"></span>
|
|
10900
11415
|
<span id="watchStatus" role="status" style="font-size:12px;color:var(--muted-foreground)"><span class="watch-dot" aria-hidden="true"></span><span class="watch-label" data-msg="preview.watching"></span></span>
|
|
10901
11416
|
<div class="spacer"></div>
|
|
@@ -10928,6 +11443,7 @@ function renderPreviewShell(options) {
|
|
|
10928
11443
|
<div class="popover" id="popover">
|
|
10929
11444
|
<div class="target-label" id="popTarget"></div>
|
|
10930
11445
|
<textarea id="popText" rows="2"></textarea>
|
|
11446
|
+
<div id="popError" role="alert"></div>
|
|
10931
11447
|
<div class="row">
|
|
10932
11448
|
<button class="btn" id="popCancel" data-msg="preview.cancel"></button>
|
|
10933
11449
|
<button class="btn btn-primary" id="popAdd" data-msg="preview.add"></button>
|
|
@@ -11122,7 +11638,7 @@ function renderPreviewShell(options) {
|
|
|
11122
11638
|
openPopover({
|
|
11123
11639
|
kind: 'element', state: 'attached',
|
|
11124
11640
|
selector: data.selector, label: data.label, contextText: data.contextText,
|
|
11125
|
-
ownText: data.ownText, tagName: data.tagName,
|
|
11641
|
+
...(data.ownTextHash ? { ownTextHash: data.ownTextHash, ownTextExcerpt: data.ownTextExcerpt } : { ownText: data.ownText }), tagName: data.tagName,
|
|
11126
11642
|
}, data.label, data.rect);
|
|
11127
11643
|
} else if (data.kind === 'anchor-verdicts') {
|
|
11128
11644
|
if (data.verificationId !== verificationId || !Number.isSafeInteger(data.generation) || data.generation <= verificationGeneration) return;
|
|
@@ -11143,24 +11659,40 @@ function renderPreviewShell(options) {
|
|
|
11143
11659
|
});
|
|
11144
11660
|
|
|
11145
11661
|
// --- popover ------------------------------------------------------------
|
|
11662
|
+
let savePending = false;
|
|
11663
|
+
let saveFailed = false;
|
|
11664
|
+
let popoverTop = 52;
|
|
11665
|
+
function positionPopover() {
|
|
11666
|
+
const height = popover.getBoundingClientRect().height;
|
|
11667
|
+
const bottom = window.innerWidth <= 860
|
|
11668
|
+
? document.querySelector('.panel').getBoundingClientRect().top
|
|
11669
|
+
: window.innerHeight;
|
|
11670
|
+
const fitsAbovePanel = bottom - height - 8 >= 52;
|
|
11671
|
+
// On phones the floating mode toggle (60) also overlaps the action row.
|
|
11672
|
+
popover.style.zIndex = window.innerWidth <= 860 ? '61' : '';
|
|
11673
|
+
popover.style.top = Math.max(52, Math.min(popoverTop,
|
|
11674
|
+
(fitsAbovePanel ? bottom : window.innerHeight) - height - 8)) + 'px';
|
|
11675
|
+
}
|
|
11146
11676
|
function openPopover(anchor, label, rect) {
|
|
11677
|
+
if (savePending || saveFailed || (pendingAnchor && popText.value.trim())) return;
|
|
11678
|
+
document.getElementById('popError').textContent = '';
|
|
11147
11679
|
pendingAnchor = anchor;
|
|
11148
11680
|
popTarget.textContent = label;
|
|
11149
11681
|
const frameRect = frame.getBoundingClientRect();
|
|
11150
11682
|
const left = Math.max(8, Math.min(
|
|
11151
11683
|
frameRect.left + (rect ? rect.left : 40) + 20,
|
|
11152
11684
|
window.innerWidth - 320));
|
|
11153
|
-
|
|
11154
|
-
frameRect.top + (rect ? rect.top + rect.height : 60) + 8,
|
|
11155
|
-
window.innerHeight - 140));
|
|
11685
|
+
popoverTop = frameRect.top + (rect ? rect.top + rect.height : 60) + 8;
|
|
11156
11686
|
popover.style.left = left + 'px';
|
|
11157
|
-
popover.style.top = top + 'px';
|
|
11158
11687
|
popover.classList.add('show');
|
|
11688
|
+
positionPopover();
|
|
11159
11689
|
popText.value = '';
|
|
11160
11690
|
popText.focus();
|
|
11161
11691
|
}
|
|
11162
11692
|
function hidePopover() {
|
|
11693
|
+
if (savePending) return;
|
|
11163
11694
|
popover.classList.remove('show');
|
|
11695
|
+
saveFailed = false;
|
|
11164
11696
|
pendingAnchor = null;
|
|
11165
11697
|
if (pendingReload !== null) {
|
|
11166
11698
|
const target = pendingReload;
|
|
@@ -11176,8 +11708,20 @@ function renderPreviewShell(options) {
|
|
|
11176
11708
|
document.getElementById('popAdd').addEventListener('click', addAnnotation);
|
|
11177
11709
|
async function addAnnotation() {
|
|
11178
11710
|
const comment = popText.value.trim();
|
|
11179
|
-
if (!comment || !pendingAnchor) return;
|
|
11180
|
-
|
|
11711
|
+
if (!comment || !pendingAnchor || savePending) return;
|
|
11712
|
+
savePending = true;
|
|
11713
|
+
document.getElementById('popAdd').disabled = true;
|
|
11714
|
+
const result = await api('POST', '/api/annotations', { anchor: pendingAnchor, comment });
|
|
11715
|
+
savePending = false;
|
|
11716
|
+
document.getElementById('popAdd').disabled = false;
|
|
11717
|
+
if (!result || !result.annotation || typeof result.annotation.thread !== 'string' || !result.annotation.thread) {
|
|
11718
|
+
saveFailed = true;
|
|
11719
|
+
document.getElementById('popError').textContent = t('preview.annotationSaveFailed');
|
|
11720
|
+
positionPopover();
|
|
11721
|
+
return;
|
|
11722
|
+
}
|
|
11723
|
+
document.getElementById('popError').textContent = '';
|
|
11724
|
+
popText.value = '';
|
|
11181
11725
|
hidePopover();
|
|
11182
11726
|
}
|
|
11183
11727
|
|
|
@@ -11191,6 +11735,7 @@ function renderPreviewShell(options) {
|
|
|
11191
11735
|
headers,
|
|
11192
11736
|
body: bodyValue === undefined ? '{}' : JSON.stringify(bodyValue),
|
|
11193
11737
|
});
|
|
11738
|
+
if (!response.ok) return null;
|
|
11194
11739
|
return await response.json().catch(() => null);
|
|
11195
11740
|
} catch (error) {
|
|
11196
11741
|
return null;
|
|
@@ -11322,7 +11867,7 @@ function renderPreviewShell(options) {
|
|
|
11322
11867
|
body.classList.toggle('annotate', annotateMode);
|
|
11323
11868
|
modeToggle.setAttribute('aria-checked', String(annotateMode));
|
|
11324
11869
|
postToFrame({ kind: 'annotate-mode', enabled: annotateMode });
|
|
11325
|
-
hidePopover();
|
|
11870
|
+
if (!popText.value.trim()) hidePopover();
|
|
11326
11871
|
});
|
|
11327
11872
|
|
|
11328
11873
|
// --- reload + orphan handling ------------------------------------------
|
|
@@ -11484,7 +12029,9 @@ function renderPreviewShell(options) {
|
|
|
11484
12029
|
// --- share --------------------------------------------------------------
|
|
11485
12030
|
document.getElementById('shareBtn').addEventListener('click', () => {
|
|
11486
12031
|
if (sharePopup && !sharePopup.closed) {
|
|
11487
|
-
sharePopup.
|
|
12032
|
+
sharePopup.focus();
|
|
12033
|
+
sharePopup.postMessage({ source: 'artifactshare-preview', kind: 'refresh-snapshot' }, CONFIG.shareOrigin);
|
|
12034
|
+
return;
|
|
11488
12035
|
}
|
|
11489
12036
|
sharePopup = window.open(CONFIG.shareOrigin + '/', '_blank', 'width=440,height=560');
|
|
11490
12037
|
});
|
|
@@ -12445,6 +12992,8 @@ async function runPreview(parsed, mode) {
|
|
|
12445
12992
|
if (!real.ok) return writeFailure(command, validationError("Path was not found.", `Check the path and retry: ${positional}`), mode, 1);
|
|
12446
12993
|
if (!statSync(real.realpath, { throwIfNoEntry: false })?.isFile()) return writeFailure(command, validationError("Only a regular file can be previewed.", `Pass a single .md or .html file, not a directory: ${positional}`), mode, 1);
|
|
12447
12994
|
const lower = real.realpath.toLowerCase();
|
|
12995
|
+
if (lower.endsWith(".pdf")) return writeFailure(command, validationError("PDF files cannot be previewed locally.", "Run share <file.pdf> to publish it and open the share URL, or preview a Markdown or HTML file."), mode, 1);
|
|
12996
|
+
if (lower.endsWith(".mp4")) return writeFailure(command, validationError("Video files cannot be previewed locally.", "Run share <file.mp4> to publish it and open the share URL, or preview a Markdown or HTML file."), mode, 1);
|
|
12448
12997
|
if (!lower.endsWith(".md") && !lower.endsWith(".html")) return writeFailure(command, validationError("Only .md and .html files can be previewed.", "Pass a single Markdown or HTML file."), mode, 1);
|
|
12449
12998
|
const existing = await resolveLiveSession(real.realpath);
|
|
12450
12999
|
const requestedNotification = previewNotificationForEnvironment();
|
|
@@ -12639,6 +13188,7 @@ async function runCommentsList(parsed, mode) {
|
|
|
12639
13188
|
const contracted = COMMENTS_LIST_RESPONSE_SCHEMA.safeParse(result.data);
|
|
12640
13189
|
const raw = isRecord$1(result.data) ? result.data : null;
|
|
12641
13190
|
const comments = contracted.success ? contracted.data.comments : Array.isArray(raw?.comments) ? raw.comments : [];
|
|
13191
|
+
if (hasMalformedPageAnchor(comments)) return writeFailure(command, malformedPageError(), mode, 1);
|
|
12642
13192
|
writeSuccess(command, {
|
|
12643
13193
|
artifact_id: artifactId,
|
|
12644
13194
|
share_url: configString(contracted.success ? contracted.data.share_url : raw?.share_url),
|
|
@@ -12685,6 +13235,7 @@ async function runCommentsPost(parsed, mode) {
|
|
|
12685
13235
|
const postedRaw = isRecord$1(result.data) ? result.data : null;
|
|
12686
13236
|
const threadId = configString(postedResponse?.thread_id ?? postedRaw?.thread_id);
|
|
12687
13237
|
if (!threadId) return writeFailure(command, serviceError("Comment was saved but the response had no thread id."), mode, 1);
|
|
13238
|
+
if (hasMalformedPageAnchor([postedResponse?.thread ?? postedRaw?.thread])) return writeFailure(command, malformedPageError(), mode, 1);
|
|
12688
13239
|
writeSuccess(command, {
|
|
12689
13240
|
artifact_id: artifactId,
|
|
12690
13241
|
share_url: configString(postedResponse?.share_url ?? postedRaw?.share_url),
|
|
@@ -12819,8 +13370,21 @@ async function postCommentAction(parsed, command, artifactId, payload, mode) {
|
|
|
12819
13370
|
writeFailure(command, serviceError("Comment was changed but the response was empty."), mode, 1);
|
|
12820
13371
|
return null;
|
|
12821
13372
|
}
|
|
13373
|
+
if (isRecord$1(result.data) && hasMalformedPageAnchor([result.data.thread])) {
|
|
13374
|
+
writeFailure(command, malformedPageError(), mode, 1);
|
|
13375
|
+
return null;
|
|
13376
|
+
}
|
|
12822
13377
|
return result.data;
|
|
12823
13378
|
}
|
|
13379
|
+
function hasMalformedPageAnchor(threads) {
|
|
13380
|
+
return threads.some((thread) => {
|
|
13381
|
+
const anchor = isRecord$1(thread) ? thread.anchor : void 0;
|
|
13382
|
+
return isRecord$1(anchor) && ("page_number" in anchor || "version_number" in anchor) && !CommentAnchorSchema.safeParse(anchor).success;
|
|
13383
|
+
});
|
|
13384
|
+
}
|
|
13385
|
+
function malformedPageError() {
|
|
13386
|
+
return serviceError("A comment had incomplete or invalid PDF page fields.");
|
|
13387
|
+
}
|
|
12824
13388
|
function requiredOption(value, message, hint) {
|
|
12825
13389
|
if (!value || !value.trim()) return { error: validationError(message, hint) };
|
|
12826
13390
|
return { value: value.trim() };
|
|
@@ -13755,11 +14319,23 @@ async function prepareUploadPayload(targetPath, dependencies) {
|
|
|
13755
14319
|
try {
|
|
13756
14320
|
const selection = await prepareUploadSelection(targetPath, false, dependencies);
|
|
13757
14321
|
if (selection.directory && selection.files.length === 0) return { error: validationError("Directory has no shareable files.", "Add index.html or index.md and retry.") };
|
|
14322
|
+
const single = selection.directory ? null : selection.files[0];
|
|
14323
|
+
let kind = "static_site";
|
|
14324
|
+
if (single) {
|
|
14325
|
+
kind = artifactKindForFile(single.name);
|
|
14326
|
+
if (isPdfFileName(single.name)) {
|
|
14327
|
+
if (!await blobHasPdfMagic(single.blob)) return { error: notPdfError(single.name) };
|
|
14328
|
+
kind = "pdf";
|
|
14329
|
+
} else if (isMp4FileName(single.name)) {
|
|
14330
|
+
if (!await blobHasMp4Signature(single.blob)) return { error: notMp4Error(single.name) };
|
|
14331
|
+
kind = "video";
|
|
14332
|
+
}
|
|
14333
|
+
}
|
|
13758
14334
|
const form = await createUploadForm();
|
|
13759
|
-
for (const file of selection.files) form.append("file", file.blob.slice(0, file.blob.size, contentTypeFor(file.name)), file.name);
|
|
14335
|
+
for (const file of selection.files) form.append("file", file.blob.slice(0, file.blob.size, kind === "pdf" ? PDF_CONTENT_TYPE : kind === "video" ? MP4_CONTENT_TYPE : contentTypeFor(file.name)), file.name);
|
|
13760
14336
|
return { payload: {
|
|
13761
14337
|
form,
|
|
13762
|
-
kind
|
|
14338
|
+
kind
|
|
13763
14339
|
} };
|
|
13764
14340
|
} catch (error) {
|
|
13765
14341
|
return { error: uploadReadError(error, targetPath) };
|
|
@@ -13868,6 +14444,47 @@ function contentTypeFor(path) {
|
|
|
13868
14444
|
function artifactKindForFile(path) {
|
|
13869
14445
|
return path.endsWith(".md") ? "markdown_page" : "html_page";
|
|
13870
14446
|
}
|
|
14447
|
+
const PDF_CONTENT_TYPE = "application/pdf";
|
|
14448
|
+
const PDF_MAGIC = [
|
|
14449
|
+
37,
|
|
14450
|
+
80,
|
|
14451
|
+
68,
|
|
14452
|
+
70,
|
|
14453
|
+
45
|
|
14454
|
+
];
|
|
14455
|
+
/** A single-file upload is a PDF only with a `.pdf` name (any case) and magic. */
|
|
14456
|
+
function isPdfFileName(name) {
|
|
14457
|
+
return name.toLowerCase().endsWith(".pdf");
|
|
14458
|
+
}
|
|
14459
|
+
function hasPdfMagic(bytes) {
|
|
14460
|
+
return PDF_MAGIC.every((value, index) => bytes[index] === value);
|
|
14461
|
+
}
|
|
14462
|
+
async function blobHasPdfMagic(blob) {
|
|
14463
|
+
return hasPdfMagic(new Uint8Array(await blob.slice(0, PDF_MAGIC.length).arrayBuffer()));
|
|
14464
|
+
}
|
|
14465
|
+
function notPdfError(name) {
|
|
14466
|
+
return validationError(`File ${name} is not a PDF: it does not start with %PDF-.`, "Export the document to PDF again, or share an HTML or Markdown file instead. Supported single files: .html, .htm, .md, .markdown, .pdf and .mp4.");
|
|
14467
|
+
}
|
|
14468
|
+
const MP4_CONTENT_TYPE = "video/mp4";
|
|
14469
|
+
const FTYP = [
|
|
14470
|
+
102,
|
|
14471
|
+
116,
|
|
14472
|
+
121,
|
|
14473
|
+
112
|
|
14474
|
+
];
|
|
14475
|
+
/** A single-file upload is a video only with a `.mp4` name (any case) and an ftyp box. */
|
|
14476
|
+
function isMp4FileName(name) {
|
|
14477
|
+
return name.toLowerCase().endsWith(".mp4");
|
|
14478
|
+
}
|
|
14479
|
+
function hasMp4Signature(bytes) {
|
|
14480
|
+
return bytes.length >= 8 && FTYP.every((value, index) => bytes[index + 4] === value);
|
|
14481
|
+
}
|
|
14482
|
+
async function blobHasMp4Signature(blob) {
|
|
14483
|
+
return hasMp4Signature(new Uint8Array(await blob.slice(0, 8).arrayBuffer()));
|
|
14484
|
+
}
|
|
14485
|
+
function notMp4Error(name) {
|
|
14486
|
+
return validationError(`File ${name} is not an MP4 video: it has no ftyp box at byte 4.`, "Export or re-encode the recording as MP4 (for example H.264 in an .mp4 container) and retry, or share an HTML, Markdown or PDF file instead. Supported single files: .html, .htm, .md, .markdown, .pdf and .mp4.");
|
|
14487
|
+
}
|
|
13871
14488
|
//#endregion
|
|
13872
14489
|
//#region src/command-runners/download.ts
|
|
13873
14490
|
var DownloadFileError = class extends Error {};
|
|
@@ -14861,7 +15478,14 @@ async function runShare(parsed, mode, isRetry = false, prepared) {
|
|
|
14861
15478
|
else if (parsed.options.noLinkExpiry === true) initialForm.set("link_expires_at", "null");
|
|
14862
15479
|
if (parsed.options.noSlackNotify === true) initialForm.set("slack_notify", "false");
|
|
14863
15480
|
const uploadQuery = {};
|
|
14864
|
-
if (shareKey !== null)
|
|
15481
|
+
if (shareKey !== null) {
|
|
15482
|
+
uploadQuery.publish_key = shareKey;
|
|
15483
|
+
if (parsed.options.visibility !== void 0) {
|
|
15484
|
+
const explicitVisibility = VisibilitySchema.safeParse(parsed.options.visibility);
|
|
15485
|
+
if (!explicitVisibility.success) return writeFailure(command, validationError("Invalid visibility.", "Use private, workspace, project, or link."), mode, 1);
|
|
15486
|
+
uploadQuery.key_visibility = explicitVisibility.data;
|
|
15487
|
+
}
|
|
15488
|
+
}
|
|
14865
15489
|
if (parsed.options.expectedVersion) uploadQuery.expected_version = parsed.options.expectedVersion;
|
|
14866
15490
|
if (upload.payload.kind === "static_site") {
|
|
14867
15491
|
uploadQuery.artifact_kind = "static_site";
|
|
@@ -14878,7 +15502,9 @@ async function runShare(parsed, mode, isRetry = false, prepared) {
|
|
|
14878
15502
|
authenticated: true,
|
|
14879
15503
|
...shareKey !== null ? {
|
|
14880
15504
|
artifactTarget: true,
|
|
14881
|
-
operation: "share"
|
|
15505
|
+
operation: "share",
|
|
15506
|
+
linkExpiresAt: parsed.options.linkExpiresAt,
|
|
15507
|
+
noLinkExpiry: parsed.options.noLinkExpiry
|
|
14882
15508
|
} : {},
|
|
14883
15509
|
baseUrl,
|
|
14884
15510
|
credentialSource: credential.source,
|
|
@@ -15056,6 +15682,8 @@ async function runAppend(parsed, mode, isRetry = false, preparedContent) {
|
|
|
15056
15682
|
}
|
|
15057
15683
|
const file = selection.files[0];
|
|
15058
15684
|
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);
|
|
15685
|
+
if (isPdfFileName(file.name) && await blobHasPdfMagic(file.blob)) return writeFailure(command, validationError("Append does not support PDF files.", "Append adds UTF-8 text to Markdown or HTML artifacts. To replace a PDF artifact, run update <artifact> <file.pdf>."), mode, 1);
|
|
15686
|
+
if (isMp4FileName(file.name) && await blobHasMp4Signature(file.blob)) return writeFailure(command, validationError("Append does not support video files.", "Append adds UTF-8 text to Markdown or HTML artifacts. To replace a video artifact, run update <artifact> <file.mp4>."), mode, 1);
|
|
15059
15687
|
try {
|
|
15060
15688
|
content = new TextDecoder("utf-8", { fatal: true }).decode(await file.blob.arrayBuffer());
|
|
15061
15689
|
} catch {
|
|
@@ -15396,6 +16024,10 @@ async function moveRunner(ctx) {
|
|
|
15396
16024
|
const parsed = parsedArgsFromContext("move", ctx);
|
|
15397
16025
|
return await runWithSkillAutoUpdate(parsed, () => runMove(parsed, outputMode(parsed.options)));
|
|
15398
16026
|
}
|
|
16027
|
+
async function artifactsVersionsRunner(ctx) {
|
|
16028
|
+
const parsed = parsedArgsFromContext("artifacts versions", ctx);
|
|
16029
|
+
return await runWithSkillAutoUpdate(parsed, () => runArtifactsVersions(parsed, outputMode(parsed.options)));
|
|
16030
|
+
}
|
|
15399
16031
|
async function artifactsGetRunner(ctx) {
|
|
15400
16032
|
const parsed = parsedArgsFromContext("artifacts get", ctx);
|
|
15401
16033
|
return await runWithSkillAutoUpdate(parsed, () => runArtifactsGet(parsed, outputMode(parsed.options)));
|
|
@@ -15854,7 +16486,7 @@ const shareDefinition = define({
|
|
|
15854
16486
|
visibility: {
|
|
15855
16487
|
type: "string",
|
|
15856
16488
|
toKebab: true,
|
|
15857
|
-
description: "private, workspace, project, or link (default: project for a project destination, otherwise resolved from config)"
|
|
16489
|
+
description: "private, workspace, project, or link (default: project for a project destination, otherwise resolved from config); keyed resends reject a different effective value before creating a version (Home project means private). Change with edit --visibility"
|
|
15858
16490
|
},
|
|
15859
16491
|
linkExpiresAt: {
|
|
15860
16492
|
type: "string",
|
|
@@ -15890,6 +16522,8 @@ const shareDefinition = define({
|
|
|
15890
16522
|
},
|
|
15891
16523
|
examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare share report.html --project-id <id> --json
|
|
15892
16524
|
npm exec --yes --package=@artifactshare/cli -- artifactshare share report.html --project-id <id> --key nightly-report --json
|
|
16525
|
+
npm exec --yes --package=@artifactshare/cli -- artifactshare share deck.pdf --project-id <id> --json
|
|
16526
|
+
npm exec --yes --package=@artifactshare/cli -- artifactshare share demo.mp4 --project-id <id> --json
|
|
15893
16527
|
|
|
15894
16528
|
Posting to a project delivers to the audience defined by that project.
|
|
15895
16529
|
With no destination, share posts to home. Choose the setting by purpose:
|
|
@@ -15908,14 +16542,21 @@ With no destination, share posts to home. Choose the setting by purpose:
|
|
|
15908
16542
|
To keep an existing share URL, use update:
|
|
15909
16543
|
npm exec --yes --package=@artifactshare/cli -- artifactshare update <artifact-id-or-url> <path> --json
|
|
15910
16544
|
|
|
16545
|
+
A single file can be HTML (.html, .htm), Markdown (.md, .markdown), PDF, or MP4 video.
|
|
16546
|
+
A PDF needs a .pdf name (any case) and must start with %PDF-; it is stored as
|
|
16547
|
+
the original file, up to 25 MiB. A static-site folder still cannot include a .pdf file.
|
|
16548
|
+
A video needs a .mp4 name (any case) and an ftyp box at byte 4; it is stored as
|
|
16549
|
+
the original file, up to 25 MiB, and plays in the viewer. An .mp4 inside a folder stays a site asset.
|
|
16550
|
+
|
|
15911
16551
|
For repeat jobs, use --key: first share creates the artifact, later runs add versions.
|
|
16552
|
+
Resending never changes visibility. An explicit --visibility whose effective value differs from the stored value fails before creating a version. Home treats project as private, as on creation. Use edit <id> --visibility <value> --json to change it intentionally.
|
|
15912
16553
|
|
|
15913
16554
|
Common failures:
|
|
15914
16555
|
auth_required Set ARTIFACTSHARE_TOKEN before share
|
|
15915
16556
|
self_upload_disabled Sign in with Google or Microsoft to upload your own files
|
|
15916
16557
|
file_too_large Reduce file or directory size and retry
|
|
15917
16558
|
upload_read_failed Check filesystem availability and permissions, then retry
|
|
15918
|
-
validation_failed Check file type (.html / .md for single files) and directory layout
|
|
16559
|
+
validation_failed Check file type (.html / .md / .pdf / .mp4 for single files; a .pdf must start with %PDF-, a .mp4 needs an ftyp box) and directory layout
|
|
15919
16560
|
link Copy into the selection or pass the target by absolute path
|
|
15920
16561
|
outside_cwd Pass an absolute path
|
|
15921
16562
|
parent_traversal Pass a direct absolute path without any .. component
|
|
@@ -15923,6 +16564,7 @@ Common failures:
|
|
|
15923
16564
|
not_found Check the path and retry
|
|
15924
16565
|
invalid_type Select a regular file or directory
|
|
15925
16566
|
unsupported_guarantee Select a filesystem with stable dev/ino and no-follow support
|
|
16567
|
+
key_visibility_mismatch Run edit <id> --visibility <value> --json to change the audience; agent credentials require a person to run edit using a human credential
|
|
15926
16568
|
key_target_moved The artifact for --key moved; update it by ID or use a new key
|
|
15927
16569
|
key_kind_mismatch The artifact for --key is a different kind; use a new key`
|
|
15928
16570
|
});
|
|
@@ -15978,7 +16620,7 @@ Common failures:
|
|
|
15978
16620
|
self_upload_disabled Sign in with Google or Microsoft to upload your own files
|
|
15979
16621
|
file_too_large Reduce file or directory size and retry
|
|
15980
16622
|
upload_read_failed Check filesystem availability and permissions, then retry
|
|
15981
|
-
validation_failed Check file type (.html / .md for single files) and directory layout
|
|
16623
|
+
validation_failed Check file type (.html / .md / .pdf / .mp4 for single files; a .pdf must start with %PDF-, a .mp4 needs an ftyp box) and directory layout
|
|
15982
16624
|
link Copy into the selection or pass the target by absolute path
|
|
15983
16625
|
outside_cwd Pass an absolute path
|
|
15984
16626
|
parent_traversal Pass a direct absolute path without any .. component
|
|
@@ -16003,7 +16645,7 @@ const appendDefinition = define({
|
|
|
16003
16645
|
description: "Non-empty UTF-8 file to append"
|
|
16004
16646
|
}
|
|
16005
16647
|
},
|
|
16006
|
-
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.
|
|
16648
|
+
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, PDFs and videos are not supported, and a PDF or MP4 file cannot be appended. Use update to replace the full source, PDF or video instead.
|
|
16007
16649
|
|
|
16008
16650
|
Common failures:
|
|
16009
16651
|
upload_read_failed Check filesystem availability and permissions, then retry
|
|
@@ -16173,6 +16815,8 @@ const downloadDefinition = define({
|
|
|
16173
16815
|
|
|
16174
16816
|
Use resolve first when a user gives a title or project name, then pass the id here.
|
|
16175
16817
|
Download writes files to a directory so the result can be inspected or passed to update.
|
|
16818
|
+
A PDF artifact downloads as its original bytes under its stored .pdf name (index.pdf when none is stored).
|
|
16819
|
+
A video artifact downloads as its original MP4 bytes under its stored .mp4 name (index.mp4 when none is stored).
|
|
16176
16820
|
Artifact IDs must match ^[a-z0-9]{10}$; invalid or duplicate list/index IDs fail before writes.
|
|
16177
16821
|
Download accepts linked output parents and rechecks their resolved directory identities.
|
|
16178
16822
|
Links in the output root, index, and every listed artifact are rejected, regardless of --force.
|
|
@@ -16208,8 +16852,8 @@ It installs or updates the bundled Artifact Share skill in user scope (Claude Co
|
|
|
16208
16852
|
Codex, or Cursor detected from the working directory; all three if none are
|
|
16209
16853
|
detected), then reads single-file artifacts. Cursor project scope is not
|
|
16210
16854
|
auto-installed; use skills install --tool cursor --scope project. Existing
|
|
16211
|
-
project-scope skills are not modified. For static sites
|
|
16212
|
-
the JSON includes a download next_command.
|
|
16855
|
+
project-scope skills are not modified. For static sites, multi-file artifacts,
|
|
16856
|
+
PDFs or videos, the JSON includes a download next_command.
|
|
16213
16857
|
|
|
16214
16858
|
Claude Code user skills go to $CLAUDE_CONFIG_DIR/skills when set, otherwise
|
|
16215
16859
|
~/.claude/skills. Relative paths resolve against cwd without tilde expansion.
|
|
@@ -16259,7 +16903,7 @@ Common failures:
|
|
|
16259
16903
|
});
|
|
16260
16904
|
const artifactsGetDefinition = define({
|
|
16261
16905
|
name: "get",
|
|
16262
|
-
description: "Read
|
|
16906
|
+
description: "Read file source or static-site metadata and retained-version totals.",
|
|
16263
16907
|
toKebab: true,
|
|
16264
16908
|
args: {
|
|
16265
16909
|
...commonArgs,
|
|
@@ -16290,15 +16934,43 @@ const artifactsGetDefinition = define({
|
|
|
16290
16934
|
|
|
16291
16935
|
Use resolve first when a user gives a title or project name, then pass the id here.
|
|
16292
16936
|
Read the successful JSON from data.content (the source) and data.version_id (the version actually read). Use --version <version-id> to read an earlier published version. Publisher credentials do not support --version.
|
|
16937
|
+
Static sites return metadata only, without content or format; --include, --version and --offset are unsupported for sites. Updated get explicitly requests metadata; released source-only clients retain unsupported-kind and open still suggests download.
|
|
16938
|
+
For human and agent credentials, get and list include retain_versions (null for unlimited), version_count and total_size_bytes for versions the caller can list, independent of --version or history pagination. For static sites, only published versions that have a publication timestamp appear in history and totals. This applies to owners too. Publisher credentials do not receive version_count or total_size_bytes. Managed artifacts can exceed their retention policy.
|
|
16939
|
+
The response includes data.title and data.visibility for the current artifact, even for historical or continuation reads.
|
|
16293
16940
|
The response also includes data.truncated and data.next_offset. If data.truncated is true, call again with the same --version selection and --offset set to data.next_offset and concatenate data.content until data.truncated is false.
|
|
16294
16941
|
|
|
16295
16942
|
Common failures:
|
|
16296
16943
|
auth_required Set ARTIFACTSHARE_TOKEN before artifacts get
|
|
16297
16944
|
target_not_found Retry with an artifact ID, share URL, or sandbox URL
|
|
16298
|
-
unsupported_kind
|
|
16945
|
+
unsupported_kind Static sites do not support --include or --version; PDFs and videos have no text source, use download
|
|
16299
16946
|
version_removed Omit --version to inspect current content
|
|
16300
16947
|
validation_failed Check --version, --offset and --include values`
|
|
16301
16948
|
});
|
|
16949
|
+
const artifactsVersionsDefinition = define({
|
|
16950
|
+
name: "versions",
|
|
16951
|
+
description: "List retained versions and logical byte totals for files and static sites.",
|
|
16952
|
+
toKebab: true,
|
|
16953
|
+
args: {
|
|
16954
|
+
...commonArgs,
|
|
16955
|
+
artifactIdOrUrl: {
|
|
16956
|
+
type: "positional",
|
|
16957
|
+
toKebab: true,
|
|
16958
|
+
description: "Artifact ID or supported share/viewer/execution URL"
|
|
16959
|
+
},
|
|
16960
|
+
cursor: {
|
|
16961
|
+
type: "string",
|
|
16962
|
+
toKebab: true,
|
|
16963
|
+
description: "Continue history with next_cursor from the previous page"
|
|
16964
|
+
}
|
|
16965
|
+
},
|
|
16966
|
+
examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare artifacts versions <artifact-id-or-url> --json
|
|
16967
|
+
npm exec --yes --package=@artifactshare/cli -- artifactshare artifacts versions <artifact-id-or-url> --cursor <token> --json
|
|
16968
|
+
|
|
16969
|
+
Returns versions with version_id, created_at, size_bytes and is_current, newest first, 50 per page.
|
|
16970
|
+
Use next_cursor while has_more is true. Restart without --cursor if invalid.
|
|
16971
|
+
retain_versions is null for unlimited retention. version_count and total_size_bytes cover versions the caller can list. For static sites, only published versions that have a publication timestamp appear in history and totals. This applies to owners too. A publisher-created static-site version may have a null creator. Static-site sizes sum all files, including inherited files. These are logical bytes, not physical storage or billing; reused files count in each version.
|
|
16972
|
+
Publisher-managed artifacts may exceed retain_versions because human and current versions are protected. Publisher credentials cannot read history. Unreadable artifacts return target_not_found.`
|
|
16973
|
+
});
|
|
16302
16974
|
const artifactsListDefinition = define({
|
|
16303
16975
|
name: "list",
|
|
16304
16976
|
description: "List artifacts you shared, newest first.",
|
|
@@ -16331,6 +17003,7 @@ const artifactsListDefinition = define({
|
|
|
16331
17003
|
npm exec --yes --package=@artifactshare/cli -- artifactshare artifacts list --home --query report --json
|
|
16332
17004
|
npm exec --yes --package=@artifactshare/cli -- artifactshare artifacts list --project-id <id> --cursor <token> --json
|
|
16333
17005
|
|
|
17006
|
+
Compare total_size_bytes across pages client-side to find the largest artifacts. Each row includes retain_versions, version_count and total_size_bytes (logical bytes across versions the caller can list; for static sites, only published versions that have a publication timestamp count, even for owners).
|
|
16334
17007
|
Use an id from this list with update, edit, move, delete, artifacts get, or comments list.
|
|
16335
17008
|
|
|
16336
17009
|
Common failures:
|
|
@@ -16346,6 +17019,7 @@ const artifactsDefinition = define({
|
|
|
16346
17019
|
subCommands: {
|
|
16347
17020
|
list: lazyCommand(artifactsListDefinition, artifactsListRunner),
|
|
16348
17021
|
get: lazyCommand(artifactsGetDefinition, artifactsGetRunner),
|
|
17022
|
+
versions: lazyCommand(artifactsVersionsDefinition, artifactsVersionsRunner),
|
|
16349
17023
|
delete: lazyCommand(deleteDefinition, (ctx) => deleteRunner(ctx, "artifacts delete"))
|
|
16350
17024
|
},
|
|
16351
17025
|
examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare artifacts list --json
|
|
@@ -16408,6 +17082,13 @@ supplied for agent posts. version_id identifies the original comment version
|
|
|
16408
17082
|
unchecked means no browser has checked it; needs-check means it was opened
|
|
16409
17083
|
but no unique position was found. ambiguous_at_creation records whether a
|
|
16410
17084
|
viewer selection was ambiguous when created; agent and legacy anchors omit it.
|
|
17085
|
+
target_path names the page the text is on: the entry page, or on a multi-file
|
|
17086
|
+
site the file or route path plus any #/ or #!/ hash route (for example
|
|
17087
|
+
/settings or /index.html#/billing). Other fragments such as #intro are not
|
|
17088
|
+
part of it. Quoted-text posting on multi-file sites remains unsupported.
|
|
17089
|
+
PDF page comments keep the artifact anchor kind and add page_number, the page
|
|
17090
|
+
open when posted, with version_id and version_number of that version (null
|
|
17091
|
+
once deleted). Agents cannot post page comments.
|
|
16411
17092
|
Older servers may omit these optional fields.
|
|
16412
17093
|
|
|
16413
17094
|
Common failures:
|
|
@@ -16592,6 +17273,9 @@ npm exec --yes --package=@artifactshare/cli -- artifactshare preview next --sess
|
|
|
16592
17273
|
Returns {items: []} with timed_out: true when the wait expires, and
|
|
16593
17274
|
session_ended: true when the preview shuts down while waiting. Successful
|
|
16594
17275
|
results include the sanitized agent notification projection.
|
|
17276
|
+
Element text up to 16,000 normalized UTF-16 code units keeps raw ownText.
|
|
17277
|
+
Larger captures return ownTextHash (full-text SHA-256) and ownTextExcerpt
|
|
17278
|
+
(first 16,000 code units, reader context only). Legacy anchors are unchanged.
|
|
16595
17279
|
|
|
16596
17280
|
Common failures:
|
|
16597
17281
|
preview_session_not_found Start a session with: preview <file>
|
|
@@ -16719,7 +17403,7 @@ Prints one ready JSON line ({url, session, share_origin, reused, agent}) and
|
|
|
16719
17403
|
keeps serving until stopped. Re-running against a live session reuses it.
|
|
16720
17404
|
|
|
16721
17405
|
Common failures:
|
|
16722
|
-
validation_failed Pass a single local .md or .html file
|
|
17406
|
+
validation_failed Pass a single local .md or .html file; PDF and video files cannot be previewed, share them instead
|
|
16723
17407
|
preview_session_unverified Retry an unresponsive session; stop and restart a session created by an older CLI`
|
|
16724
17408
|
});
|
|
16725
17409
|
const previewDefinition = define({
|
|
@@ -16738,7 +17422,7 @@ const previewDefinition = define({
|
|
|
16738
17422
|
npm exec --yes --package=@artifactshare/cli -- artifactshare preview next ./lp.html --wait 90
|
|
16739
17423
|
|
|
16740
17424
|
Common failures:
|
|
16741
|
-
validation_failed Pass a single local .md or .html file
|
|
17425
|
+
validation_failed Pass a single local .md or .html file; PDF and video files cannot be previewed, share them instead
|
|
16742
17426
|
preview_session_unverified Retry an unresponsive session; stop and restart a session created by an older CLI
|
|
16743
17427
|
preview_session_not_found No live session; start one with preview <file>`,
|
|
16744
17428
|
run: parentCommandRunner("preview")
|