pipeup 0.7.0 → 0.8.0-beta.2

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/cli/pipeup.mjs CHANGED
@@ -5,6 +5,8 @@ import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
5
5
  import { homedir } from "node:os";
6
6
  import { basename, dirname, join, resolve } from "node:path";
7
7
  import { check, table } from "./check.mjs";
8
+ import { init, InitError } from "./init.mjs";
9
+ import { read, ReadError } from "./read.mjs";
8
10
  import { comments, watch } from "./link.mjs";
9
11
  import * as skills from "./skills.mjs";
10
12
 
@@ -14,7 +16,23 @@ const core = () => import("../dist/pipeup.core.js");
14
16
  const KEYFILE = process.env.PIPEUP_AGENT_FILE || join(homedir(), ".pipeup", "agent.json");
15
17
  const AI = "AI assistant";
16
18
 
17
- const USAGE = `pipeup skills install|remove|list [--project] [--agent claude|codex|all] [--yes] [--replace] [--dry-run]
19
+ const USAGE = `pipeup init <page.html> [--yes] [--dry-run] [--update] [--offline] [--addon <id>]… [--agent] [--marks]
20
+ Adds Pipeup to the page: the script pinned to this version and its integrity hash, and a document identity if the
21
+ page has none (never a new one for a page that has one). It says what it will change and asks first; every other
22
+ byte stays as it was. --update moves a page to this version, --offline puts Pipeup inside the page, --addon adds an
23
+ add-on (saying what it sends; one that needs something asks, or takes it as --inbox <url> or --github-repo owner/repo),
24
+ --agent lists this computer's agent and adds the agents add-on. Then it offers stable names for the page's blocks,
25
+ charts and slides, one at a time (--marks goes straight there; --yes skips it). Exit codes: 0 done, 1 a file
26
+ failed, 2 the command needs something first.
27
+
28
+ pipeup read <page.html> [--from <file or folder>]… [--deep] [--all] [--json] [--no-share] [--out <file>]
29
+ Prints the page's comments without opening it, as Markdown (like Copy comments › As Markdown) or, with --json, as data: from
30
+ feedback files and folders of them (--deep looks in folders inside), the page's shared copy (with @pipeup/share
31
+ installed; --no-share reads nothing from the network) and its replies file. Every comment is checked as the page
32
+ checks it; what was read, skipped or left out is said on standard error. --out writes one merged feedback file.
33
+ Exit codes: 0 done, 1 a source couldn't be read, 2 the command needs something first.
34
+
35
+ pipeup skills install|remove|list [--project] [--agent claude|codex|all] [--yes] [--replace] [--dry-run]
18
36
  Puts Pipeup's agent skills where Claude Code (.claude/skills) and Codex (.agents/skills) look: for you, in every
19
37
  project, or with --project for this folder only. It says what it will write, asks first (--yes to go ahead without
20
38
  asking), and never replaces a skill you changed unless you say --replace.
@@ -183,6 +201,57 @@ else if (command === "skills") {
183
201
  } catch (e) {
184
202
  fail(e.message);
185
203
  }
204
+ } else if (command === "init") {
205
+ const page = args._[0];
206
+ if (!page) fail(`missing the page\n\n${USAGE}`);
207
+ // --addon may be given more than once: read every one from the raw arguments.
208
+ const addons = [];
209
+ for (let i = 0; i < rest.length; i++)
210
+ if (rest[i] === "--addon" && rest[i + 1] && !rest[i + 1].startsWith("--")) addons.push(rest[++i]);
211
+ const values = {};
212
+ for (const flag of ["inbox", "github-repo"]) if (typeof args[flag] === "string") values[flag] = args[flag];
213
+ const yes = args.yes === true;
214
+ const marks = args.marks === true;
215
+ try {
216
+ await init({
217
+ page,
218
+ yes,
219
+ dryRun: args["dry-run"] === true,
220
+ update: args.update === true,
221
+ offline: args.offline === true,
222
+ marks,
223
+ agent: args.agent === true,
224
+ addons,
225
+ values,
226
+ input: !yes || marks ? process.stdin : undefined,
227
+ });
228
+ } catch (e) {
229
+ console.error(`pipeup: ${e.message}`);
230
+ process.exit(e instanceof InitError ? e.code : 1);
231
+ }
232
+ } else if (command === "read") {
233
+ const page = args._[0];
234
+ if (!page) fail(`missing the page\n\n${USAGE}`);
235
+ const from = [];
236
+ for (let i = 0; i < rest.length; i++)
237
+ if (rest[i] === "--from" && rest[i + 1] && !rest[i + 1].startsWith("--")) from.push(rest[++i]);
238
+ try {
239
+ const { text, failed } = await read({
240
+ page,
241
+ from,
242
+ deep: args.deep === true,
243
+ all: args.all === true,
244
+ json: args.json === true,
245
+ share: args["no-share"] !== true,
246
+ out: typeof args.out === "string" ? args.out : undefined,
247
+ local: process.env.PIPEUP_SHARE_LOCAL === "1",
248
+ });
249
+ console.log(text);
250
+ process.exit(failed ? 1 : 0);
251
+ } catch (e) {
252
+ console.error(`pipeup: ${e.message}`);
253
+ process.exit(e instanceof ReadError ? e.code : 1);
254
+ }
186
255
  } else if (command === "check") {
187
256
  const page = args._[0];
188
257
  if (!page) fail(`missing the page\n\n${USAGE}`);
package/cli/read.mjs ADDED
@@ -0,0 +1,299 @@
1
+ // pipeup read: a page's comments without opening it (spec §15f): from feedback files, the page's shared copy and its
2
+ // replies file. Every comment goes through the same checks as in the page; the Markdown is Copy comments › As Markdown's.
3
+ import { readdir, readFile, stat, writeFile } from "node:fs/promises";
4
+ import { basename, dirname, join, resolve } from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+
7
+ const core = () => import("../dist/pipeup.core.js");
8
+ const MAX_MERGE = 5000;
9
+ const MAX_FILE = 5_000_000;
10
+
11
+ export class ReadError extends Error {
12
+ constructor(message, code = 2) {
13
+ super(message);
14
+ this.code = code;
15
+ }
16
+ }
17
+
18
+ const attrOf = (html, name) => {
19
+ const tag = /<html\b(?:[^>"']|"[^"]*"|'[^']*')*>/i.exec(html)?.[0] ?? "";
20
+ const m = new RegExp(`\\s${name}\\s*=\\s*("([^"]*)"|'([^']*)')`, "i").exec(tag);
21
+ return m ? (m[2] ?? m[3]).replace(/&quot;/g, '"').replace(/&amp;/g, "&") : null;
22
+ };
23
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
24
+
25
+ /** Where a thread is, from what the comment itself saved: no page is opened, so nothing is measured. */
26
+ function where(anchor) {
27
+ const parts = [];
28
+ if (anchor.view?.slide) parts.push(`Slide ${anchor.view.slide}`);
29
+ if (anchor.id) parts.push(`"${anchor.id}"`);
30
+ return {
31
+ where: parts.length ? parts.join(" › ") : `"${anchor.snapshot}"`,
32
+ element: null,
33
+ id: anchor.id ?? null,
34
+ quote: anchor.quote?.exact ?? null,
35
+ pin: anchor.point
36
+ ? `${Math.round(anchor.point.x * 100)}% across, ${Math.round(anchor.point.y * 100)}% down the element`
37
+ : null,
38
+ };
39
+ }
40
+
41
+ /** The feedback files in a folder (and the folders inside it with `deep`). */
42
+ async function filesIn(dir, deep) {
43
+ const out = [];
44
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
45
+ const path = join(dir, entry.name);
46
+ if (entry.isDirectory()) {
47
+ if (deep) out.push(...(await filesIn(path, deep)));
48
+ } else if (/\.(json|pipeup)$/i.test(entry.name)) out.push(path);
49
+ }
50
+ return out.sort();
51
+ }
52
+
53
+ /**
54
+ * The share add-on's headless reader, if it is installed: beside this package, or in the project the command runs in
55
+ * (as with `npx pipeup read` in a folder where `@pipeup/share` is installed). It is never a dependency of `pipeup`.
56
+ */
57
+ async function shareReader() {
58
+ try {
59
+ return await import("@pipeup/share/headless");
60
+ } catch {
61
+ for (let dir = process.cwd(); ; dir = dirname(dir)) {
62
+ const pkg = join(dir, "node_modules", "@pipeup", "share", "package.json");
63
+ try {
64
+ const entry = JSON.parse(await readFile(pkg, "utf8")).exports?.["./headless"]?.import;
65
+ if (entry) return await import(pathToFileURL(join(dirname(pkg), entry)).href);
66
+ } catch {
67
+ // not here
68
+ }
69
+ if (dirname(dir) === dir) return null;
70
+ }
71
+ }
72
+ }
73
+
74
+ /** What a feedback file's refusal means, in a few words. */
75
+ function why(message) {
76
+ if (/different document/.test(message)) return "another document's";
77
+ if (/sealed|could not be opened/.test(message)) return "can't be opened with this page's key";
78
+ if (/too large/.test(message)) return "too large";
79
+ return "not a feedback file";
80
+ }
81
+
82
+ /** The ops in a replies file (`(globalThis.pipeupReplies ||= []).push({...})`), read as data, never run. */
83
+ function repliesOps(text, docId) {
84
+ const ops = [];
85
+ for (const m of text.matchAll(/\.push\((\{[\s\S]*?\})\);?\s*(?=\(|$)/g)) {
86
+ try {
87
+ const file = JSON.parse(m[1]);
88
+ if (file?.format === "pipeup-replies" && file.doc === docId && Array.isArray(file.ops))
89
+ ops.push(...file.ops);
90
+ } catch {
91
+ // not a replies entry
92
+ }
93
+ }
94
+ return ops;
95
+ }
96
+
97
+ /**
98
+ * Reads the comments. o: { page, from: string[], deep, all, json, share, out, local, log }. Resolves to the text to
99
+ * print; what it read and left out goes to `log` (standard error), so the comments can be piped on their own.
100
+ */
101
+ export async function read(o) {
102
+ const log = o.log ?? ((line) => console.error(line));
103
+ let html;
104
+ try {
105
+ html = await readFile(o.page, "utf8");
106
+ } catch (e) {
107
+ throw new ReadError(`can't read ${o.page}: ${e.message}`, 1);
108
+ }
109
+ const attr = attrOf(html, "data-pipeup-doc");
110
+ if (!attr)
111
+ throw new ReadError(
112
+ "the page has no document identity (data-pipeup-doc), so no comments can be matched to it; run `pipeup init` first",
113
+ );
114
+ const {
115
+ PipeupDocument,
116
+ MemoryStore,
117
+ createIdentity,
118
+ parseDocumentAttribute,
119
+ readFeedbackFile,
120
+ agentComments,
121
+ } = await core();
122
+ let id;
123
+ let key;
124
+ try {
125
+ ({ id, key } = await parseDocumentAttribute(attr));
126
+ } catch (e) {
127
+ throw new ReadError(e.message.replace(/^pipeup: /, ""));
128
+ }
129
+ const doc = await PipeupDocument.open({
130
+ doc: id,
131
+ key,
132
+ store: new MemoryStore(),
133
+ identity: await createIdentity(),
134
+ name: "",
135
+ });
136
+ let found = 0;
137
+ let duplicates = 0;
138
+ let refused = 0;
139
+ /** Merges ops from one source, counting what was new, already there and refused. */
140
+ const take = async (ops, source) => {
141
+ const before = new Set(doc.ops().map((op) => op.body.id));
142
+ let added = 0;
143
+ for (let i = 0; i < ops.length; i += MAX_MERGE)
144
+ added += await doc.merge(ops.slice(i, i + MAX_MERGE), source);
145
+ const seen = ops.filter((op) => typeof op?.body?.id === "string" && before.has(op.body.id)).length;
146
+ found += ops.length;
147
+ duplicates += seen;
148
+ refused += Math.max(0, ops.length - added - seen);
149
+ return added;
150
+ };
151
+
152
+ // Feedback files, and folders of them.
153
+ let failed = false;
154
+ const files = [];
155
+ for (const from of o.from ?? []) {
156
+ let info;
157
+ try {
158
+ info = await stat(from);
159
+ } catch {
160
+ log(`Can't find ${from}.`);
161
+ failed = true;
162
+ continue;
163
+ }
164
+ if (info.isDirectory()) {
165
+ const inside = await filesIn(from, o.deep);
166
+ if (!inside.length)
167
+ log(`No feedback files in ${from}${o.deep ? "" : " (add --deep to look in the folders inside it)"}.`);
168
+ files.push(...inside.map((path) => ({ path, folder: true })));
169
+ } else files.push({ path: from, folder: false });
170
+ }
171
+ let read = 0;
172
+ const skipped = [];
173
+ for (const f of files) {
174
+ try {
175
+ if ((await stat(f.path)).size > MAX_FILE) throw new Error("too large");
176
+ const ops = await readFeedbackFile(await readFile(f.path, "utf8"), id, key);
177
+ await take(ops, "file");
178
+ read += 1;
179
+ } catch (e) {
180
+ skipped.push(`${f.folder ? basename(f.path) : f.path} (${why(e.message)})`);
181
+ if (!f.folder) failed = true;
182
+ }
183
+ }
184
+ if (files.length) {
185
+ log(`Read ${plural(read, "feedback file")}.`);
186
+ if (skipped.length) log(`Skipped ${plural(skipped.length, "file")}: ${skipped.join(", ")}.`);
187
+ }
188
+
189
+ // The replies file beside the page: replies from the agents the page lists.
190
+ const repliesPath = resolve(o.page).replace(/\.[^./\\]*$/, "") + ".replies.js";
191
+ let replies = null;
192
+ try {
193
+ replies = await readFile(repliesPath, "utf8");
194
+ } catch {
195
+ // none
196
+ }
197
+ if (replies !== null) {
198
+ const listed = (attrOf(html, "data-pipeup-agents") ?? "").split(/[\s,]+/).filter(Boolean);
199
+ const ops = repliesOps(replies, id);
200
+ const theirs = ops.filter((op) => listed.includes(op?.body?.author));
201
+ if (ops.length > theirs.length)
202
+ log(
203
+ `Left out ${plural(ops.length - theirs.length, "reply", "replies")} in ${basename(repliesPath)} from agents the page doesn't list.`,
204
+ );
205
+ await take(theirs, "replies");
206
+ log(`Read ${basename(repliesPath)}.`);
207
+ }
208
+
209
+ // The shared copy.
210
+ const share = attrOf(html, "data-pipeup-share");
211
+ if (share && o.share !== false) {
212
+ let host = "the sharing service";
213
+ try {
214
+ host = new URL(share.replace(/^[a-z]+:(?=https?:)/i, "").split("#")[0]).host || host;
215
+ } catch {
216
+ // the add-on reads the address; this is only for the sentence
217
+ }
218
+ log(`Reading the shared copy from ${host} (nothing is sent to it).`);
219
+ const headless = await shareReader();
220
+ if (!headless) {
221
+ log(
222
+ "Reading a shared copy needs the share add-on: npm i -D @pipeup/share, then run this again (or --no-share).",
223
+ );
224
+ failed = true;
225
+ }
226
+ if (headless) {
227
+ const ac = new AbortController();
228
+ try {
229
+ const link = await headless.connectShare(doc, {
230
+ share,
231
+ signal: ac.signal,
232
+ sendable: () => false,
233
+ local: o.local,
234
+ });
235
+ await link.flush(60_000);
236
+ // What arrives is merged in short batches after the read: wait until nothing more lands for half a second.
237
+ for (let n = -1, quiet = 0, t0 = Date.now(); quiet < 5 && Date.now() - t0 < 10_000;) {
238
+ await new Promise((r) => setTimeout(r, 100));
239
+ const now = doc.ops().length;
240
+ quiet = now === n ? quiet + 1 : 0;
241
+ n = now;
242
+ }
243
+ link.stop();
244
+ log("Read the shared copy.");
245
+ } catch (e) {
246
+ log(`Couldn't read the shared copy: ${e.message}`);
247
+ failed = true;
248
+ } finally {
249
+ ac.abort();
250
+ }
251
+ }
252
+ } else if (share) log("The page has a shared copy; it was not read (--no-share).");
253
+
254
+ if (duplicates)
255
+ log(
256
+ `${plural(duplicates, "comment change")} came from more than one place and ${duplicates === 1 ? "is" : "are"} shown once.`,
257
+ );
258
+ if (refused)
259
+ log(
260
+ `Left out ${plural(refused, "change")} that failed Pipeup's checks: not signed by the person named, altered after signing, or for another document.`,
261
+ );
262
+
263
+ const threads = doc.threads();
264
+ if (!threads.length && !found)
265
+ log(
266
+ "No comments found. Comments that are only in a reviewer's browser can't be read from here: they reach you by Copy comments › As Markdown, a feedback file, or sharing.",
267
+ );
268
+ // Page order: where the page marks the block, else where its quoted words (or what the reviewer saw) appear.
269
+ const order = (t) => {
270
+ const marked = t.anchor.id ? html.indexOf(`data-pipeup-id="${t.anchor.id}"`) : -1;
271
+ if (marked >= 0) return marked;
272
+ for (const words of [t.anchor.quote?.exact, t.anchor.snapshot?.slice(0, 40)]) {
273
+ const at = words ? html.indexOf(words.trim()) : -1;
274
+ if (at >= 0) return at;
275
+ }
276
+ return Number.MAX_SAFE_INTEGER;
277
+ };
278
+ const items = [...threads]
279
+ .sort((a, b) => order(a) - order(b) || a.root.at - b.root.at)
280
+ .map((thread) => ({ thread, location: where(thread.anchor) }));
281
+ const title = /<title[^>]*>([^<]*)<\/title>/i.exec(html)?.[1]?.trim() || basename(o.page);
282
+ const out = agentComments(items, {
283
+ title,
284
+ url: pathToFileURL(resolve(o.page)).href,
285
+ exportedAt: new Date(),
286
+ all: o.all,
287
+ });
288
+
289
+ if (o.out) {
290
+ try {
291
+ await writeFile(o.out, await doc.exportFile());
292
+ log(`Wrote every comment found to ${o.out}${key ? ", sealed for this document" : ""}.`);
293
+ } catch (e) {
294
+ throw new ReadError(`can't write ${o.out}: ${e.message}`, 1);
295
+ }
296
+ }
297
+ const text = o.json ? JSON.stringify(out, null, 2) : out.markdown;
298
+ return { text, failed };
299
+ }
@@ -0,0 +1,54 @@
1
+ {
2
+ "share": {
3
+ "integrity": "sha384-wql/NFYQR4jzJgnXOS/Ch9FC7wydHsfjDtacKSSwiglNCFsRHEAFu+NV77BtQK7a",
4
+ "says": "Sends the comments you choose to share, sealed so only people with this page can read them, to the sharing service the page names. That service sees when and how much is sent, and your network address."
5
+ },
6
+ "voice": {
7
+ "integrity": "sha384-eq8QijeWKjzubQyL1eH5khy4VFRKEyyQkJcsYg3U4brv8N8QsDKDwY+5XrNC7OKs",
8
+ "says": "Only when you press the microphone: your browser may download a speech pack once, and, only if it can't work on this device, your voice goes to the browser maker's speech service."
9
+ },
10
+ "live": {
11
+ "integrity": "sha384-RSVdnK2BRkBSTApk5bOpSe2DEDfk4I+g9yjaXioPnGv8t2L4N6TosjpEH1cSf0DF",
12
+ "says": "When you go live, you connect directly to other people viewing this page. They see your network address; the meeting-point services see your network address and when you connect, never your comments."
13
+ },
14
+ "assist": {
15
+ "integrity": "sha384-AScldYlxP5WwWHTGwyi6+2Z5+Hu7KM89zm7Yk8U9D3pOTsoBXPkteg2JlKy0BHAj",
16
+ "says": "Only after you turn it on: your browser may download a small AI model once. Comments and the page are read on this device and never sent anywhere; if the page's author named notes files, they are read from this site."
17
+ },
18
+ "agents": {
19
+ "integrity": "sha384-EnaJKckz3SQdlQBT68pWQHPibrJGW81iye5e8AGl/KhAVFyG0gRhxJxzhpG+vwDA",
20
+ "says": "Reads a replies file next to this page. When the page is shown through pipeup watch, and only after you switch it on, it sends this page's comments to the program running on this computer. Nothing leaves this computer."
21
+ },
22
+ "emoji": {
23
+ "integrity": "sha384-RSEPcw/wigVNhrEv3MnJtqr2eXSmQtteFrGlNxBKKi/zLG+PrB9V484tJImp0Acl",
24
+ "says": "Nothing is sent anywhere: the emoji are part of this script."
25
+ },
26
+ "github": {
27
+ "integrity": "sha384-NTSohG4/5QrH2JlSjsT4WBzWAIUe+CrgqG9kdDxd49TwdvKdhCXE+1LsE7jiLPvR",
28
+ "says": "Only when you press Mention on GitHub: your browser opens GitHub's new-issue page with the person's @name and the comment's words filled in; nothing is sent until you submit it there.",
29
+ "asks": {
30
+ "attr": "data-pipeup-github-repo",
31
+ "flag": "github-repo",
32
+ "what": "the repository the issues go to (owner/repo)",
33
+ "pattern": "^[A-Za-z0-9-]{1,39}/[A-Za-z0-9._-]{1,100}$"
34
+ }
35
+ },
36
+ "updates": {
37
+ "integrity": "sha384-tCLIdgybLTEfmrfkBV1cH3GSYTIXv/g9ivN7fBB2/hHkX+NdsyfMpTgSragOCaUP",
38
+ "says": "Checks the Pipeup project's published update list (GitHub Pages) once a day, only on this computer or where the page's author asked; that service can see your network address."
39
+ },
40
+ "inbox": {
41
+ "integrity": "sha384-7bQh3sG8fhxekWjQFsPogPesPzCLMzw0DmJPecvTdkG/KuXNSaJQWbTZ2GHfVNXV",
42
+ "says": "Only after you switch on Mentions by inbox: when you mention someone, a short note (who, your words, the page's address) is left for them at the page's inbox service, sealed so only they can read it; and your own inbox is checked there. The service sees that a note arrived, its size and when, and your network address, never who it is from or what it says.",
43
+ "asks": {
44
+ "attr": "data-pipeup-inbox",
45
+ "flag": "inbox",
46
+ "what": "the address of your inbox service (https://…)",
47
+ "pattern": "^https://\\S+$"
48
+ }
49
+ },
50
+ "identity": {
51
+ "integrity": "sha384-KTS/eDFIsZUSp67Ag+SdKf0+GbH9Z/O8T5boIE7MWASPnHjuyiWt8P2xX/VqWOK9",
52
+ "says": "Nothing. Your recovery code stays on this device unless you copy it or save it as a file yourself."
53
+ }
54
+ }
@@ -1,2 +1,2 @@
1
- "use strict";(()=>{function b(e){let t=globalThis;(t.pipeupAddons||=[]).push(e),typeof addEventListener=="function"&&addEventListener("load",()=>{t.Pipeup||console.error(`pipeup: the "${e.id}" add-on needs Pipeup on the page too; load pipeup.min.js.`)},{once:!0})}var re=2n**256n-2n**32n-977n;var L=/^\/__pipeup\/[A-Za-z0-9_-]{16,}$/;function P(e){let t=document.documentElement,n=t.getAttribute("data-pipeup-link")??"",s=L.test(n),o=!1,c=0,y=()=>{};async function r(){let d=!1;try{d=(await fetch(`${n}/comments`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(await e.snapshot())})).ok}catch{}if(!d)throw new Error("pipeup: the link to your agent isn't reachable; your comments are safe here")}let u=()=>{window.clearTimeout(c),y(),y=()=>{},o=!1};return{enabled:s,agent:t.getAttribute("data-pipeup-link-agent")??"",file:t.getAttribute("data-pipeup-link-file")??"",on:()=>o,set:async d=>{if(s){if(!d){u(),e.refresh();return}await r(),o=!0,y=e.changes(()=>{window.clearTimeout(c),c=window.setTimeout(()=>{r().catch(h=>{u(),e.refresh(),globalThis.reportError?.(h)})},300)}),e.refresh()}},destroy:u}}function T(e){let t=n=>n.replace(/\s+/g," ").trim();return[`Act on the review comments on this page, which uses Pipeup: ${t(e.title)} (${t(e.url)}).`,"",e.file?`1. Read the comments: \`npx pipeup comments ${e.file}\` (add --all for resolved ones). If it says nothing is shared, ask me to switch on Share with my agent.`:"1. Read the comments. Open the page in a browser and run `await Pipeup.comments()`, then read `.markdown`. If you can't run the page, ask me to paste its Copy as Markdown.","2. Work through the open threads in order. For each, make the change I approved, or say why you didn't. Ask me before changing anything I haven't approved, and answer a question with an answer.",e.replies?`3. Answer in each thread: \`npx pipeup reply --page ${e.file||"<the page's file>"} --thread <Thread id> "what you changed and where" --addressed "short note"\`. That writes ${t(e.replies)}.`+(e.listed?"":" The page doesn't list your key yet: run `npx pipeup agent --name <your name>` and tell me the attribute to add."):"3. Tell me what you would reply in each thread, in words I can paste.","4. Only mark a thread addressed. Never resolve, reopen, edit or delete: I close threads. Keep your key out of the page and its folder, and never answer as me.","","Guide: https://pipeup-ai.github.io/pipeup/skills/pipeup-apply/SKILL.md"].join(`
1
+ "use strict";(()=>{function b(e){let t=globalThis;(t.pipeupAddons||=[]).push(e),typeof addEventListener=="function"&&addEventListener("load",()=>{t.Pipeup||console.error(`pipeup: the "${e.id}" add-on needs Pipeup on the page too; load pipeup.min.js.`)},{once:!0})}var re=2n**256n-2n**32n-977n;var L=/^\/__pipeup\/[A-Za-z0-9_-]{16,}$/;function P(e){let t=document.documentElement,n=t.getAttribute("data-pipeup-link")??"",s=L.test(n),o=!1,c=0,y=()=>{};async function r(){let d=!1;try{d=(await fetch(`${n}/comments`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(await e.snapshot())})).ok}catch{}if(!d)throw new Error("pipeup: the link to your agent isn't reachable; your comments are safe here")}let u=()=>{window.clearTimeout(c),y(),y=()=>{},o=!1};return{enabled:s,agent:t.getAttribute("data-pipeup-link-agent")??"",file:t.getAttribute("data-pipeup-link-file")??"",on:()=>o,set:async d=>{if(s){if(!d){u(),e.refresh();return}await r(),o=!0,y=e.changes(()=>{window.clearTimeout(c),c=window.setTimeout(()=>{r().catch(h=>{u(),e.refresh(),globalThis.reportError?.(h)})},300)}),e.refresh()}},destroy:u}}function T(e){let t=n=>n.replace(/\s+/g," ").trim();return[`Act on the review comments on this page, which uses Pipeup: ${t(e.title)} (${t(e.url)}).`,"",e.file?`1. Read the comments: \`npx pipeup comments ${e.file}\` (add --all for resolved ones). If it says nothing is shared, ask me to switch on Share with my agent.`:"1. Read the comments. Open the page in a browser and run `await Pipeup.comments()`, then read `.markdown`. If you can't run the page, ask me to paste its comments (Copy comments \u203A As Markdown).","2. Work through the open threads in order. For each, make the change I approved, or say why you didn't. Ask me before changing anything I haven't approved, and answer a question with an answer.",e.replies?`3. Answer in each thread: \`npx pipeup reply --page ${e.file||"<the page's file>"} --thread <Thread id> "what you changed and where" --addressed "short note"\`. That writes ${t(e.replies)}.`+(e.listed?"":" The page doesn't list your key yet: run `npx pipeup agent --name <your name>` and tell me the attribute to add."):"3. Tell me what you would reply in each thread, in words I can paste.","4. Only mark a thread addressed. Never resolve, reopen, edit or delete: I close threads. Keep your key out of the page and its folder, and never answer as me.","","Guide: https://pipeup-ai.github.io/pipeup/skills/pipeup-apply/SKILL.md"].join(`
2
2
  `)}var C=/^[A-Za-z0-9_-]{43}$/,_="pipeupReplies";var D=/^AI assistant\s*·?\s*/;function x(e=document.documentElement){let t=e.getAttribute("data-pipeup-agents")??"";return[...new Set(t.split(/[\s,]+/).filter(n=>C.test(n)))]}function k(e=location,t=document.documentElement){let n=t.getAttribute("data-pipeup-replies");try{let s=e.href.split(/[?#]/)[0],o=new URL(n??(/\/$/.test(s)?`${s}index.replies.js`:s.replace(/\.[^./]*$/,"")+".replies.js"),e.href),c=o.protocol==="file:"?e.protocol==="file:":o.origin===e.origin;return c||console.warn("pipeup: the replies file must be on this site or this computer; ignoring it"),c?o.href:null}catch{return null}}function E(e){let t=x(),n=0,s="",o=null;async function c(){let l=globalThis[_];if(!Array.isArray(l))return 0;let p=l.splice(0),g=[];for(let f of p){let m=f;if(!(m?.format!=="pipeup-replies"||m.doc!==e.document.id||!Array.isArray(m.ops)))for(let i of m.ops){let a=i?.body;a&&t.includes(a.author)&&(a.kind==="reply"||a.kind==="addressed"||a.kind==="react"||a.kind==="unreact")?(g.push(i),(a.name==="AI assistant"||a.name.startsWith("AI assistant "))&&(s=a.name.replace(D,""))):n++}}return g.length?e.merge(g):0}function y(){let l=k();return l?(o?.remove(),new Promise((p,g)=>{let f=document.createElement("script");o=f,f.src=`${l}?${Date.now()}`;let m=a=>{window.clearTimeout(i),f.remove(),o===f&&(o=null),a?g(new Error(`pipeup: ${a}`)):p()},i=window.setTimeout(()=>m("the replies file didn't answer"),4e3);f.addEventListener("load",()=>m()),f.addEventListener("error",()=>m("there is no replies file yet")),e.overlay().append(f)})):Promise.reject(new Error("pipeup: the replies file can't be read from here"))}async function r(){if(!t.length)return 0;let l=await c();return await y(),l+await c()}let u=!1,d=()=>{u||document.hidden||(u=!0,r().catch(()=>{}).finally(()=>u=!1))},h=0;return t.length?(d(),h=window.setInterval(d,4e3),document.addEventListener("visibilitychange",d)):c(),{enabled:t.length>0,ignored:()=>n,who:()=>s,check:r,tally:l=>{let p=l.filter(i=>!i.resolved),g=i=>i.root.replies.some(a=>t.includes(a.author)),f=new Set(l.map(i=>i.id));return{stray:new Set(e.document.ops().filter(i=>t.includes(i.body.author)&&!f.has(i.body.thread)).map(i=>i.body.thread)).size,open:p.length,answered:p.filter(g).length,addressed:p.filter(i=>i.addressed).length}},destroy:()=>{window.clearInterval(h),document.removeEventListener("visibilitychange",d),o?.remove()}}}var R=()=>globalThis.Pipeup??{},H=["M10 8h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-8a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2z","M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"],N=["M21 12L3.5 4.5 6.2 12l-2.7 7.5zM6.2 12H13"],z="Reads a replies file next to this page. When the page is shown through pipeup watch, and only after you switch it on, it sends this page's comments to the program running on this computer. Nothing leaves this computer.",S=e=>e instanceof Error?e.message.replace(/^pipeup: /,""):"Something went wrong";async function K(e,t){try{await navigator.clipboard.writeText(e);return}catch{}let n=document.createElement("textarea");n.value=e,n.setAttribute("readonly",""),n.style.cssText="position:fixed;opacity:0;pointer-events:none",t.append(n),n.select();let s=document.execCommand("copy");if(n.remove(),!s)throw new Error("pipeup: your browser blocked copying")}function U(){return{id:"agents",api:1,version:"0.6.0",needs:["menu","status","notify","listnote"],network:{when:"page-configured",to:["page"],says:z},setup(e){let t=E(e),n=P({snapshot:async()=>{let r=R();if(!r.comments)throw new Error("pipeup: this page has no Pipeup to read comments from");let[u,d]=await Promise.all([r.comments(),r.comments({all:!0})]);return{v:1,at:new Date().toISOString(),title:document.title,open:u,all:d}},changes:r=>e.document.onChange(r),refresh:()=>o()}),s=()=>t.who()||n.agent,o=()=>{if(e.setStatus(t.enabled||n.enabled?{text:n.on()?`Sharing comments with ${s()||"your agent"}`:`${s()||"An AI agent"} can answer comments here`}:null),!t.enabled)return e.setListNote(null);let r=t.tally(e.document.threads()),u=s()||"An agent",d=r.answered?`${u} has answered ${r.answered} of ${r.open} open comments${r.addressed?`; ${r.addressed} ${r.addressed===1?"is":"are"} marked addressed`:""}`:"No replies from an agent yet",h=t.ignored(),l=(n.on()?`Sharing with ${n.agent||"your agent"} \xB7 `:"")+d+(h?` \xB7 ${h} from other writers ignored`:"")+(r.stray?` \xB7 replies for ${r.stray} comment${r.stray===1?"":"s"} this page doesn't have`:"");e.setListNote({text:l,action:{label:"Check for replies",run:async()=>{try{let p=await t.check();e.notify(p?`${p} new ${p===1?"reply":"replies"}`:"No new replies")}catch(p){e.notify(S(p))}finally{o()}}}})},c=[e.addMenuItem({id:"prompt",icon:H,label:()=>"Copy a prompt for my agent",hint:()=>"Tells an AI agent where the comments are and how to answer them",select:async()=>{try{await K(T({title:document.title,url:location.href,replies:k(),file:n.enabled?n.file:"",listed:x().length>0}),e.overlay()),e.notify("Copied a prompt for your agent")}catch(r){e.notify(S(r))}}})];n.enabled&&c.push(e.addMenuItem({id:"link",icon:N,label:()=>"Share with my agent",hint:()=>"Sends this page's comments to the program running on this computer, and nothing else",checked:()=>n.on(),select:async()=>{try{await n.set(!n.on())}catch(r){e.notify(S(r))}o()}}));let y=e.document.onChange(o);return o(),()=>{y(),t.destroy(),n.destroy()}}}}b(U());})();
@@ -1 +1 @@
1
- function e(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function t(e){let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function r(e){return(new TextEncoder).encode(e)}function n(e){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return"["+e.map(n).join(",")+"]";let t=e;return"{"+Object.keys(t).filter(e=>void 0!==t[e]).sort().map(e=>JSON.stringify(e)+":"+n(t[e])).join(",")+"}"}function i(e){return e.replace(/\s+/g," ").trim()}function o(e){let t=i(e),r=2166136261;for(let e=0;e<t.length;e++)r^=t.charCodeAt(e),r=Math.imul(r,16777619)>>>0;return r.toString(16).padStart(8,"0")}var a=/^[A-Za-z0-9_-]{43}$/,s=new Map;async function l(){let t=await crypto.subtle.generateKey({name:"Ed25519"},!1,["sign","verify"]);return{publicKey:e(new Uint8Array(await crypto.subtle.exportKey("raw",t.publicKey))),privateKey:t.privateKey}}async function d(t,r){let n=await crypto.subtle.sign({name:"Ed25519"},t.privateKey,r);return e(new Uint8Array(n))}var u="0123456789ABCDEFGHJKMNPQRSTVWXYZ";Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);var c=["Otter","Fox","Owl","Bear","Rabbit"],h=["Red","Orange","Yellow","Green","Teal","Blue","Purple","Pink","Brown","Grey"];function p(e){let t=2166136261;for(let r=0;r<e.length;r++)t=Math.imul(t^e.charCodeAt(r),16777619);return t=Math.imul(t^t>>>16,2246822507),t=Math.imul(t^t>>>13,3266489909),(t^t>>>16)>>>0}var f=e=>`${h[(e=>Math.floor(p(e)/c.length)%h.length)(e)]} ${c[(e=>p(e)%c.length)(e)]}`,m=e=>{let t=e.name.replace(/^AI assistant · /,"")||f(e.author);return e.alike?`${t} · ${function(e){let t=p(`id:${e}`),r="";for(let e=0;e<4;e++,t>>>=5)r+="0123456789ABCDEFGHJKMNPQRSTVWXYZ"[31&t];return r}(e.author)}`:t},g="AI assistant",y=e=>e===g||e.startsWith(`${g} `),w=1e4,b=2**40,x=2**47,v=1e4,k=/^[0-9a-f]{8}$/,A=/^[A-Za-z0-9_-]{43}$/,E=/^(?:[^\s@<>"]{1,64}@[^\s@<>"]{1,190}\.[^\s@<>"]{2,24}|gh:[A-Za-z0-9-]{1,39})$/,$=/^(?:[A-Za-z0-9_-]{43}|(?:host|gh):[A-Za-z0-9._@-]{1,64})$/,M=/^[A-Za-z0-9_-]{43}$/,S=new Set(["create","reply","edit","delete","resolve","reopen","addressed","react","unreact","seen","contact","uncontact"]),C=/^(?:\p{Regional_Indicator}{2}|[#*0-9]\uFE0F?\u20E3|\p{Extended_Pictographic}(?:\uFE0F|\p{Emoji_Modifier})?(?:\u200D\p{Extended_Pictographic}(?:\uFE0F|\p{Emoji_Modifier})?)*)$/u,N=e=>"string"==typeof e&&C.test(e)&&[...e].length<=16;async function O(e,t){if(e.author!==t.publicKey)throw new Error("pipeup: an op must be signed by its author");return{body:e,sig:await d(t,r(n(e)))}}var P=(e,t)=>"string"==typeof e&&e.length<=t,q=e=>!!e&&"object"==typeof e,j=e=>"number"==typeof e&&Number.isFinite(e)&&e>=0&&e<=1;function T(e){if(!q(e))return!1;let{id:t,path:r,fingerprint:n,snapshot:i,quote:o,point:a,view:s}=e;if(!(P(r,2e3)&&P(i,500)&&"string"==typeof n&&k.test(n)&&(void 0===t||P(t,200)&&""!==t)&&(void 0===o||q(o)&&P(o.exact,v)&&""!==o.exact&&P(o.prefix,64)&&P(o.suffix,64))&&(void 0===a||q(a)&&j(a.x)&&j(a.y))))return!1;if(void 0!==s){if(!q(s)||Array.isArray(s))return!1;let e=Object.entries(s);if(e.length>16||!e.every(([e,t])=>e.length<=64&&P(t,200)))return!1}return!0}function I(e){if(!q(e))return!1;let{body:t,sig:r}=e;if("string"!=typeof r||!q(t)||JSON.stringify({body:t,sig:r}).length>262144)return!1;let n=t;if(1!==n.v||"string"!=typeof n.id||!A.test(n.id)||!S.has(n.kind)||!P(n.doc,64)||""===n.doc||"string"!=typeof n.thread||!A.test(n.thread)||"string"!=typeof n.author||!M.test(n.author)||"string"!=typeof n.name||n.name.length>80||n.name!==n.name.trim()||"number"!=typeof n.clock||!Number.isSafeInteger(n.clock)||n.clock<1||n.clock>b||"number"!=typeof n.at||!Number.isSafeInteger(n.at)||n.at<0||n.at>x||void 0!==n.text&&(!P(n.text,w)||n.text!==n.text.trim())||void 0!==n.target&&("string"!=typeof n.target||!A.test(n.target))||("create"===n.kind||"reply"===n.kind||"edit"===n.kind||"addressed"===n.kind)&&!n.text||("reply"===n.kind||"edit"===n.kind||"delete"===n.kind)&&!n.target)return!1;if(void 0!==n.mentions){if("create"!==n.kind&&"reply"!==n.kind&&"edit"!==n.kind||!Array.isArray(n.mentions)||n.mentions.length>20)return!1;let e=n.text?.length??0;for(let t of n.mentions){if(!q(t)||!Number.isSafeInteger(t.start)||!Number.isSafeInteger(t.end))return!1;let{start:r,end:n,ref:i}=t;if(r<0||n<=r||n>e||"string"!=typeof i||!$.test(i))return!1}}return!(!("contact"!==n.kind||"string"==typeof n.text&&E.test(n.text))||"seen"===n.kind&&!n.target||!("react"!==n.kind&&"unreact"!==n.kind||n.target&&N(n.text))||!("create"!==n.kind||n.id===n.thread&&T(n.anchor)))}function F(i){return async function(r,n,i){if(!a.test(r))return!1;try{if(e(t(r))!==r)return!1;let o=s.get(r);if(!o){s.size>=512&&s.delete(s.keys().next().value),o=crypto.subtle.importKey("raw",t(r),{name:"Ed25519"},!0,["verify"]),s.set(r,o);let e=o;e.catch(()=>{s.get(r)===e&&s.delete(r)})}return await crypto.subtle.verify({name:"Ed25519"},await o,t(i),n)}catch{return!1}}(i.body.author,r(n(i.body)),i.sig)}function D(e,t){return e.body.clock!==t.body.clock?e.body.clock-t.body.clock:e.body.at!==t.body.at?e.body.at-t.body.at:e.body.author!==t.body.author?e.body.author<t.body.author?-1:1:e.body.id!==t.body.id?e.body.id<t.body.id?-1:1:0}function R(e,t,r,n,i,o){let a={id:e,author:t,name:r,text:n,at:i,edited:!1,deleted:!1,replies:[],reactions:[]};return o?.length&&(a.mentions=o),a}async function U(t){let i={...t,id:void 0,thread:"create"===t.kind?void 0:t.thread},o=await crypto.subtle.digest("SHA-256",r(n(i)));return e(new Uint8Array(o))}var K=class{constructor(e){this.doc=e}ops=new Map;clock=0;createAt=new Map;threadAt=new Map;get size(){return this.ops.size}all(){return[...this.ops.values()]}threads(){return function(e){let t=new Map,r=new Map,n=new Map;for(let{body:i}of[...e].sort(D)){if(i.name&&n.set(i.author,i.name),"create"===i.kind){if(t.has(i.id)||!i.anchor||void 0===i.text)continue;let e=R(i.id,i.author,i.name,i.text,i.at,i.mentions);t.set(i.id,{id:i.id,anchor:i.anchor,root:e,resolved:!1}),r.set(i.id,{comment:e,thread:i.id});continue}let e=t.get(i.thread);if(!e)continue;if("resolve"===i.kind||"reopen"===i.kind){e.resolved="resolve"===i.kind,"reopen"===i.kind&&delete e.addressed;continue}if("addressed"===i.kind){void 0!==i.text&&(e.addressed={text:i.text,author:i.author,name:i.name,at:i.at});continue}let o=i.target?r.get(i.target):void 0;if(o&&o.thread===i.thread){if("reply"===i.kind){if(r.has(i.id)||void 0===i.text)continue;let t=R(i.id,i.author,i.name,i.text,i.at,i.mentions);e.root.replies.push(t),r.set(i.id,{comment:t,thread:i.thread});continue}if("seen"===i.kind){let e=o.comment.seenBy??=[];e.includes(i.author)||e.push(i.author);continue}if("react"===i.kind||"unreact"===i.kind){if(void 0===i.text||o.comment.deleted)continue;let e=o.comment.reactions,t=e.find(e=>e.emoji===i.text);if("react"===i.kind){let r={author:i.author,name:i.name};t?t.by.some(e=>e.author===i.author)||t.by.push(r):e.length<12&&e.push({emoji:i.text,by:[r]})}else t&&(t.by=t.by.filter(e=>e.author!==i.author),t.by.length||e.splice(e.indexOf(t),1));continue}i.author!==o.comment.author||o.comment.deleted||("edit"===i.kind&&void 0!==i.text&&(o.comment.text=i.text,o.comment.edited=!0,i.mentions?o.comment.mentions=i.mentions:delete o.comment.mentions),"delete"===i.kind&&(o.comment.text="",o.comment.deleted=!0,o.comment.reactions=[],delete o.comment.mentions))}}for(let{comment:e}of r.values()){e.name||(e.unnamed=!0,e.name=n.get(e.author)??"");for(let t of e.reactions)for(let e of t.by)e.name||=n.get(e.author)??""}let i=new Map,o=(e,t)=>{let r=m({author:e,name:t}).toLowerCase();(i.get(r)??i.set(r,new Set).get(r)).add(e)};for(let{comment:e}of r.values()){o(e.author,e.name);for(let t of e.reactions)for(let e of t.by)o(e.author,e.name)}let a=(e,t)=>(i.get(m({author:e,name:t}).toLowerCase())?.size??0)>1;for(let{comment:e}of r.values()){a(e.author,e.name)&&(e.alike=!0);for(let t of e.reactions)for(let e of t.by)a(e.author,e.name)&&(e.alike=!0)}return[...t.values()]}(this.ops.values())}async add(e){let t=[];for(let r of e){if(!I(r)||r.body.doc!==this.doc||this.ops.has(r.body.id)||r.body.id!==await U(r.body)||!await F(r))continue;let e={body:r.body,sig:r.sig};this.ops.set(e.body.id,e),this.clock=Math.max(this.clock,e.body.clock),"create"===e.body.kind&&this.createAt.set(e.body.author,Math.max(this.createAt.get(e.body.author)??0,e.body.at)),this.threadAt.set(e.body.thread,Math.max(this.threadAt.get(e.body.thread)??0,e.body.at)),t.push(e)}return t}async append(e,t,r){let n={v:1,...r,id:"",thread:"create"===r.kind?"":r.thread,doc:this.doc,author:e.publicKey,name:t,clock:Math.min(this.clock+1,b),at:Math.min(Math.max(Date.now(),"create"===r.kind?(this.createAt.get(e.publicKey)??0)+1:(this.threadAt.get(r.thread)??0)+1),x)};n.id=await U(n);let i=this.ops.get(n.id);if(i)return i;"create"===n.kind&&(n.thread=n.id);let[o]=await this.add([await O(n,e)]);if(!o)throw new Error("pipeup: could not record this change");return o}},H=/^([A-Za-z0-9_-]{16}):([A-Za-z0-9_-]{43})$/;function L(){return`${function(t=16){return e(crypto.getRandomValues(new Uint8Array(t)))}(12)}:${e(crypto.getRandomValues(new Uint8Array(32)))}`}async function _(e){let r=H.exec(e.trim()),n=r?.[1],i=r?.[2];if(!n||!i)throw new Error('pipeup: data-pipeup-doc must look like "<id>:<key>", as made by newDocumentAttribute()');return{id:n,key:await crypto.subtle.importKey("raw",t(i),{name:"AES-GCM"},!1,["encrypt","decrypt"])}}async function z(t,n,i){let o=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:o,additionalData:r(i)},t,r(n));return{iv:e(o),data:e(new Uint8Array(a))}}var B=e=>`pipeup-file:${e}`;var G=/^[a-z][a-z0-9-]{1,23}\/[a-z][a-z0-9-]{0,31}$/,Z=class extends Error{constructor(e,t,r=1){super("pipeup: shown here, but not saved yet"),this.id=e,this.cause=t,this.count=r,this.name="UnsavedChangeError"}},J=class e{constructor(e,t){this.log=e,this.options=t,this.displayName=t.name.trim()?Q(t.name):""}listeners=new Set;cache=[];comments=new Map;displayName;e=Promise.resolve();unsaved=[];static async open(t){if("string"!=typeof t.doc||""===t.doc||t.doc.length>64)throw new Error("pipeup: the document id must be 1 to 64 characters");let r=new K(t.doc),n=await t.store.load(t.doc),i=n.length-(await r.add(n)).length;i&&console.warn(`pipeup: ${i} saved change${1===i?"":"s"} on this page couldn't be read; kept as saved`);let o=new e(r,t);return o.refresh(!1),o}get id(){return this.options.doc}get me(){return this.options.identity.publicKey}get name(){return this.displayName}set name(e){this.displayName=Q(e),this.refresh(!0,[],"")}threads(){return this.cache}ops(){return this.log.all()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}comment(e,t,r){return this.enqueue(()=>this.write({kind:"create",anchor:e,text:V(t),...r?.length?{mentions:r}:{}}))}reply(e,t,r){return this.enqueue(()=>this.write({kind:"reply",thread:this.find(e).thread,target:e,text:V(t),...r?.length?{mentions:r}:{}}))}edit(e,t,r){return this.enqueue(async()=>{let{thread:n}=this.mine(e);await this.write({kind:"edit",thread:n,target:e,text:V(t),...r?.length?{mentions:r}:{}})})}remove(e){return this.enqueue(async()=>{let{thread:t}=this.mine(e);await this.write({kind:"delete",thread:t,target:e})})}contact(e){let t=e.trim();return E.test(t)?this.enqueue(async()=>{await this.write({kind:"contact",thread:this.me,text:t})}):Promise.reject(new Error("pipeup: that isn't an email address or a GitHub name"))}uncontact(){return this.enqueue(async()=>{await this.write({kind:"uncontact",thread:this.me})})}contacts(){let e=new Map;for(let{body:t}of[...this.log.all()].sort(D))"contact"===t.kind&&t.text?e.set(t.author,t.text):"uncontact"===t.kind&&e.delete(t.author);return e}get portable(){return this.options.identity.privateKey.extractable}identityCode(){return async function(e){if(!e.privateKey.extractable)return null;let r=await crypto.subtle.exportKey("jwk",e.privateKey);return r.d?function(e){let t=(function(e){let t=0,r=0,n="";for(let i of e)for(r=r<<8|i,t+=8;t>=5;)n+=u[r>>>t-5&31],t-=5;return t&&(n+=u[r<<5-t&31]),n}(e)+function(e){let t=2166136261;for(let r of e)t=Math.imul(t^r,16777619);t=Math.imul(t^t>>>15,739982445);let r="";for(let e=0;e<4;e++,t>>>=5)r+=u[31&t];return r}(e)).match(/.{1,4}/g).join("-");return`PU1-${t}`}(t(r.d)):null}(this.options.identity)}seen(e){return this.enqueue(async()=>{for(let t of e){let e=this.comments.get(t);e&&!e.comment.seenBy?.includes(this.me)&&await this.write({kind:"seen",thread:e.thread,target:t})}})}react(e,t){return this.enqueue(async()=>{await this.write({kind:"react",thread:this.find(e).thread,target:e,text:W(t)})})}unreact(e,t){return this.enqueue(async()=>{await this.write({kind:"unreact",thread:this.find(e).thread,target:e,text:W(t)})})}resolve(e){return this.enqueue(async()=>{await this.write({kind:"resolve",thread:this.thread(e)})})}reopen(e){return this.enqueue(async()=>{await this.write({kind:"reopen",thread:this.thread(e)})})}sign(e,t){if(!G.test(e))throw new Error('pipeup: a signing purpose looks like "<add-on id>/<name>"');return d(this.options.identity,r(`pipeup:${e}\n${t}`))}flush(){return this.enqueue(()=>this.persist())}exportFile(){return async function(e,t,r){let n=r?{pipeup:1,doc:e,sealed:!0,...await z(r,JSON.stringify(t),B(e))}:{pipeup:1,doc:e,sealed:!1,ops:t};return JSON.stringify(n,null,2)}(this.options.doc,this.log.all(),this.options.key)}async importFile(e){return this.merge(await async function(e,n,i){if(e.length>5e6)throw new Error("pipeup: this feedback file is too large");let o,a,s;try{o=JSON.parse(e)}catch{throw new Error("pipeup: this is not an Pipeup feedback file")}if(!o||"object"!=typeof o||1!==o.pipeup||"string"!=typeof o.doc)throw new Error("pipeup: this is not an Pipeup feedback file");if(o.doc!==n)throw new Error("pipeup: this feedback is for a different document");if(!o.sealed)return Array.isArray(o.ops)?o.ops:[];if(!i)throw new Error("pipeup: this feedback is sealed, and this page has no document key");if("string"!=typeof o.iv||"string"!=typeof o.data)throw new Error("pipeup: this is not an Pipeup feedback file");try{a=await async function(e,n,i){try{let o=await crypto.subtle.decrypt({name:"AES-GCM",iv:t(n.iv),additionalData:r(i)},e,t(n.data));return(new TextDecoder).decode(o)}catch{throw new Error("pipeup: this feedback could not be opened with this document")}}(i,{iv:o.iv,data:o.data},B(n))}catch{throw new Error("pipeup: this feedback could not be opened with this document's key")}try{s=JSON.parse(a)}catch{throw new Error("pipeup: this is not an Pipeup feedback file")}return Array.isArray(s)?s:[]}(e,this.options.doc,this.options.key),"file")}merge(e,t){return e.length>5e3?Promise.reject(new RangeError("pipeup: too many changes to merge at once")):this.enqueue(async()=>{let r=await this.log.add([...e]);this.unsaved.push(...r),r.length>0&&this.refresh(!0,r,t);try{await this.persist()}catch(e){throw r.length>0?new Z(r[0].body.id,e,r.length):e}return r.length})}enqueue(e){let t=this.e.then(e);return this.e=t.catch(()=>{}),t}async write(e){let t=await this.log.append(this.options.identity,this.displayName,e);this.unsaved.push(t),this.refresh(!0,[t],"local");try{await this.persist()}catch(e){throw new Z(t.body.id,e)}return t.body.id}async persist(){if(0===this.unsaved.length)return;let e=[...this.unsaved];await this.options.store.append(this.options.doc,e),this.unsaved=this.unsaved.filter(t=>!e.includes(t))}refresh(e,t=[],r=""){this.cache=this.log.threads(),this.comments.clear();let n=(e,t)=>{e.unnamed&&e.author===this.me&&this.displayName&&(e.name=this.displayName),this.comments.set(e.id,{comment:e,thread:t});for(let r of e.replies)n(r,t)};for(let e of this.cache)n(e.root,e.id);if(e)for(let e of this.listeners)try{e(this.cache,t,r)}catch(e){globalThis.reportError?.(e)}}find(e){let t=this.comments.get(e);if(!t)throw new Error("pipeup: there is no comment with that id");return t}mine(e){let t=this.find(e);if(t.comment.author!==this.me)throw new Error("pipeup: only the writer can change a comment");return t}thread(e){if(!this.cache.some(t=>t.id===e))throw new Error("pipeup: there is no thread with that id");return e}};function V(e){let t=e.trim();if(!t)throw new Error("pipeup: a comment needs some words");if(t.length>w)throw new Error(`pipeup: comments are limited to ${w} characters`);return t}function W(e){if(!N(e))throw new Error("pipeup: a reaction is one emoji");return e}function Q(e){let t=e.replace(/\s+/g," ").trim();if(!t||t.length>80)throw new Error("pipeup: choose a name of 1 to 80 characters");if(y(t))throw new Error("pipeup: that name is kept for AI replies; choose another");return t}var X=class{docs=new Map;profile=null;async load(e){return[...this.docs.get(e)?.values()??[]]}async append(e,t){let r=this.docs.get(e);r||this.docs.set(e,r=new Map);for(let e of t)r.set(e.body.id,e)}async loadProfile(){return this.profile}async saveProfile(e){this.profile=e}async saveProfileIfAbsent(e){return this.profile||(this.profile=e),this.profile}},Y="";async function ee(e,t=""){let r=await e.loadProfile();if(r)return"Reviewer"===r.name?{...r,name:""}:r;let n={identity:await l(),name:t};return e.saveProfileIfAbsent(n)}var te=class e{constructor(e){this.db=e}static open(t="pipeup"){return new Promise((r,n)=>{let i=indexedDB.open(t,1);i.onupgradeneeded=()=>{let e=i.result;e.createObjectStore("ops",{keyPath:["doc","id"]}).createIndex("doc","doc"),e.createObjectStore("meta")},i.onsuccess=()=>{let t=i.result;t.onversionchange=()=>t.close(),r(new e(t))},i.onerror=()=>n(i.error??new Error("pipeup: could not open local storage"))})}close(){this.db.close()}async load(e){return(await this.request("ops","readonly",t=>t.index("doc").getAll(e))).map(e=>e.op)}async append(e,t){if(0===t.length)return;let r=this.db.transaction("ops","readwrite"),n=r.objectStore("ops"),i=re(r);try{for(let r of t)n.put({doc:e,id:r.body.id,op:r})}catch(e){throw r.abort(),i.catch(()=>{}),e}await i}async loadProfile(){return await this.request("meta","readonly",e=>e.get("profile"))??null}async saveProfile(e){await this.request("meta","readwrite",t=>t.put(e,"profile"))}async saveProfileIfAbsent(e){let t=this.db.transaction("meta","readwrite"),r=t.objectStore("meta"),n=re(t),i=e,o=r.get("profile");return o.onsuccess=()=>{o.result?i=o.result:r.put(e,"profile")},await n,i}request(e,t,r){return new Promise((n,i)=>{let o=r(this.db.transaction(e,t).objectStore(e));o.onsuccess=()=>n(o.result),o.onerror=()=>i(o.error??new Error("pipeup: local storage request failed"))})}};function re(e){return new Promise((t,r)=>{e.oncomplete=()=>t(),e.onerror=()=>r(e.error??new Error("pipeup: local storage write failed")),e.onabort=()=>r(e.error??new Error("pipeup: local storage write aborted"))})}function ne(e){let t=(e.ownerDocument??e).createTreeWalker(e,NodeFilter.SHOW_TEXT),r=[],n="";for(let e=t.nextNode();e;e=t.nextNode())r.push({node:e,start:n.length}),n+=e.data;return{text:n,nodes:r}}function ie(e,t,r){let n=(e.ownerDocument??e).createRange();return n.setStart(e,0),n.setEnd(t,r),n.toString().length}function oe(e,t,r){let n=ae(e,t,!1),i=ae(e,r,!0);if(!n||!i||r<t)return null;let o=n.node.ownerDocument.createRange();return o.setStart(n.node,n.offset),o.setEnd(i.node,i.offset),o}function ae(e,t,r){let n=e.nodes.find(e=>t>=e.start&&t<e.start+e.node.data.length+Number(r));return n&&{node:n.node,offset:t-n.start}}function se(e){return e.nodeType===Node.ELEMENT_NODE?e:e.parentElement}function le(e,t){for(let r=se(e)?.closest("[data-pipeup-id]")??null;r;){if(!t.contains(r))return null;let e=r.getAttribute("data-pipeup-id")??"";if(""!==e&&e.length<=200)return r;r=r.parentElement?.closest("[data-pipeup-id]")??null}return null}function de(e,t,r){return e.slice(t,r).replace(/^[\uDC00-\uDFFF]|[\uD800-\uDBFF]$/g,"")}function ue(e,t){let r=function(e,t){if(e===t)return"";let r=[];for(let n=t;n&&n!==e;n=n.parentElement){let e=1;for(let t=n.previousElementSibling;t;t=t.previousElementSibling)t.tagName===n.tagName&&e++;r.unshift(`${n.tagName.toLowerCase()}:nth-of-type(${e})`)}return":scope > "+r.join(" > ")}(e,t);if(r.length>2e3)throw new Error("pipeup: this element is nested too deeply to comment on — give a nearby container a data-pipeup-id");return r}function ce(e){if(!T(e))throw new Error("pipeup: could not describe this place on the page");return e}function he(e,t){let r=se(e),n=r?.closest("p,li,h1,h2,h3,h4,h5,h6,td,th,blockquote,pre,figcaption,dt,dd,summary,caption")??null;return n&&t.contains(n)?n:r&&t.contains(r)?r:t}function pe(e,t,r){if(!t.contains(e.commonAncestorContainer))throw new Error("pipeup: the selection is outside the commentable area");let n=le(e.commonAncestorContainer,t),a=n??t,{text:s}=ne(a),l=ie(a,e.startContainer,e.startOffset),d=ie(a,e.endContainer,e.endOffset),u=s.slice(l,d);if(""===u)throw new Error("pipeup: select some text to comment on");if(u.length>v)throw new Error("pipeup: selections are limited to 10000 characters");let c=de(s,Math.max(0,l-32),l),h=de(s,d,d+32);return ce({...n?{id:n.getAttribute("data-pipeup-id")??""}:{},path:"",quote:{exact:u,prefix:c,suffix:h},...r?{view:r}:{},fingerprint:o(he(e.startContainer,t).textContent??""),snapshot:de(i(c+u+h),0,200)})}function fe(e,t,r,n){let a=le(e,t);return ce({...a?{id:a.getAttribute("data-pipeup-id")??""}:{},path:ue(a??t,e),...r?{point:{x:me(r.x),y:me(r.y)}}:{},...n?{view:n}:{},fingerprint:o(e.textContent??""),snapshot:de(i(e.textContent??""),0,200)})}function me(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function ge(e,t,r){let n=Array.from({length:t.length+1},(e,t)=>t),i=[...n],o=[t.length];for(let a=1;a<=e.length;a++){i[0]=r?0:a;for(let r=1;r<=t.length;r++){let o=e.charCodeAt(a-1)===t.charCodeAt(r-1)?0:1;i[r]=Math.min(n[r]+1,i[r-1]+1,n[r-1]+o)}o.push(i[t.length]),[n,i]=[i,n]}return o}var ye=(e,t)=>ge(e,t,!1).pop(),we={state:"orphaned",element:null,range:null};function be(e,t,r={}){let n=e.id?function(e,t){for(let r of e.querySelectorAll("[data-pipeup-id]"))if(r.getAttribute("data-pipeup-id")===t)return r;return null}(t,e.id):t;return e.quote?function(e,t,r,n,i){let a=r??n,s=ne(a),l=function(e,t){if(!t.exact)return-1;let r=-1,n=-1;for(let i=e.indexOf(t.exact);-1!==i;i=e.indexOf(t.exact,i+1)){let o=e.slice(Math.max(0,i-t.prefix.length),i),a=e.slice(i+t.exact.length,i+t.exact.length+t.suffix.length),s=ve(o,t.prefix)+xe(a,t.suffix);s>n&&(r=i,n=s)}return r}(s.text,t);if(l>=0){let i=oe(s,l,l+t.exact.length);if(i){let t=he(i.startContainer,n);return{state:null!==r&&o(t.textContent??"")===e.fingerprint?"attached":"moved",element:t,range:i}}}if(i){let e=a===n?s:ne(n);if(e.text.length<=5e4&&t.exact.length>=12&&t.exact.length<=300){let r=function(e,t,r){let n=t.length;if(0===n)return null;let i=-1,o=1/0;if(ge(e,t,!0).forEach((e,t)=>{t&&e<o&&(o=e,i=t)}),o>r)return null;let a=Math.max(0,i-n),s=1/0;for(let o=Math.max(0,i-n-r);o<=Math.min(i,i-n+r);o++){let r=ye(e.slice(o,i),t);r<s&&(s=r,a=o)}return{start:a,end:i,distance:s}}(e.text,t.exact,Math.floor(t.exact.length/4)),i=r?oe(e,r.start,r.end):null;if(i)return{state:"moved",element:he(i.startContainer,n),range:i}}}return we}(e,e.quote,n,t,!1!==r.fuzzy):function(e,t){if(!t)return we;let r=t;if(e.path){if(!e.path.startsWith(":scope > "))return we;try{r=t.querySelector(e.path)}catch{return we}}return r?{state:o(r.textContent??"")===e.fingerprint?"attached":"moved",element:r,range:null}:we}(e,n)}function xe(e,t){let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)r++;return r}function ve(e,t){let r=0;for(;r<e.length&&r<t.length&&e[e.length-1-r]===t[t.length-1-r];)r++;return r}var ke={A:"Link",BUTTON:"Button",P:"Paragraph",LI:"List item",IMG:"Image",TABLE:"Table",TD:"Cell",TH:"Cell",FIGURE:"Figure",SVG:"Graphic",CANVAS:"Graphic",LABEL:"Label",INPUT:"Field",SELECT:"Field",TEXTAREA:"Field",SUMMARY:"Question",BLOCKQUOTE:"Quote",SECTION:"Section",H1:"Heading",H2:"Heading",H3:"Heading",H4:"Heading",H5:"Heading",H6:"Heading"};function Ae(e){return e.getAttribute("data-pipeup-label")||ke[e.tagName.toUpperCase()]||"Block"}function Ee(e){let t=e.getAttribute("data-pipeup-label");if(t)return t;let r=function(e){return Me(i(e.getAttribute("aria-label")??e.getAttribute("alt")??e.innerText??e.textContent??""),40)}(e);return r?`${Ae(e)} · ${r}`:Ae(e)}function $e(e,t,r){let n=e.id??null,o=e.quote?.exact??null,a=e.point?`${Math.round(100*e.point.x)}% across, ${Math.round(100*e.point.y)}% down the element`:null,s=t.element;if("orphaned"===t.state||!s)return{where:`No longer on the page (it read: "${e.snapshot}")`,element:null,id:n,quote:o,pin:a};let l=[],d=e.view?.slide;if(d){let e=s.closest("[data-pipeup-slide]")?.querySelector("h1,h2,h3")?.textContent;l.push(`Slide ${d}`+(e?` "${Me(i(e))}"`:""))}else{let t=function(e){return e?e.label||Object.entries(e).filter(([e,t])=>t&&"slide"!==e).map(([,e])=>e).join(" · "):""}(e.view);t&&l.push(t);let n=function(e,t){let r=null;for(let n of t.querySelectorAll("h1,h2,h3")){if(n===e||n.contains(e))break;if(!(4&n.compareDocumentPosition(e)))break;r=n}return r}(s,r);n&&l.push(`Section "${Me(i(n.textContent??""))}"`)}let u=Ee(s);return l.push(u),{where:l.join(" › "),element:u,id:n,quote:o,pin:a}}function Me(e,t=60){return e.length>t?e.slice(0,t-1)+"…":e}var Se="Each thread says where it is: the slide or section, the element (its data-pipeup-id attribute in the HTML), and the exact quoted text or pin position. Work through the open threads in order, and for each one say what you changed or why you did not. Answer in the thread (the Pipeup skill says how) and mark it addressed; never resolve it, the author does.";function Ce(e,t){let r=Math.max(0,Math.round((t-e)/1e3));if(r<60)return"just now";let n=Math.round(r/60);if(n<60)return`${n}m ago`;let i=Math.round(n/60);return i<48?`${i}h ago`:`${Math.round(i/24)}d ago`}function Ne(e,t,r,n){return"ai"===t?je(e,"## Comment thread",n,r):Te(e)}function Oe(e,t,r){let n=r.all?e:e.filter(e=>!e.thread.resolved);if("text"===t)return n.map(Te).join("\n");let i=r.all?0:e.length-n.length,o=[`# Review comments: ${qe(r.title)}`,"",`- **Page:** ${qe(r.url)}`,`- **Exported:** ${r.exportedAt.toISOString()}`,`- **Open threads:** ${e.length-e.filter(e=>e.thread.resolved).length}${i?` (${i} resolved, not included)`:r.all?" (resolved ones included)":""}`,"",Se,"",""].join("\n"),a=r.exportedAt.getTime();return o+n.map((e,t)=>je(e,`## Thread ${t+1}`,a)).join("\n")}function Pe(e){return e.reactions.map(e=>`${e.emoji} ${e.by.length} (${e.by.map(e=>qe(m(e))).join(", ")})`).join(" · ")}function qe(e){return e.replace(/\s+/g," ").trim()}function je(e,t,r,n){let{thread:i,location:o}=e,a=i.root.replies.length,s=[`${t} · ${i.resolved?"resolved":i.addressed?"open, addressed":"open"}`];if(s.push(`- **Thread:** ${i.id}`),n&&s.push(`- **Page:** ${qe(n)}`),s.push(`- **Where:** ${qe(o.where)}`),o.id){let e=qe(o.id.replace(/`/g,""));s.push(`- **Element:** \`[data-pipeup-id="${e}"]\`${o.element?` (${qe(o.element)})`:""}`)}o.quote&&s.push(`- **Quoted text:** "${qe(o.quote)}"`),o.pin&&s.push(`- **Pin:** ${qe(o.pin)}`),i.addressed&&!i.resolved&&s.push(`- **Addressed:** ${qe(i.addressed.text)} (${qe(m(i.addressed))}, ${Ce(i.addressed.at,r)})`),s.push(`- **Started by:** ${qe(m(i.root))}, ${Ce(i.root.at,r)}${a?` · ${a} ${1===a?"reply":"replies"}`:""}`,"",`**${qe(m(i.root))}** (${Ce(i.root.at,r)}): ${Ie(i.root," ")}`),i.root.reactions.length&&s.push(`Reactions: ${Pe(i.root)}`);for(let e of i.root.replies)s.push(`- **${qe(m(e))}** (${Ce(e.at,r)}): ${Ie(e," ")} \x3c!-- comment:${e.id} --\x3e`),e.reactions.length&&s.push(` - Reactions: ${Pe(e)}`);return s.join("\n")+"\n"}function Te(e){let{thread:t,location:r}=e,n=[qe(r.where)+(r.quote?`, on the text "${qe(r.quote)}"`:""),`${qe(m(t.root))}: ${Ie(t.root," ")}`];t.root.reactions.length&&n.push(` Reactions: ${Pe(t.root)}`);for(let e of t.root.replies)n.push(` ${qe(m(e))}: ${Ie(e," ")}`),e.reactions.length&&n.push(` Reactions: ${Pe(e)}`);return n.join("\n")+"\n"}function Ie(e,t){return e.deleted?"(deleted)":e.text.replace(/\r\n|\r|\n/g,"\n"+t)+(e.edited?" (edited)":"")}var Fe="0.7.0",De="2026-10-13";export{g as AI_NAME,c as ANIMALS,De as BUILT,h as COLOURS,Y as DEFAULT_PROFILE_NAME,te as IndexedDbStore,X as MemoryStore,J as PipeupDocument,Z as UnsavedChangeError,Fe as VERSION,f as animalName,U as computeOpId,Oe as copyAll,Ne as copyThread,l as createIdentity,fe as describeElement,pe as describeRange,Ce as formatAgo,y as isAiName,Ee as labelOf,ee as loadOrCreateProfile,$e as locate,m as nameOf,L as newDocumentAttribute,_ as parseDocumentAttribute,be as resolveAnchor,O as signOp};
1
+ function e(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function t(e){let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function r(e){return(new TextEncoder).encode(e)}function n(e){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return"["+e.map(n).join(",")+"]";let t=e;return"{"+Object.keys(t).filter(e=>void 0!==t[e]).sort().map(e=>JSON.stringify(e)+":"+n(t[e])).join(",")+"}"}function i(e){return e.replace(/\s+/g," ").trim()}function o(e){let t=i(e),r=2166136261;for(let e=0;e<t.length;e++)r^=t.charCodeAt(e),r=Math.imul(r,16777619)>>>0;return r.toString(16).padStart(8,"0")}var a=/^[A-Za-z0-9_-]{43}$/,s=new Map;async function d(){let t=await crypto.subtle.generateKey({name:"Ed25519"},!1,["sign","verify"]);return{publicKey:e(new Uint8Array(await crypto.subtle.exportKey("raw",t.publicKey))),privateKey:t.privateKey}}async function l(t,r){let n=await crypto.subtle.sign({name:"Ed25519"},t.privateKey,r);return e(new Uint8Array(n))}var u=["Otter","Fox","Owl","Bear","Rabbit"],c=["Red","Orange","Yellow","Green","Teal","Blue","Purple","Pink","Brown","Grey"];function h(e){let t=2166136261;for(let r=0;r<e.length;r++)t=Math.imul(t^e.charCodeAt(r),16777619);return t=Math.imul(t^t>>>16,2246822507),t=Math.imul(t^t>>>13,3266489909),(t^t>>>16)>>>0}var p=e=>`${c[(e=>Math.floor(h(e)/u.length)%c.length)(e)]} ${u[(e=>h(e)%u.length)(e)]}`,f=e=>{let t=e.name.replace(/^AI assistant \xb7 /,"")||p(e.author);return e.alike?`${t} \xb7 ${function(e){let t=h(`id:${e}`),r="";for(let e=0;e<4;e++,t>>>=5)r+="0123456789ABCDEFGHJKMNPQRSTVWXYZ"[31&t];return r}(e.author)}`:t},m="AI assistant",g=e=>e===m||e.startsWith(`${m} `),y=1e4,w=2**40,b=2**47,x=1e4,v=/^[0-9a-f]{8}$/,k=/^[A-Za-z0-9_-]{43}$/,A=/^(?:[^\s@<>"]{1,64}@[^\s@<>"]{1,190}\.[^\s@<>"]{2,24}|gh:[A-Za-z0-9-]{1,39})$/,E=/^(?:[A-Za-z0-9_-]{43}|(?:host|gh):[A-Za-z0-9._@-]{1,64})$/,$=/^[A-Za-z0-9_-]{43}$/,S=new Set(["create","reply","edit","delete","resolve","reopen","addressed","react","unreact","seen","contact","uncontact"]),M=/^(?:\p{Regional_Indicator}{2}|[#*0-9]\uFE0F?\u20E3|\p{Extended_Pictographic}(?:\uFE0F|\p{Emoji_Modifier})?(?:\u200D\p{Extended_Pictographic}(?:\uFE0F|\p{Emoji_Modifier})?)*)$/u,C=e=>"string"==typeof e&&M.test(e)&&[...e].length<=16;async function N(e,t){if(e.author!==t.publicKey)throw new Error("pipeup: an op must be signed by its author");return{body:e,sig:await l(t,r(n(e)))}}var q=(e,t)=>"string"==typeof e&&e.length<=t,O=e=>!!e&&"object"==typeof e,j=e=>"number"==typeof e&&Number.isFinite(e)&&e>=0&&e<=1;function P(e){if(!O(e))return!1;let{id:t,path:r,fingerprint:n,snapshot:i,quote:o,point:a,view:s}=e;if(!(q(r,2e3)&&q(i,500)&&"string"==typeof n&&v.test(n)&&(void 0===t||q(t,200)&&""!==t)&&(void 0===o||O(o)&&q(o.exact,x)&&""!==o.exact&&q(o.prefix,64)&&q(o.suffix,64))&&(void 0===a||O(a)&&j(a.x)&&j(a.y))))return!1;if(void 0!==s){if(!O(s)||Array.isArray(s))return!1;let e=Object.entries(s);if(e.length>16||!e.every(([e,t])=>e.length<=64&&q(t,200)))return!1}return!0}function T(e){if(!O(e))return!1;let{body:t,sig:r}=e;if("string"!=typeof r||!O(t)||JSON.stringify({body:t,sig:r}).length>262144)return!1;let n=t;if(1!==n.v||"string"!=typeof n.id||!k.test(n.id)||!S.has(n.kind)||!q(n.doc,64)||""===n.doc||"string"!=typeof n.thread||!k.test(n.thread)||"string"!=typeof n.author||!$.test(n.author)||"string"!=typeof n.name||n.name.length>80||n.name!==n.name.trim()||"number"!=typeof n.clock||!Number.isSafeInteger(n.clock)||n.clock<1||n.clock>w||"number"!=typeof n.at||!Number.isSafeInteger(n.at)||n.at<0||n.at>b||void 0!==n.text&&(!q(n.text,y)||n.text!==n.text.trim())||void 0!==n.target&&("string"!=typeof n.target||!k.test(n.target))||("create"===n.kind||"reply"===n.kind||"edit"===n.kind||"addressed"===n.kind)&&!n.text||("reply"===n.kind||"edit"===n.kind||"delete"===n.kind)&&!n.target)return!1;if(void 0!==n.mentions){if("create"!==n.kind&&"reply"!==n.kind&&"edit"!==n.kind||!Array.isArray(n.mentions)||n.mentions.length>20)return!1;let e=n.text?.length??0;for(let t of n.mentions){if(!O(t)||!Number.isSafeInteger(t.start)||!Number.isSafeInteger(t.end))return!1;let{start:r,end:n,ref:i}=t;if(r<0||n<=r||n>e||"string"!=typeof i||!E.test(i))return!1}}return!(!("contact"!==n.kind||"string"==typeof n.text&&A.test(n.text))||"seen"===n.kind&&!n.target||!("react"!==n.kind&&"unreact"!==n.kind||n.target&&C(n.text))||!("create"!==n.kind||n.id===n.thread&&P(n.anchor)))}function I(i){return async function(r,n,i){if(!a.test(r))return!1;try{if(e(t(r))!==r)return!1;let o=s.get(r);if(!o){s.size>=512&&s.delete(s.keys().next().value),o=crypto.subtle.importKey("raw",t(r),{name:"Ed25519"},!0,["verify"]),s.set(r,o);let e=o;e.catch(()=>{s.get(r)===e&&s.delete(r)})}return await crypto.subtle.verify({name:"Ed25519"},await o,t(i),n)}catch{return!1}}(i.body.author,r(n(i.body)),i.sig)}function F(e,t){return e.body.clock!==t.body.clock?e.body.clock-t.body.clock:e.body.at!==t.body.at?e.body.at-t.body.at:e.body.author!==t.body.author?e.body.author<t.body.author?-1:1:e.body.id!==t.body.id?e.body.id<t.body.id?-1:1:0}function D(e,t,r,n,i,o){let a={id:e,author:t,name:r,text:n,at:i,edited:!1,deleted:!1,replies:[],reactions:[]};return o?.length&&(a.mentions=o),a}async function R(t){let i={...t,id:void 0,thread:"create"===t.kind?void 0:t.thread},o=await crypto.subtle.digest("SHA-256",r(n(i)));return e(new Uint8Array(o))}var L=class{constructor(e){this.doc=e}ops=new Map;clock=0;createAt=new Map;threadAt=new Map;get size(){return this.ops.size}all(){return[...this.ops.values()]}threads(){return function(e){let t=new Map,r=new Map,n=new Map;for(let{body:i}of[...e].sort(F)){if(i.name&&n.set(i.author,i.name),"create"===i.kind){if(t.has(i.id)||!i.anchor||void 0===i.text)continue;let e=D(i.id,i.author,i.name,i.text,i.at,i.mentions);t.set(i.id,{id:i.id,anchor:i.anchor,root:e,resolved:!1}),r.set(i.id,{comment:e,thread:i.id});continue}let e=t.get(i.thread);if(!e)continue;if("resolve"===i.kind||"reopen"===i.kind){e.resolved="resolve"===i.kind,"reopen"===i.kind&&delete e.addressed;continue}if("addressed"===i.kind){void 0!==i.text&&(e.addressed={text:i.text,author:i.author,name:i.name,at:i.at});continue}let o=i.target?r.get(i.target):void 0;if(o&&o.thread===i.thread){if("reply"===i.kind){if(r.has(i.id)||void 0===i.text)continue;let t=D(i.id,i.author,i.name,i.text,i.at,i.mentions);e.root.replies.push(t),r.set(i.id,{comment:t,thread:i.thread});continue}if("seen"===i.kind){let e=o.comment.seenBy??=[];e.includes(i.author)||e.push(i.author);continue}if("react"===i.kind||"unreact"===i.kind){if(void 0===i.text||o.comment.deleted)continue;let e=o.comment.reactions,t=e.find(e=>e.emoji===i.text);if("react"===i.kind){let r={author:i.author,name:i.name};t?t.by.some(e=>e.author===i.author)||t.by.push(r):e.length<12&&e.push({emoji:i.text,by:[r]})}else t&&(t.by=t.by.filter(e=>e.author!==i.author),t.by.length||e.splice(e.indexOf(t),1));continue}i.author!==o.comment.author||o.comment.deleted||("edit"===i.kind&&void 0!==i.text&&(o.comment.text=i.text,o.comment.edited=!0,i.mentions?o.comment.mentions=i.mentions:delete o.comment.mentions),"delete"===i.kind&&(o.comment.text="",o.comment.deleted=!0,o.comment.reactions=[],delete o.comment.mentions))}}for(let{comment:e}of r.values()){e.name||(e.unnamed=!0,e.name=n.get(e.author)??"");for(let t of e.reactions)for(let e of t.by)e.name||=n.get(e.author)??""}let i=new Map,o=(e,t)=>{let r=f({author:e,name:t}).toLowerCase();(i.get(r)??i.set(r,new Set).get(r)).add(e)};for(let{comment:e}of r.values()){o(e.author,e.name);for(let t of e.reactions)for(let e of t.by)o(e.author,e.name)}let a=(e,t)=>(i.get(f({author:e,name:t}).toLowerCase())?.size??0)>1;for(let{comment:e}of r.values()){a(e.author,e.name)&&(e.alike=!0);for(let t of e.reactions)for(let e of t.by)a(e.author,e.name)&&(e.alike=!0)}return[...t.values()]}(this.ops.values())}async add(e){let t=[];for(let r of e){if(!T(r)||r.body.doc!==this.doc||this.ops.has(r.body.id)||r.body.id!==await R(r.body)||!await I(r))continue;let e={body:r.body,sig:r.sig};this.ops.set(e.body.id,e),this.clock=Math.max(this.clock,e.body.clock),"create"===e.body.kind&&this.createAt.set(e.body.author,Math.max(this.createAt.get(e.body.author)??0,e.body.at)),this.threadAt.set(e.body.thread,Math.max(this.threadAt.get(e.body.thread)??0,e.body.at)),t.push(e)}return t}async append(e,t,r){let n={v:1,...r,id:"",thread:"create"===r.kind?"":r.thread,doc:this.doc,author:e.publicKey,name:t,clock:Math.min(this.clock+1,w),at:Math.min(Math.max(Date.now(),"create"===r.kind?(this.createAt.get(e.publicKey)??0)+1:(this.threadAt.get(r.thread)??0)+1),b)};n.id=await R(n);let i=this.ops.get(n.id);if(i)return i;"create"===n.kind&&(n.thread=n.id);let[o]=await this.add([await N(n,e)]);if(!o)throw new Error("pipeup: could not record this change");return o}},U=/^([A-Za-z0-9_-]{16}):([A-Za-z0-9_-]{43})$/;function _(){return`${function(t=16){return e(crypto.getRandomValues(new Uint8Array(t)))}(12)}:${e(crypto.getRandomValues(new Uint8Array(32)))}`}async function z(e){let r=U.exec(e.trim()),n=r?.[1],i=r?.[2];if(!n||!i)throw new Error('pipeup: data-pipeup-doc must look like "<id>:<key>", as made by newDocumentAttribute()');return{id:n,key:await crypto.subtle.importKey("raw",t(i),{name:"AES-GCM"},!1,["encrypt","decrypt"])}}async function H(t,n,i){let o=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:o,additionalData:r(i)},t,r(n));return{iv:e(o),data:e(new Uint8Array(a))}}var K=e=>`pipeup-file:${e}`;async function B(e,n,i){if(e.length>5e6)throw new Error("pipeup: this feedback file is too large");let o,a,s;try{o=JSON.parse(e)}catch{throw new Error("pipeup: this is not an Pipeup feedback file")}if(!o||"object"!=typeof o||1!==o.pipeup||"string"!=typeof o.doc)throw new Error("pipeup: this is not an Pipeup feedback file");if(o.doc!==n)throw new Error("pipeup: this feedback is for a different document");if(!o.sealed)return Array.isArray(o.ops)?o.ops:[];if(!i)throw new Error("pipeup: this feedback is sealed, and this page has no document key");if("string"!=typeof o.iv||"string"!=typeof o.data)throw new Error("pipeup: this is not an Pipeup feedback file");try{a=await async function(e,n,i){try{let o=await crypto.subtle.decrypt({name:"AES-GCM",iv:t(n.iv),additionalData:r(i)},e,t(n.data));return(new TextDecoder).decode(o)}catch{throw new Error("pipeup: this feedback could not be opened with this document")}}(i,{iv:o.iv,data:o.data},K(n))}catch{throw new Error("pipeup: this feedback could not be opened with this document's key")}try{s=JSON.parse(a)}catch{throw new Error("pipeup: this is not an Pipeup feedback file")}return Array.isArray(s)?s:[]}var G=/^[a-z][a-z0-9-]{1,23}\/[a-z][a-z0-9-]{0,31}$/,Z=class extends Error{constructor(e,t,r=1){super("pipeup: shown here, but not saved yet"),this.id=e,this.cause=t,this.count=r,this.name="UnsavedChangeError"}},J=class e{constructor(e,t){this.log=e,this.options=t,this.displayName=t.name.trim()?Q(t.name):""}listeners=new Set;cache=[];comments=new Map;displayName;e=Promise.resolve();unsaved=[];static async open(t){if("string"!=typeof t.doc||""===t.doc||t.doc.length>64)throw new Error("pipeup: the document id must be 1 to 64 characters");let r=new L(t.doc),n=await t.store.load(t.doc),i=n.length-(await r.add(n)).length;i&&console.warn(`pipeup: ${i} saved change${1===i?"":"s"} on this page couldn't be read; kept as saved`);let o=new e(r,t);return o.refresh(!1),o}get id(){return this.options.doc}get me(){return this.options.identity.publicKey}get name(){return this.displayName}set name(e){this.displayName=Q(e),this.refresh(!0,[],"")}threads(){return this.cache}ops(){return this.log.all()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}comment(e,t,r){return this.enqueue(()=>this.write({kind:"create",anchor:e,text:V(t),...r?.length?{mentions:r}:{}}))}reply(e,t,r){return this.enqueue(()=>this.write({kind:"reply",thread:this.find(e).thread,target:e,text:V(t),...r?.length?{mentions:r}:{}}))}edit(e,t,r){return this.enqueue(async()=>{let{thread:n}=this.mine(e);await this.write({kind:"edit",thread:n,target:e,text:V(t),...r?.length?{mentions:r}:{}})})}remove(e){return this.enqueue(async()=>{let{thread:t}=this.mine(e);await this.write({kind:"delete",thread:t,target:e})})}contact(e){let t=e.trim();return A.test(t)?this.enqueue(async()=>{await this.write({kind:"contact",thread:this.me,text:t})}):Promise.reject(new Error("pipeup: that isn't an email address or a GitHub name"))}uncontact(){return this.enqueue(async()=>{await this.write({kind:"uncontact",thread:this.me})})}contacts(){let e=new Map;for(let{body:t}of[...this.log.all()].sort(F))"contact"===t.kind&&t.text?e.set(t.author,t.text):"uncontact"===t.kind&&e.delete(t.author);return e}get portable(){return this.options.identity.privateKey.extractable}async seed(){let e=this.options.identity.privateKey;if(!e.extractable)return null;let{d:r}=await crypto.subtle.exportKey("jwk",e);return r?t(r):null}seen(e){return this.enqueue(async()=>{for(let t of e){let e=this.comments.get(t);e&&!e.comment.seenBy?.includes(this.me)&&await this.write({kind:"seen",thread:e.thread,target:t})}})}react(e,t){return this.enqueue(async()=>{await this.write({kind:"react",thread:this.find(e).thread,target:e,text:W(t)})})}unreact(e,t){return this.enqueue(async()=>{await this.write({kind:"unreact",thread:this.find(e).thread,target:e,text:W(t)})})}resolve(e){return this.enqueue(async()=>{await this.write({kind:"resolve",thread:this.thread(e)})})}reopen(e){return this.enqueue(async()=>{await this.write({kind:"reopen",thread:this.thread(e)})})}sign(e,t){if(!G.test(e))throw new Error('pipeup: a signing purpose looks like "<add-on id>/<name>"');return l(this.options.identity,r(`pipeup:${e}\n${t}`))}flush(){return this.enqueue(()=>this.persist())}exportFile(){return async function(e,t,r){let n=r?{pipeup:1,doc:e,sealed:!0,...await H(r,JSON.stringify(t),K(e))}:{pipeup:1,doc:e,sealed:!1,ops:t};return JSON.stringify(n,null,2)}(this.options.doc,this.log.all(),this.options.key)}async importFile(e){return this.merge(await B(e,this.options.doc,this.options.key),"file")}merge(e,t){return e.length>5e3?Promise.reject(new RangeError("pipeup: too many changes to merge at once")):this.enqueue(async()=>{let r=await this.log.add([...e]);this.unsaved.push(...r),r.length>0&&this.refresh(!0,r,t);try{await this.persist()}catch(e){throw r.length>0?new Z(r[0].body.id,e,r.length):e}return r.length})}enqueue(e){let t=this.e.then(e);return this.e=t.catch(()=>{}),t}async write(e){let t=await this.log.append(this.options.identity,this.displayName,e);this.unsaved.push(t),this.refresh(!0,[t],"local");try{await this.persist()}catch(e){throw new Z(t.body.id,e)}return t.body.id}async persist(){if(0===this.unsaved.length)return;let e=[...this.unsaved];await this.options.store.append(this.options.doc,e),this.unsaved=this.unsaved.filter(t=>!e.includes(t))}refresh(e,t=[],r=""){this.cache=this.log.threads(),this.comments.clear();let n=(e,t)=>{e.unnamed&&e.author===this.me&&this.displayName&&(e.name=this.displayName),this.comments.set(e.id,{comment:e,thread:t});for(let r of e.replies)n(r,t)};for(let e of this.cache)n(e.root,e.id);if(e)for(let e of this.listeners)try{e(this.cache,t,r)}catch(e){globalThis.reportError?.(e)}}find(e){let t=this.comments.get(e);if(!t)throw new Error("pipeup: there is no comment with that id");return t}mine(e){let t=this.find(e);if(t.comment.author!==this.me)throw new Error("pipeup: only the writer can change a comment");return t}thread(e){if(!this.cache.some(t=>t.id===e))throw new Error("pipeup: there is no thread with that id");return e}};function V(e){let t=e.trim();if(!t)throw new Error("pipeup: a comment needs some words");if(t.length>y)throw new Error(`pipeup: comments are limited to ${y} characters`);return t}function W(e){if(!C(e))throw new Error("pipeup: a reaction is one emoji");return e}function Q(e){let t=e.replace(/\s+/g," ").trim();if(!t||t.length>80)throw new Error("pipeup: choose a name of 1 to 80 characters");if(g(t))throw new Error("pipeup: that name is kept for AI replies; choose another");return t}var X=class{docs=new Map;profile=null;async load(e){return[...this.docs.get(e)?.values()??[]]}async append(e,t){let r=this.docs.get(e);r||this.docs.set(e,r=new Map);for(let e of t)r.set(e.body.id,e)}async loadProfile(){return this.profile}async saveProfile(e){this.profile=e}async saveProfileIfAbsent(e){return this.profile||(this.profile=e),this.profile}},Y="";async function ee(e,t=""){let r=await e.loadProfile();if(r)return"Reviewer"===r.name?{...r,name:""}:r;let n={identity:await d(),name:t};return e.saveProfileIfAbsent(n)}var te=class e{constructor(e){this.db=e}static open(t="pipeup"){return new Promise((r,n)=>{let i=indexedDB.open(t,1);i.onupgradeneeded=()=>{let e=i.result;e.createObjectStore("ops",{keyPath:["doc","id"]}).createIndex("doc","doc"),e.createObjectStore("meta")},i.onsuccess=()=>{let t=i.result;t.onversionchange=()=>t.close(),r(new e(t))},i.onerror=()=>n(i.error??new Error("pipeup: could not open local storage"))})}close(){this.db.close()}async load(e){return(await this.request("ops","readonly",t=>t.index("doc").getAll(e))).map(e=>e.op)}async append(e,t){if(0===t.length)return;let r=this.db.transaction("ops","readwrite"),n=r.objectStore("ops"),i=re(r);try{for(let r of t)n.put({doc:e,id:r.body.id,op:r})}catch(e){throw r.abort(),i.catch(()=>{}),e}await i}async loadProfile(){return await this.request("meta","readonly",e=>e.get("profile"))??null}async saveProfile(e){await this.request("meta","readwrite",t=>t.put(e,"profile"))}async saveProfileIfAbsent(e){let t=this.db.transaction("meta","readwrite"),r=t.objectStore("meta"),n=re(t),i=e,o=r.get("profile");return o.onsuccess=()=>{o.result?i=o.result:r.put(e,"profile")},await n,i}request(e,t,r){return new Promise((n,i)=>{let o=r(this.db.transaction(e,t).objectStore(e));o.onsuccess=()=>n(o.result),o.onerror=()=>i(o.error??new Error("pipeup: local storage request failed"))})}};function re(e){return new Promise((t,r)=>{e.oncomplete=()=>t(),e.onerror=()=>r(e.error??new Error("pipeup: local storage write failed")),e.onabort=()=>r(e.error??new Error("pipeup: local storage write aborted"))})}function ne(e){let t=(e.ownerDocument??e).createTreeWalker(e,NodeFilter.SHOW_TEXT),r=[],n="";for(let e=t.nextNode();e;e=t.nextNode())r.push({node:e,start:n.length}),n+=e.data;return{text:n,nodes:r}}function ie(e,t,r){let n=(e.ownerDocument??e).createRange();return n.setStart(e,0),n.setEnd(t,r),n.toString().length}function oe(e,t,r){let n=ae(e,t,!1),i=ae(e,r,!0);if(!n||!i||r<t)return null;let o=n.node.ownerDocument.createRange();return o.setStart(n.node,n.offset),o.setEnd(i.node,i.offset),o}function ae(e,t,r){let n=e.nodes.find(e=>t>=e.start&&t<e.start+e.node.data.length+Number(r));return n&&{node:n.node,offset:t-n.start}}function se(e){return e.nodeType===Node.ELEMENT_NODE?e:e.parentElement}function de(e,t){for(let r=se(e)?.closest("[data-pipeup-id]")??null;r;){if(!t.contains(r))return null;let e=r.getAttribute("data-pipeup-id")??"";if(""!==e&&e.length<=200)return r;r=r.parentElement?.closest("[data-pipeup-id]")??null}return null}function le(e,t,r){return e.slice(t,r).replace(/^[\uDC00-\uDFFF]|[\uD800-\uDBFF]$/g,"")}function ue(e,t){let r=function(e,t){if(e===t)return"";let r=[];for(let n=t;n&&n!==e;n=n.parentElement){let e=1;for(let t=n.previousElementSibling;t;t=t.previousElementSibling)t.tagName===n.tagName&&e++;r.unshift(`${n.tagName.toLowerCase()}:nth-of-type(${e})`)}return":scope > "+r.join(" > ")}(e,t);if(r.length>2e3)throw new Error("pipeup: this element is nested too deeply to comment on \u2014 give a nearby container a data-pipeup-id");return r}function ce(e){if(!P(e))throw new Error("pipeup: could not describe this place on the page");return e}function he(e,t){let r=se(e),n=r?.closest("p,li,h1,h2,h3,h4,h5,h6,td,th,blockquote,pre,figcaption,dt,dd,summary,caption")??null;return n&&t.contains(n)?n:r&&t.contains(r)?r:t}function pe(e,t,r){if(!t.contains(e.commonAncestorContainer))throw new Error("pipeup: the selection is outside the commentable area");let n=de(e.commonAncestorContainer,t),a=n??t,{text:s}=ne(a),d=ie(a,e.startContainer,e.startOffset),l=ie(a,e.endContainer,e.endOffset),u=s.slice(d,l);if(""===u)throw new Error("pipeup: select some text to comment on");if(u.length>x)throw new Error("pipeup: selections are limited to 10000 characters");let c=le(s,Math.max(0,d-32),d),h=le(s,l,l+32);return ce({...n?{id:n.getAttribute("data-pipeup-id")??""}:{},path:"",quote:{exact:u,prefix:c,suffix:h},...r?{view:r}:{},fingerprint:o(he(e.startContainer,t).textContent??""),snapshot:le(i(c+u+h),0,200)})}function fe(e,t,r,n){let a=de(e,t);return ce({...a?{id:a.getAttribute("data-pipeup-id")??""}:{},path:ue(a??t,e),...r?{point:{x:me(r.x),y:me(r.y)}}:{},...n?{view:n}:{},fingerprint:o(e.textContent??""),snapshot:le(i(e.textContent??""),0,200)})}function me(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function ge(e,t,r){let n=Array.from({length:t.length+1},(e,t)=>t),i=[...n],o=[t.length];for(let a=1;a<=e.length;a++){i[0]=r?0:a;for(let r=1;r<=t.length;r++){let o=e.charCodeAt(a-1)===t.charCodeAt(r-1)?0:1;i[r]=Math.min(n[r]+1,i[r-1]+1,n[r-1]+o)}o.push(i[t.length]),[n,i]=[i,n]}return o}var ye=(e,t)=>ge(e,t,!1).pop(),we={state:"orphaned",element:null,range:null};function be(e,t,r={}){let n=e.id?function(e,t){for(let r of e.querySelectorAll("[data-pipeup-id]"))if(r.getAttribute("data-pipeup-id")===t)return r;return null}(t,e.id):t;return e.quote?function(e,t,r,n,i){let a=r??n,s=ne(a),d=function(e,t){if(!t.exact)return-1;let r=-1,n=-1;for(let i=e.indexOf(t.exact);-1!==i;i=e.indexOf(t.exact,i+1)){let o=e.slice(Math.max(0,i-t.prefix.length),i),a=e.slice(i+t.exact.length,i+t.exact.length+t.suffix.length),s=ve(o,t.prefix)+xe(a,t.suffix);s>n&&(r=i,n=s)}return r}(s.text,t);if(d>=0){let i=oe(s,d,d+t.exact.length);if(i){let t=he(i.startContainer,n);return{state:null!==r&&o(t.textContent??"")===e.fingerprint?"attached":"moved",element:t,range:i}}}if(i){let e=a===n?s:ne(n);if(e.text.length<=5e4&&t.exact.length>=12&&t.exact.length<=300){let r=function(e,t,r){let n=t.length;if(0===n)return null;let i=-1,o=1/0;if(ge(e,t,!0).forEach((e,t)=>{t&&e<o&&(o=e,i=t)}),o>r)return null;let a=Math.max(0,i-n),s=1/0;for(let o=Math.max(0,i-n-r);o<=Math.min(i,i-n+r);o++){let r=ye(e.slice(o,i),t);r<s&&(s=r,a=o)}return{start:a,end:i,distance:s}}(e.text,t.exact,Math.floor(t.exact.length/4)),i=r?oe(e,r.start,r.end):null;if(i)return{state:"moved",element:he(i.startContainer,n),range:i}}}return we}(e,e.quote,n,t,!1!==r.fuzzy):function(e,t){if(!t)return we;let r=t;if(e.path){if(!e.path.startsWith(":scope > "))return we;try{r=t.querySelector(e.path)}catch{return we}}return r?{state:o(r.textContent??"")===e.fingerprint?"attached":"moved",element:r,range:null}:we}(e,n)}function xe(e,t){let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)r++;return r}function ve(e,t){let r=0;for(;r<e.length&&r<t.length&&e[e.length-1-r]===t[t.length-1-r];)r++;return r}var ke={A:"Link",BUTTON:"Button",P:"Paragraph",LI:"List item",IMG:"Image",TABLE:"Table",TD:"Cell",TH:"Cell",FIGURE:"Figure",SVG:"Graphic",CANVAS:"Graphic",LABEL:"Label",INPUT:"Field",SELECT:"Field",TEXTAREA:"Field",SUMMARY:"Question",BLOCKQUOTE:"Quote",SECTION:"Section",H1:"Heading",H2:"Heading",H3:"Heading",H4:"Heading",H5:"Heading",H6:"Heading"};function Ae(e){return e.getAttribute("data-pipeup-label")||ke[e.tagName.toUpperCase()]||"Block"}function Ee(e){let t=e.getAttribute("data-pipeup-label");if(t)return t;let r=function(e){return Se(i(e.getAttribute("aria-label")??e.getAttribute("alt")??e.innerText??e.textContent??""),40)}(e);return r?`${Ae(e)} \xb7 ${r}`:Ae(e)}function $e(e,t,r){let n=e.id??null,o=e.quote?.exact??null,a=e.point?`${Math.round(100*e.point.x)}% across, ${Math.round(100*e.point.y)}% down the element`:null,s=t.element;if("orphaned"===t.state||!s)return{where:`No longer on the page (it read: "${e.snapshot}")`,element:null,id:n,quote:o,pin:a};let d=[],l=e.view?.slide;if(l){let e=s.closest("[data-pipeup-slide]")?.querySelector("h1,h2,h3")?.textContent;d.push(`Slide ${l}`+(e?` "${Se(i(e))}"`:""))}else{let t=function(e){return e?e.label||Object.entries(e).filter(([e,t])=>t&&"slide"!==e).map(([,e])=>e).join(" \xb7 "):""}(e.view);t&&d.push(t);let n=function(e,t){let r=null;for(let n of t.querySelectorAll("h1,h2,h3")){if(n===e||n.contains(e))break;if(!(4&n.compareDocumentPosition(e)))break;r=n}return r}(s,r);n&&d.push(`Section "${Se(i(n.textContent??""))}"`)}let u=Ee(s);return d.push(u),{where:d.join(" \u203a "),element:u,id:n,quote:o,pin:a}}function Se(e,t=60){return e.length>t?e.slice(0,t-1)+"\u2026":e}var Me="Each thread says where it is: the slide or section, the element (its data-pipeup-id attribute in the HTML), and the exact quoted text or pin position. Work through the open threads in order, and for each one say what you changed or why you did not. Answer in the thread (the Pipeup skill says how) and mark it addressed; never resolve it, the author does.";function Ce(e,t){let r=Math.max(0,Math.round((t-e)/1e3));if(r<60)return"just now";let n=Math.round(r/60);if(n<60)return`${n}m ago`;let i=Math.round(n/60);return i<48?`${i}h ago`:`${Math.round(i/24)}d ago`}function Ne(e,t,r,n){return"ai"===t?Pe(e,"## Comment thread",n,r):Te(e)}function qe(e,t,r){let n=r.all?e:e.filter(e=>!e.thread.resolved);if("text"===t)return n.map(Te).join("\n");let i=r.all?0:e.length-n.length,o=[`# Review comments: ${je(r.title)}`,"",`- **Page:** ${je(r.url)}`,`- **Exported:** ${r.exportedAt.toISOString()}`,`- **Open threads:** ${e.length-e.filter(e=>e.thread.resolved).length}${i?` (${i} resolved, not included)`:r.all?" (resolved ones included)":""}`,"",Me,"",""].join("\n"),a=r.exportedAt.getTime();return o+n.map((e,t)=>Pe(e,`## Thread ${t+1}`,a)).join("\n")}function Oe(e){return e.reactions.map(e=>`${e.emoji} ${e.by.length} (${e.by.map(e=>je(f(e))).join(", ")})`).join(" \xb7 ")}function je(e){return e.replace(/\s+/g," ").trim()}function Pe(e,t,r,n){let{thread:i,location:o}=e,a=i.root.replies.length,s=[`${t} \xb7 ${i.resolved?"resolved":i.addressed?"open, addressed":"open"}`];if(s.push(`- **Thread:** ${i.id}`),n&&s.push(`- **Page:** ${je(n)}`),s.push(`- **Where:** ${je(o.where)}`),o.id){let e=je(o.id.replace(/`/g,""));s.push(`- **Element:** \`[data-pipeup-id="${e}"]\`${o.element?` (${je(o.element)})`:""}`)}o.quote&&s.push(`- **Quoted text:** "${je(o.quote)}"`),o.pin&&s.push(`- **Pin:** ${je(o.pin)}`),i.addressed&&!i.resolved&&s.push(`- **Addressed:** ${je(i.addressed.text)} (${je(f(i.addressed))}, ${Ce(i.addressed.at,r)})`),s.push(`- **Started by:** ${je(f(i.root))}, ${Ce(i.root.at,r)}${a?` \xb7 ${a} ${1===a?"reply":"replies"}`:""}`,"",`**${je(f(i.root))}** (${Ce(i.root.at,r)}): ${Ie(i.root," ")}`),i.root.reactions.length&&s.push(`Reactions: ${Oe(i.root)}`);for(let e of i.root.replies)s.push(`- **${je(f(e))}** (${Ce(e.at,r)}): ${Ie(e," ")} \x3c!-- comment:${e.id} --\x3e`),e.reactions.length&&s.push(` - Reactions: ${Oe(e)}`);return s.join("\n")+"\n"}function Te(e){let{thread:t,location:r}=e,n=[je(r.where)+(r.quote?`, on the text "${je(r.quote)}"`:""),`${je(f(t.root))}: ${Ie(t.root," ")}`];t.root.reactions.length&&n.push(` Reactions: ${Oe(t.root)}`);for(let e of t.root.replies)n.push(` ${je(f(e))}: ${Ie(e," ")}`),e.reactions.length&&n.push(` Reactions: ${Oe(e)}`);return n.join("\n")+"\n"}function Ie(e,t){return e.deleted?"(deleted)":e.text.replace(/\r\n|\r|\n/g,"\n"+t)+(e.edited?" (edited)":"")}function Fe(e,t){return{markdown:qe(e,"ai",t),threads:e.filter(e=>t.all||!e.thread.resolved).map(({thread:e,location:t})=>{let r={id:e.id,state:e.resolved?"resolved":e.addressed?"addressed":"open",where:t.where,comments:[e.root,...e.root.replies].map(e=>({id:e.id,by:f(e),agent:g(e.name),at:new Date(e.at).toISOString(),text:e.deleted?"":e.text,...e.reactions.length?{reactions:e.reactions.map(e=>({emoji:e.emoji,by:e.by.map(f)}))}:{}}))};return t.id&&(r.element=t.id),t.quote&&(r.quote=t.quote),t.pin&&(r.pin=t.pin),e.addressed&&!e.resolved&&(r.addressed={note:e.addressed.text,by:f(e.addressed)}),r})}}var De="0.8.0-beta.2",Re="2026-10-15";export{m as AI_NAME,u as ANIMALS,Re as BUILT,c as COLOURS,Y as DEFAULT_PROFILE_NAME,te as IndexedDbStore,X as MemoryStore,J as PipeupDocument,Z as UnsavedChangeError,De as VERSION,Fe as agentComments,p as animalName,R as computeOpId,qe as copyAll,Ne as copyThread,d as createIdentity,fe as describeElement,pe as describeRange,Ce as formatAgo,g as isAiName,Ee as labelOf,ee as loadOrCreateProfile,$e as locate,f as nameOf,_ as newDocumentAttribute,z as parseDocumentAttribute,B as readFeedbackFile,be as resolveAnchor,N as signOp};