pipeup 0.8.0 → 0.8.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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Comments and feedback right on any HTML page: documents, slide decks and whole sites.
4
4
 
5
- > **Alpha (0.8.0).** The API and the stored comment format may change before 1.0; pin an exact version.
5
+ > **Alpha (0.8.2).** The API and the stored comment format may change before 1.0; pin an exact version.
6
6
  > Website and Try pages: https://pipeup-ai.github.io/pipeup/ · Source: https://github.com/pipeup-ai/pipeup
7
7
 
8
8
  Pipeup: signed comment operations, threads with one-level replies, anchors that survive page changes,
@@ -21,7 +21,7 @@ As a classic script (also works from `file://`), it mounts itself on pages that
21
21
  ```html
22
22
  <html data-pipeup-doc="<id>:<key>">
23
23
  ...
24
- <script src="https://cdn.jsdelivr.net/npm/pipeup@0.8.0/dist/pipeup.min.js" integrity="sha384-…" crossorigin="anonymous" defer></script>
24
+ <script src="https://cdn.jsdelivr.net/npm/pipeup@0.8.2/dist/pipeup.min.js" integrity="sha384-…" crossorigin="anonymous" defer></script>
25
25
  ```
26
26
 
27
27
  Each release's notes on GitHub give the `integrity` value
package/cli/init.mjs CHANGED
@@ -67,7 +67,7 @@ function attrSpan(tag, name) {
67
67
  const attrEnd = (tag) => tag.length - (/\s*\/?>$/.exec(tag)?.[0].length ?? 1);
68
68
 
69
69
  /** What the page already has: its <html> tag, Pipeup's script, add-ons. */
70
- function survey(html) {
70
+ export function survey(html) {
71
71
  const h = HTML_TAG.exec(html);
72
72
  if (!h) throw new InitError("the page has no <html> element; add one around the page and run this again");
73
73
  const found = { html: { at: h.index, tag: h[0] }, core: null, addons: new Map(), lastScriptEnd: -1 };
@@ -298,7 +298,7 @@ export function candidates(html) {
298
298
  }
299
299
 
300
300
  /** Applies edits (each { at, del, text }) from the end of the file back, so earlier offsets stay right. */
301
- function apply(html, edits) {
301
+ export function apply(html, edits) {
302
302
  let out = html;
303
303
  for (const e of [...edits].sort((a, b) => b.at - a.at || b.order - a.order))
304
304
  out = out.slice(0, e.at) + e.text + out.slice(e.at + (e.del ?? 0));
@@ -306,7 +306,7 @@ function apply(html, edits) {
306
306
  }
307
307
 
308
308
  /** Sets (or appends to) an attribute on the <html> start tag: returns the edit, or null when nothing changes. */
309
- function htmlAttr(found, name, value, { append = false } = {}) {
309
+ export function htmlAttr(found, name, value, { append = false } = {}) {
310
310
  const { at, tag } = found.html;
311
311
  const span = attrSpan(tag, name);
312
312
  if (!span) return { at: at + attrEnd(tag), text: ` ${name}="${escapeAttr(value)}"` };
package/cli/pipeup.mjs CHANGED
@@ -1,11 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  // pipeup agent / pipeup reply: how an AI agent answers comments on a Pipeup page.
3
3
  // The agent's key stays in ~/.pipeup/agent.json (owner-only) and never goes in the page or its folder.
4
- import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
4
+ import { chmod, mkdir, readdir, readFile, writeFile } from "node:fs/promises";
5
5
  import { homedir } from "node:os";
6
- import { basename, dirname, join, resolve } from "node:path";
6
+ import { basename, dirname, join, relative, resolve } from "node:path";
7
+ import { createInterface } from "node:readline/promises";
7
8
  import { check, table } from "./check.mjs";
8
- import { init, InitError } from "./init.mjs";
9
+ import { apply, htmlAttr, init, InitError, survey } from "./init.mjs";
9
10
  import { read, ReadError } from "./read.mjs";
10
11
  import { comments, watch } from "./link.mjs";
11
12
  import * as skills from "./skills.mjs";
@@ -41,9 +42,10 @@ pipeup check <page.html> [--json]
41
42
  Loads the page with and without Pipeup at 375, 768 and 1440 px (with Playwright, which you install) and says what
42
43
  Pipeup changes or covers, and what the page could do better: pass, WARN or FAIL for each. Exits 1 on any FAIL.
43
44
 
44
- pipeup agent [--name <name>]
45
+ pipeup agent [--name <name>] [--page <page.html>] [--yes]
45
46
  Makes this computer's agent key (once) and prints the public key to list on the page:
46
- <html data-pipeup-agents="<key>">
47
+ <html data-pipeup-agents="<key>">. With --page it lists the agent on that page itself: it shows the one change and
48
+ asks first (--yes to go ahead without asking; where it can't ask, it changes nothing and exits 2).
47
49
 
48
50
  pipeup watch <page.html> [--agent <name>] [--port <number>]
49
51
  Shows the page from this computer, with a live link to the agent: the page offers "Share with my agent"
@@ -55,8 +57,62 @@ pipeup comments <page.html> [--all] [--json]
55
57
  Prints the comments the page has shared (open threads, or all with --all), as Markdown or, with --json, as data.
56
58
 
57
59
  pipeup reply --page <file.html> --thread <id> "<words>" [--addressed "<short note>"]
58
- Writes a signed reply (and, with --addressed, an addressed note) to <file>.replies.js next to the page.
59
- It never resolves, reopens, edits or deletes anything: the author closes threads.`;
60
+ Writes a signed reply (and, with --addressed, an addressed note) where the page reads replies: <file>.replies.js
61
+ next to the page, or the file the page names. The page is the HTML file that runs Pipeup, never a file it shows.
62
+ It never resolves, reopens, edits or deletes anything: the author closes threads.
63
+
64
+ Agents run these as \`npx --yes pipeup@0 …\`: any release from 0.6 answers agent, reply and comments the same way.`;
65
+
66
+ /** How agents are told to run this command line: never stopping to ask, and any release npm will give. */
67
+ const RUN = "npx --yes pipeup@0";
68
+ /** A path as the person typed it, or relative to where they are. */
69
+ const shown = (file) => relative(process.cwd(), resolve(file)) || file;
70
+ const DOC = /<html\b[^>]*\sdata-pipeup-doc\s*=\s*["']([^"']+)["']/i;
71
+
72
+ /**
73
+ * The options each agent command knows: one this release doesn't know is said, and the rest carry on (a newer
74
+ * agent's command still works with an older release).
75
+ */
76
+ const KNOWN = {
77
+ agent: ["name", "page", "yes"],
78
+ reply: ["page", "thread", "addressed"],
79
+ comments: ["all", "json"],
80
+ watch: ["agent", "port"],
81
+ };
82
+ function unknown(command, args) {
83
+ for (const k of Object.keys(args))
84
+ if (k !== "_" && KNOWN[command] && !KNOWN[command].includes(k))
85
+ console.warn(`pipeup: this release doesn't know --${k}; carrying on without it`);
86
+ }
87
+
88
+ /** The HTML file nearest to `file` (its folder, then the folders above) that runs Pipeup, or null. */
89
+ async function nearbyPage(file) {
90
+ const self = resolve(file);
91
+ let dir = dirname(self);
92
+ for (let i = 0; i < 4; i++) {
93
+ const names = await readdir(dir).catch(() => []);
94
+ for (const n of names.filter((n) => /\.html?$/i.test(n)).sort()) {
95
+ const p = join(dir, n);
96
+ if (p !== self && DOC.test(await readFile(p, "utf8").catch(() => ""))) return p;
97
+ }
98
+ const up = dirname(dir);
99
+ if (up === dir) break;
100
+ dir = up;
101
+ }
102
+ return null;
103
+ }
104
+
105
+ /** `file` doesn't run Pipeup (a note a viewer shows, say): nothing is written, and the page nearby is named. */
106
+ async function notPipeup(file, what) {
107
+ const near = await nearbyPage(file);
108
+ console.error(`pipeup: ${shown(file)} doesn't run Pipeup, so ${what}.`);
109
+ console.error(
110
+ near
111
+ ? `The page that shows it is probably ${shown(near)}:\n --page ${shown(near)}`
112
+ : "Pass the HTML page the comments were left on: --page <page.html>",
113
+ );
114
+ process.exit(1);
115
+ }
60
116
 
61
117
  function fail(message) {
62
118
  console.error(`pipeup: ${message}`);
@@ -109,13 +165,26 @@ async function loadAgent(name) {
109
165
  /** A name that shows it is an agent: "AI assistant · Claude". */
110
166
  const signedName = (name) => (name && name !== AI ? `${AI} · ${name}`.slice(0, 80) : AI);
111
167
 
168
+ /** Reads a page: its text, or a plain failure when it can't be read. */
169
+ const readPage = (file) => readFile(file, "utf8").catch((e) => fail(`can't read ${file}: ${e.message}`));
170
+
112
171
  async function pageDoc(file) {
113
- const html = await readFile(file, "utf8");
114
- const m = /<html\b[^>]*\sdata-pipeup-doc\s*=\s*["']([^"']+)["']/i.exec(html);
115
- if (!m) fail(`${file} has no data-pipeup-doc attribute; add Pipeup to the page first`);
172
+ const html = await readPage(file);
173
+ const m = DOC.exec(html);
174
+ if (!m) await notPipeup(file, "nothing was written");
116
175
  const { id } = await (await core()).parseDocumentAttribute(m[1]);
117
176
  const listed = /<html\b[^>]*\sdata-pipeup-agents\s*=\s*["']([^"']*)["']/i.exec(html)?.[1] ?? "";
118
- return { id, listed: listed.split(/[\s,]+/).filter(Boolean) };
177
+ // Where the page reads replies: the file it names (a path beside it), else <page>.replies.js.
178
+ const given = /<html\b[^>]*\sdata-pipeup-replies\s*=\s*["']([^"']+)["']/i.exec(html)?.[1];
179
+ const local = given && !/^[a-z][\w+.-]*:|^\/\//i.test(given);
180
+ if (given && !local)
181
+ console.warn(
182
+ `pipeup: the page reads replies from ${given}, which isn't a file here; writing next to the page`,
183
+ );
184
+ const replies = local
185
+ ? resolve(dirname(file), given.split(/[?#]/)[0])
186
+ : resolve(file.replace(/\.[^./\\]*$/, "") + ".replies.js");
187
+ return { id, listed: listed.split(/[\s,]+/).filter(Boolean), replies };
119
188
  }
120
189
 
121
190
  const headerOf = (file) =>
@@ -139,17 +208,12 @@ async function reply(args) {
139
208
  if (typeof page !== "string" || typeof thread !== "string" || !words)
140
209
  fail(`missing words, --page or --thread\n\n${USAGE}`);
141
210
  const note = typeof args.addressed === "string" ? args.addressed.trim() : "";
142
- const { id: doc, listed } = await pageDoc(page);
211
+ const { id: doc, listed, replies: out } = await pageDoc(page);
143
212
  const { identity, name } = await loadAgent();
144
213
  const linked = await readFile(page.replace(/\.[^./\\]*$/, "") + ".comments.json", "utf8").then(
145
214
  () => true,
146
215
  () => false,
147
216
  );
148
- if (!listed.includes(identity.publicKey) && !linked)
149
- console.warn(
150
- `pipeup: this page doesn't list your key yet, so it will ignore these replies.\n Add: <html data-pipeup-agents="${identity.publicKey}">`,
151
- );
152
- const out = resolve(page.replace(/\.[^./\\]*$/, "") + ".replies.js");
153
217
  const ops = await readReplies(out, doc);
154
218
  // Seconds since 1970: later than any counter a browser has kept, so these follow the thread they answer.
155
219
  let clock = Math.max(Math.floor(Date.now() / 1000), ...ops.map((o) => o.body.clock + 1));
@@ -173,16 +237,57 @@ async function reply(args) {
173
237
  if (note) added.push(await make({ kind: "addressed", thread, text: note }));
174
238
  const file = { format: "pipeup-replies", v: 1, doc, ops: [...ops, ...added] };
175
239
  await writeFile(out, `${headerOf(page)}(globalThis.pipeupReplies ||= []).push(${JSON.stringify(file)});\n`);
176
- console.log(`Wrote ${added.length} ${added.length === 1 ? "entry" : "entries"} to ${out}`);
240
+ console.log(`Wrote ${added.length} ${added.length === 1 ? "entry" : "entries"} to ${shown(out)}.`);
241
+ // Written either way, so nothing is lost: the page shows them once it lists the agent.
242
+ if (!listed.includes(identity.publicKey) && !linked)
243
+ console.warn(
244
+ `The page will ignore them until it lists ${name || "your agent"}. Ask the page's author. After their yes, run:\n ${RUN} agent --page ${shown(page)} --yes`,
245
+ );
246
+ else console.log("The page reads this file: the reply shows in its thread within a few seconds.");
247
+ }
248
+
249
+ /**
250
+ * Lists the agent on a page: the one change (its key in data-pipeup-agents on <html>) is shown and asked about first;
251
+ * --yes goes ahead. Where it can't ask (an agent's shell, with nobody to answer), nothing changes and it exits 2.
252
+ */
253
+ async function listOn(page, identity, name, yes) {
254
+ const html = await readPage(page);
255
+ if (!DOC.test(html)) await notPipeup(page, "nothing was changed");
256
+ const found = survey(html);
257
+ const edit = htmlAttr(found, "data-pipeup-agents", identity.publicKey, { append: true });
258
+ if (!edit) return console.log(`${name} is already listed on ${shown(page)}; nothing was changed.`);
259
+ const next = apply(html, [{ ...edit, order: 0 }]);
260
+ console.log(
261
+ `\nThis ${edit.del ? `adds ${name}'s key to the page's agents` : "adds one attribute"} on ${shown(page)}, and changes nothing else:\n ${survey(next).html.tag}\n`,
262
+ );
263
+ if (!yes) {
264
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
265
+ console.log(
266
+ "This shell can't ask, so nothing was changed.\nAsk the page's author. After their yes, run it again with --yes.",
267
+ );
268
+ process.exitCode = 2;
269
+ return;
270
+ }
271
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
272
+ const answer = await rl.question("Add it? (y/N) ");
273
+ rl.close();
274
+ if (!/^y(es)?$/i.test(answer.trim())) return console.log("Nothing was changed.");
275
+ }
276
+ await writeFile(page, next);
277
+ console.log(`Listed ${name} on ${shown(page)}. Reload the page, and it shows ${name}'s replies.`);
177
278
  }
178
279
 
179
280
  const [command, ...rest] = process.argv.slice(2);
180
281
  const args = flags(rest);
282
+ unknown(command, args);
181
283
  if (command === "agent") {
182
284
  const { identity, name } = await loadAgent(args.name);
183
- console.log(
184
- `${name} (${KEYFILE})\n\nList this key on the page:\n <html data-pipeup-agents="${identity.publicKey}">`,
185
- );
285
+ console.log(`${name} (${KEYFILE})`);
286
+ if (typeof args.page === "string") await listOn(args.page, identity, name, args.yes === true);
287
+ else
288
+ console.log(
289
+ `\nList this key on the page:\n <html data-pipeup-agents="${identity.publicKey}">\nOr list it in one step: ${RUN} agent --page <page.html>`,
290
+ );
186
291
  } else if (command === "reply") await reply(args);
187
292
  else if (command === "skills") {
188
293
  const sub = args._[0];
@@ -299,7 +404,7 @@ else if (command === "skills") {
299
404
  else if (link.support === "builtin")
300
405
  console.log("This page's Pipeup (0.6) has agent support built in, so nothing is added to it.");
301
406
  console.log(
302
- `Read: npx pipeup comments ${page}\nReply: npx pipeup reply --page ${page} --thread <id> "words" --addressed "note"\nStop: Ctrl-C (comments stay in ${basename(link.sidecar)})`,
407
+ `Read: ${RUN} comments ${page}\nReply: ${RUN} reply --page ${page} --thread <id> "words" --addressed "note"\nStop: Ctrl-C (comments stay in ${basename(link.sidecar)})`,
303
408
  );
304
409
  const stop = () => link.close().then(() => process.exit(0));
305
410
  process.on("SIGINT", stop);
package/cli/read.mjs CHANGED
@@ -52,7 +52,7 @@ async function filesIn(dir, deep) {
52
52
 
53
53
  /**
54
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`.
55
+ * (as with `npx --yes pipeup@0 read` in a folder where `@pipeup/share` is installed). It is never a dependency of `pipeup`.
56
56
  */
57
57
  async function shareReader() {
58
58
  try {
package/dist/addons.json CHANGED
@@ -16,7 +16,7 @@
16
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
17
  },
18
18
  "agents": {
19
- "integrity": "sha384-GkGy8gt0VPnWdPQlinQuPktE6rY/upvyYi9veqIBpwFi3WnnMEOHpHu00vin350j",
19
+ "integrity": "sha384-5CVpIwX4Kz1uscPidtGqGlGuQrJ4Q/jCH8XXOoqyAcrrc7YSXrBJPiCmCQMh1+tg",
20
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
21
  },
22
22
  "emoji": {
@@ -1,2 +1,2 @@
1
- "use strict";(()=>{function b(e){let n=globalThis;(n.pipeupAddons||=[]).push(e),typeof addEventListener=="function"&&addEventListener("load",()=>{n.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 n=document.documentElement,t=n.getAttribute("data-pipeup-link")??"",i=L.test(t),o=!1,c=0,y=()=>{};async function r(){let d=!1;try{d=(await fetch(`${t}/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:i,agent:n.getAttribute("data-pipeup-link-agent")??"",file:n.getAttribute("data-pipeup-link-file")??"",on:()=>o,set:async d=>{if(i){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 n=o=>o.replace(/\s+/g," ").trim(),t=e.version?`npx pipeup@${e.version}`:"npx pipeup",i=`https://pipeup-ai.github.io/pipeup/${e.version?.includes("-")?"next/":""}`;return[`Act on the review comments on this page, which uses Pipeup: ${n(e.title)} (${n(e.url)}).`,"",e.file?`1. Read the comments: \`${t} 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: \`${t} reply --page ${e.file||"<the page's file>"} --thread <Thread id> "what you changed and where" --addressed "short note"\`. That writes ${n(e.replies)}.`+(e.listed?"":` The page doesn't list your key yet: run \`${t} 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: ${i}skills/pipeup-apply/SKILL.md`].join(`
2
- `)}var C=/^[A-Za-z0-9_-]{43}$/,_="pipeupReplies";var D=/^AI assistant\s*·?\s*/;function x(e=document.documentElement){let n=e.getAttribute("data-pipeup-agents")??"";return[...new Set(n.split(/[\s,]+/).filter(t=>C.test(t)))]}function k(e=location,n=document.documentElement){let t=n.getAttribute("data-pipeup-replies");try{let i=e.href.split(/[?#]/)[0],o=new URL(t??(/\/$/.test(i)?`${i}index.replies.js`:i.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 n=x(),t=0,i="",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 s of m.ops){let a=s?.body;a&&n.includes(a.author)&&(a.kind==="reply"||a.kind==="addressed"||a.kind==="react"||a.kind==="unreact")?(g.push(s),(a.name==="AI assistant"||a.name.startsWith("AI assistant "))&&(i=a.name.replace(D,""))):t++}}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(s),f.remove(),o===f&&(o=null),a?g(new Error(`pipeup: ${a}`)):p()},s=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(!n.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 n.length?(d(),h=window.setInterval(d,4e3),document.addEventListener("visibilitychange",d)):c(),{enabled:n.length>0,ignored:()=>t,who:()=>i,check:r,tally:l=>{let p=l.filter(s=>!s.resolved),g=s=>s.root.replies.some(a=>n.includes(a.author)),f=new Set(l.map(s=>s.id));return{stray:new Set(e.document.ops().filter(s=>n.includes(s.body.author)&&!f.has(s.body.thread)).map(s=>s.body.thread)).size,open:p.length,answered:p.filter(g).length,addressed:p.filter(s=>s.addressed).length}},destroy:()=>{window.clearInterval(h),document.removeEventListener("visibilitychange",d),o?.remove()}}}var R=()=>globalThis.Pipeup??{},N=["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"],H=["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,n){try{await navigator.clipboard.writeText(e);return}catch{}let t=document.createElement("textarea");t.value=e,t.setAttribute("readonly",""),t.style.cssText="position:fixed;opacity:0;pointer-events:none",n.append(t),t.select();let i=document.execCommand("copy");if(t.remove(),!i)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 n=E(e),t=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()}),i=()=>n.who()||t.agent,o=()=>{if(e.setStatus(n.enabled||t.enabled?{text:t.on()?`Sharing comments with ${i()||"your agent"}`:`${i()||"An AI agent"} can answer comments here`}:null),!n.enabled)return e.setListNote(null);let r=n.tally(e.document.threads()),u=i()||"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=n.ignored(),l=(t.on()?`Sharing with ${t.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 n.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:N,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:t.enabled?t.file:"",listed:x().length>0,version:globalThis.Pipeup?.VERSION}),e.overlay()),e.notify("Copied a prompt for your agent")}catch(r){e.notify(S(r))}}})];t.enabled&&c.push(e.addMenuItem({id:"link",icon:H,label:()=>"Share with my agent",hint:()=>"Sends this page's comments to the program running on this computer, and nothing else",checked:()=>t.on(),select:async()=>{try{await t.set(!t.on())}catch(r){e.notify(S(r))}o()}}));let y=e.document.onChange(o);return o(),()=>{y(),n.destroy(),t.destroy()}}}}b(U());})();
1
+ "use strict";(()=>{function b(e){let n=globalThis;(n.pipeupAddons||=[]).push(e),typeof addEventListener=="function"&&addEventListener("load",()=>{n.Pipeup||console.error(`pipeup: the "${e.id}" add-on needs Pipeup on the page too; load pipeup.min.js.`)},{once:!0})}var se=2n**256n-2n**32n-977n;var L=/^\/__pipeup\/[A-Za-z0-9_-]{16,}$/;function P(e){let n=document.documentElement,t=n.getAttribute("data-pipeup-link")??"",o=L.test(t),i=!1,a=0,m=()=>{};async function r(){let c=!1;try{c=(await fetch(`${t}/comments`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(await e.snapshot())})).ok}catch{}if(!c)throw new Error("pipeup: the link to your agent isn't reachable; your comments are safe here")}let d=()=>{window.clearTimeout(a),m(),m=()=>{},i=!1};return{enabled:o,agent:n.getAttribute("data-pipeup-link-agent")??"",file:n.getAttribute("data-pipeup-link-file")??"",on:()=>i,set:async c=>{if(o){if(!c){d(),e.refresh();return}await r(),i=!0,m=e.changes(()=>{window.clearTimeout(a),a=window.setTimeout(()=>{r().catch(y=>{d(),e.refresh(),globalThis.reportError?.(y)})},300)}),e.refresh()}},destroy:d}}function C(e){if(!e)return{cli:"npx --yes pipeup@0",fallback:null};let t=`npx --yes pipeup@${e.split(".")[0]??"0"}`;return e.includes("-")?{cli:`npx --yes pipeup@${e}`,fallback:t}:{cli:t,fallback:null}}function R(e,n=""){if(n)return{page:n,served:!1};try{let t=new URL(e),o=decodeURIComponent(t.pathname);return o.endsWith("/")&&(o+="index.html"),t.protocol==="file:"?{page:/^\/[A-Za-z]:\//.test(o)?o.slice(1):o,served:!1}:{page:o,served:!0}}catch{return{page:"<the page's HTML file>",served:!1}}}var _=e=>{try{let n=new URL(e);return n.protocol==="file:"?decodeURIComponent(n.pathname).replace(/^\/([A-Za-z]:\/)/,"$1"):n.href}catch{return e}};function T(e){let n=d=>d.replace(/\s+/g," ").trim(),{cli:t,fallback:o}=C(e.version),i=`https://pipeup-ai.github.io/pipeup/${e.version?.includes("-")?"next/":""}`,{page:a,served:m}=R(e.url,e.file),r=m?`<the HTML file your site serves at ${a}>`:a;return[`Act on the review comments on this page, which uses Pipeup: ${n(e.title)} (${n(e.url)}).`,"",e.file?`1. Read the comments: \`${t} 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: \`${t} reply --page ${r} --thread <Thread id> "what you changed and where" --addressed "short note"\`. Pass that file, the one that runs Pipeup, not a file it shows. It writes ${n(_(e.replies))}, which the page reads by itself.`+(e.listed?"":` The page doesn't list you yet. Ask me first; after my yes, run \`${t} agent --name <your name> --page ${r} --yes\`.`)+(o?` If npm refuses ${t.split(" ").at(-1)}, use ${o.split(" ").at(-1)}: it answers these commands the same way.`:""):"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: ${i}skills/pipeup-apply/SKILL.md`].join(`
2
+ `)}var D=/^[A-Za-z0-9_-]{43}$/,H="pipeupReplies";var N=/^AI assistant\s*·?\s*/;function x(e=document.documentElement){let n=e.getAttribute("data-pipeup-agents")??"";return[...new Set(n.split(/[\s,]+/).filter(t=>D.test(t)))]}function k(e=location,n=document.documentElement){let t=n.getAttribute("data-pipeup-replies");try{let o=e.href.split(/[?#]/)[0],i=new URL(t??(/\/$/.test(o)?`${o}index.replies.js`:o.replace(/\.[^./]*$/,"")+".replies.js"),e.href),a=i.protocol==="file:"?e.protocol==="file:":i.origin===e.origin;return a||console.warn("pipeup: the replies file must be on this site or this computer; ignoring it"),a?i.href:null}catch{return null}}function U(e){let n=x(),t=0,o="",i=null;async function a(){let u=globalThis[H];if(!Array.isArray(u))return 0;let l=u.splice(0),g=[];for(let f of l){let h=f;if(!(h?.format!=="pipeup-replies"||h.doc!==e.document.id||!Array.isArray(h.ops)))for(let s of h.ops){let p=s?.body;p&&n.includes(p.author)&&(p.kind==="reply"||p.kind==="addressed"||p.kind==="react"||p.kind==="unreact")?(g.push(s),(p.name==="AI assistant"||p.name.startsWith("AI assistant "))&&(o=p.name.replace(N,""))):t++}}return g.length?e.merge(g):0}function m(){let u=k();return u?(i?.remove(),new Promise((l,g)=>{let f=document.createElement("script");i=f,f.src=`${u}?${Date.now()}`;let h=p=>{window.clearTimeout(s),f.remove(),i===f&&(i=null),p?g(new Error(`pipeup: ${p}`)):l()},s=window.setTimeout(()=>h("the replies file didn't answer"),4e3);f.addEventListener("load",()=>h()),f.addEventListener("error",()=>h("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(!n.length)return 0;let u=await a();return await m(),u+await a()}let d=!1,c=()=>{d||document.hidden||(d=!0,r().catch(()=>{}).finally(()=>d=!1))},y=0;return n.length?(c(),y=window.setInterval(c,4e3),document.addEventListener("visibilitychange",c)):a(),{enabled:n.length>0,ignored:()=>t,who:()=>o,check:r,tally:u=>{let l=u.filter(s=>!s.resolved),g=s=>s.root.replies.some(p=>n.includes(p.author)),f=new Set(u.map(s=>s.id));return{stray:new Set(e.document.ops().filter(s=>n.includes(s.body.author)&&!f.has(s.body.thread)).map(s=>s.body.thread)).size,open:l.length,answered:l.filter(g).length,addressed:l.filter(s=>s.addressed).length}},destroy:()=>{window.clearInterval(y),document.removeEventListener("visibilitychange",c),i?.remove()}}}var z=()=>globalThis.Pipeup??{},K=["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"],j=["M21 12L3.5 4.5 6.2 12l-2.7 7.5zM6.2 12H13"],F="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 Z(e,n){try{await navigator.clipboard.writeText(e);return}catch{}let t=document.createElement("textarea");t.value=e,t.setAttribute("readonly",""),t.style.cssText="position:fixed;opacity:0;pointer-events:none",n.append(t),t.select();let o=document.execCommand("copy");if(t.remove(),!o)throw new Error("pipeup: your browser blocked copying")}function E(){return{id:"agents",api:1,version:"0.6.0",needs:["menu","status","notify","listnote"],network:{when:"page-configured",to:["page"],says:F},setup(e){let n=U(e),t=P({snapshot:async()=>{let r=z();if(!r.comments)throw new Error("pipeup: this page has no Pipeup to read comments from");let[d,c]=await Promise.all([r.comments(),r.comments({all:!0})]);return{v:1,at:new Date().toISOString(),title:document.title,open:d,all:c}},changes:r=>e.document.onChange(r),refresh:()=>i()}),o=()=>n.who()||t.agent,i=()=>{if(e.setStatus(n.enabled||t.enabled?{text:t.on()?`Sharing comments with ${o()||"your agent"}`:`${o()||"An AI agent"} can answer comments here`}:null),!n.enabled)return e.setListNote(null);let r=n.tally(e.document.threads()),d=o()||"An agent",c=r.answered?`${d} 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",y=n.ignored(),u=(t.on()?`Sharing with ${t.agent||"your agent"} \xB7 `:"")+c+(y?` \xB7 ${y} from other writers ignored`:"")+(r.stray?` \xB7 replies for ${r.stray} comment${r.stray===1?"":"s"} this page doesn't have`:"");e.setListNote({text:u,action:{label:"Check for replies",run:async()=>{try{let l=await n.check();e.notify(l?`${l} new ${l===1?"reply":"replies"}`:"No new replies")}catch(l){e.notify(S(l))}finally{i()}}}})},a=[e.addMenuItem({id:"prompt",icon:K,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 Z(T({title:document.title,url:location.href,replies:k(),file:t.enabled?t.file:"",listed:x().length>0,version:globalThis.Pipeup?.VERSION}),e.overlay()),e.notify("Copied a prompt for your agent")}catch(r){e.notify(S(r))}}})];t.enabled&&a.push(e.addMenuItem({id:"link",icon:j,label:()=>"Share with my agent",hint:()=>"Sends this page's comments to the program running on this computer, and nothing else",checked:()=>t.on(),select:async()=>{try{await t.set(!t.on())}catch(r){e.notify(S(r))}i()}}));let m=e.document.onChange(i);return i(),()=>{m(),n.destroy(),t.destroy()}}}}b(E());})();
@@ -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 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 O=(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 P(e){if(!q(e))return!1;let{id:t,path:r,fingerprint:n,snapshot:i,quote:o,point:a,view:s}=e;if(!(O(r,2e3)&&O(i,500)&&"string"==typeof n&&v.test(n)&&(void 0===t||O(t,200)&&""!==t)&&(void 0===o||q(o)&&O(o.exact,x)&&""!==o.exact&&O(o.prefix,64)&&O(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&&O(t,200)))return!1}return!0}function T(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||!k.test(n.id)||!S.has(n.kind)||!O(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&&(!O(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(!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||!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 L(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 D=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=L(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=L(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 B(){return`${function(t=16){return e(crypto.getRandomValues(new Uint8Array(t)))}(12)}:${e(crypto.getRandomValues(new Uint8Array(32)))}`}async function _(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 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 H=e=>`pipeup-file:${e}`;async function K(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},H(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 D(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 z(r,JSON.stringify(t),H(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 K(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",UL:"List",OL:"List",IMG:"Image",TABLE:"Table",TD:"Cell",TH:"Cell",FIGURE:"Figure",SVG:"Graphic",CANVAS:"Graphic",LABEL:"Label",INPUT:"Field",SELECT:"Dropdown",TEXTAREA:"Field",SUMMARY:"Disclosure",BLOCKQUOTE:"Quote",SECTION:"Section",ARTICLE:"Article",H1:"Heading",H2:"Heading",H3:"Heading",H4:"Heading",H5:"Heading",H6:"Heading",switch:"Switch",tab:"Tab",checkbox:"Checkbox",radio:"Radio button",button:"Button",submit:"Button",link:"Link"};function Ae(e){let t=e.getAttribute("role")??("INPUT"===e.tagName?e.type:""),r=e.getAttribute("data-pipeup-label")||Object.hasOwn(ke,t)&&ke[t]||ke[e.tagName.toUpperCase()];if(r)return r;if($e(e))return"Block";let n=e.getBoundingClientRect(),i=n.width/n.height;return i>1.4||i<.7?"Bar":"Shape"}var Ee=e=>e.innerText||e.textContent||"";function $e(e){let t=e,r=t.labels?.[0];return Ne(i(e.getAttribute("aria-label")??e.getAttribute("alt")??(r&&Ee(r))??("SELECT"===e.tagName?t.selectedOptions[0]?.text:null)??(t.placeholder||Ee(e))),40)}function Se(e){let t=e.getAttribute("data-pipeup-label");if(t)return t;let r=$e(e);return r?`${Ae(e)} \xb7 ${r}`:Ae(e)}function Me(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],.reveal .slides section")?.querySelector(Ce)?.textContent;d.push(`Slide ${l}`+(e?` "${Ne(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=e=>!1!==e.checkVisibility?.(),n=r(e),o=e=>i(e.textContent??"");for(let i=e;i&&i!==t;i=i.parentElement)for(let e=i.previousElementSibling;e;e=e.previousElementSibling){let t=e.matches(Ce)?e:[...e.querySelectorAll(Ce)].pop();if(t&&o(e)===o(t)&&(!n||r(t)))return t}return null}(s,r);n&&d.push(`Section "${Ne(i(n.textContent??""))}"`)}let u=Se(s);return d.push(u),{where:d.join(" \u203a "),element:u,id:n,within:!!n&&s.getAttribute("data-pipeup-id")!==n,quote:o,pin:a}}var Ce="h1,h2,h3";function Ne(e,t=60){return e.length>t?e.slice(0,t-1)+"\u2026":e}var Oe="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 qe(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 je(e,t,r,n){return"ai"===t?Fe(e,"## Comment thread",n,r):Le(e)}function Pe(e,t,r){let n=r.all?e:e.filter(e=>!e.thread.resolved);if("text"===t)return n.map(Le).join("\n");let i=r.all?0:e.length-n.length,o=[`# Review comments: ${Ie(r.title)}`,"",`- **Page:** ${Ie(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)":""}`,"",Oe,"",""].join("\n"),a=r.exportedAt.getTime();return o+n.map((e,t)=>Fe(e,`## Thread ${t+1}`,a)).join("\n")}function Te(e){return e.reactions.map(e=>`${e.emoji} ${e.by.length} (${e.by.map(e=>Ie(f(e))).join(", ")})`).join(" \xb7 ")}function Ie(e){return e.replace(/\s+/g," ").trim()}function Fe(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:** ${Ie(n)}`),s.push(`- **Where:** ${Ie(o.where)}`),o.id){let e=`\`[data-pipeup-id="${Ie(o.id.replace(/`/g,""))}"]\``;s.push("- **Element:** "+(o.within&&o.element?`${Ie(o.element)} in ${e}`:`${e}${o.element?` (${Ie(o.element)})`:""}`))}o.quote&&s.push(`- **Quoted text:** "${Ie(o.quote)}"`),o.pin&&s.push(`- **Pin:** ${Ie(o.pin)}`),i.addressed&&!i.resolved&&s.push(`- **Addressed:** ${Ie(i.addressed.text)} (${Ie(f(i.addressed))}, ${qe(i.addressed.at,r)})`),s.push(`- **Started by:** ${Ie(f(i.root))}, ${qe(i.root.at,r)}${a?` \xb7 ${a} ${1===a?"reply":"replies"}`:""}`,"",`**${Ie(f(i.root))}** (${qe(i.root.at,r)}): ${Re(i.root," ")}`),i.root.reactions.length&&s.push(`Reactions: ${Te(i.root)}`);for(let e of i.root.replies)s.push(`- **${Ie(f(e))}** (${qe(e.at,r)}): ${Re(e," ")} \x3c!-- comment:${e.id} --\x3e`),e.reactions.length&&s.push(` - Reactions: ${Te(e)}`);return s.join("\n")+"\n"}function Le(e){let{thread:t,location:r}=e,n=[Ie(r.where)+(r.quote?`, on the text "${Ie(r.quote)}"`:""),`${Ie(f(t.root))}: ${Re(t.root," ")}`];t.root.reactions.length&&n.push(` Reactions: ${Te(t.root)}`);for(let e of t.root.replies)n.push(` ${Ie(f(e))}: ${Re(e," ")}`),e.reactions.length&&n.push(` Reactions: ${Te(e)}`);return n.join("\n")+"\n"}function Re(e,t){return e.deleted?"(deleted)":e.text.replace(/\r\n|\r|\n/g,"\n"+t)+(e.edited?" (edited)":"")}function De(e,t){return{markdown:Pe(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 Ue="0.8.0",Be="2026-10-18";export{m as AI_NAME,u as ANIMALS,Be as BUILT,c as COLOURS,Y as DEFAULT_PROFILE_NAME,te as IndexedDbStore,X as MemoryStore,J as PipeupDocument,Z as UnsavedChangeError,Ue as VERSION,De as agentComments,p as animalName,R as computeOpId,Pe as copyAll,je as copyThread,d as createIdentity,fe as describeElement,pe as describeRange,qe as formatAgo,g as isAiName,Se as labelOf,ee as loadOrCreateProfile,Me as locate,f as nameOf,B as newDocumentAttribute,_ as parseDocumentAttribute,K as readFeedbackFile,be as resolveAnchor,N 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 O=(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 P(e){if(!q(e))return!1;let{id:t,path:r,fingerprint:n,snapshot:i,quote:o,point:a,view:s}=e;if(!(O(r,2e3)&&O(i,500)&&"string"==typeof n&&v.test(n)&&(void 0===t||O(t,200)&&""!==t)&&(void 0===o||q(o)&&O(o.exact,x)&&""!==o.exact&&O(o.prefix,64)&&O(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&&O(t,200)))return!1}return!0}function T(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||!k.test(n.id)||!S.has(n.kind)||!O(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&&(!O(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(!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||!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 L(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 D=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=L(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=L(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 B(){return`${function(t=16){return e(crypto.getRandomValues(new Uint8Array(t)))}(12)}:${e(crypto.getRandomValues(new Uint8Array(32)))}`}async function _(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 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 H=e=>`pipeup-file:${e}`;async function K(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},H(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 D(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 z(r,JSON.stringify(t),H(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 K(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",UL:"List",OL:"List",IMG:"Image",TABLE:"Table",TD:"Cell",TH:"Cell",FIGURE:"Figure",SVG:"Graphic",CANVAS:"Graphic",LABEL:"Label",INPUT:"Field",SELECT:"Dropdown",TEXTAREA:"Field",SUMMARY:"Disclosure",BLOCKQUOTE:"Quote",SECTION:"Section",ARTICLE:"Article",H1:"Heading",H2:"Heading",H3:"Heading",H4:"Heading",H5:"Heading",H6:"Heading",switch:"Switch",tab:"Tab",checkbox:"Checkbox",radio:"Radio button",button:"Button",submit:"Button",link:"Link"};function Ae(e){let t=e.getAttribute("role")??("INPUT"===e.tagName?e.type:""),r=e.getAttribute("data-pipeup-label")||Object.hasOwn(ke,t)&&ke[t]||ke[e.tagName.toUpperCase()];if(r)return r;if($e(e))return"Block";let n=e.getBoundingClientRect(),i=n.width/n.height;return i>1.4||i<.7?"Bar":"Shape"}var Ee=e=>e.innerText||e.textContent||"";function $e(e){let t=e,r=t.labels?.[0];return Ne(i(e.getAttribute("aria-label")??e.getAttribute("alt")??(r&&Ee(r))??("SELECT"===e.tagName?t.selectedOptions[0]?.text:null)??(t.placeholder||Ee(e))),40)}function Se(e){let t=e.getAttribute("data-pipeup-label");if(t)return t;let r=$e(e);return r?`${Ae(e)} \xb7 ${r}`:Ae(e)}function Me(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],.reveal .slides section")?.querySelector(Ce)?.textContent;d.push(`Slide ${l}`+(e?` "${Ne(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=e=>!1!==e.checkVisibility?.(),n=r(e),o=e=>i(e.textContent??"");for(let i=e;i&&i!==t;i=i.parentElement)for(let e=i.previousElementSibling;e;e=e.previousElementSibling){let t=e.matches(Ce)?e:[...e.querySelectorAll(Ce)].pop();if(t&&o(e)===o(t)&&(!n||r(t)))return t}return null}(s,r);n&&d.push(`Section "${Ne(i(n.textContent??""))}"`)}let u=Se(s);return d.push(u),{where:d.join(" \u203a "),element:u,id:n,within:!!n&&s.getAttribute("data-pipeup-id")!==n,quote:o,pin:a}}var Ce="h1,h2,h3";function Ne(e,t=60){return e.length>t?e.slice(0,t-1)+"\u2026":e}var Oe="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 qe(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 je(e,t,r,n){return"ai"===t?Fe(e,"## Comment thread",n,r):Le(e)}function Pe(e,t,r){let n=r.all?e:e.filter(e=>!e.thread.resolved);if("text"===t)return n.map(Le).join("\n");let i=r.all?0:e.length-n.length,o=[`# Review comments: ${Ie(r.title)}`,"",`- **Page:** ${Ie(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)":""}`,"",Oe,"",""].join("\n"),a=r.exportedAt.getTime();return o+n.map((e,t)=>Fe(e,`## Thread ${t+1}`,a)).join("\n")}function Te(e){return e.reactions.map(e=>`${e.emoji} ${e.by.length} (${e.by.map(e=>Ie(f(e))).join(", ")})`).join(" \xb7 ")}function Ie(e){return e.replace(/\s+/g," ").trim()}function Fe(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:** ${Ie(n)}`),s.push(`- **Where:** ${Ie(o.where)}`),o.id){let e=`\`[data-pipeup-id="${Ie(o.id.replace(/`/g,""))}"]\``;s.push("- **Element:** "+(o.within&&o.element?`${Ie(o.element)} in ${e}`:`${e}${o.element?` (${Ie(o.element)})`:""}`))}o.quote&&s.push(`- **Quoted text:** "${Ie(o.quote)}"`),o.pin&&s.push(`- **Pin:** ${Ie(o.pin)}`),i.addressed&&!i.resolved&&s.push(`- **Addressed:** ${Ie(i.addressed.text)} (${Ie(f(i.addressed))}, ${qe(i.addressed.at,r)})`),s.push(`- **Started by:** ${Ie(f(i.root))}, ${qe(i.root.at,r)}${a?` \xb7 ${a} ${1===a?"reply":"replies"}`:""}`,"",`**${Ie(f(i.root))}** (${qe(i.root.at,r)}): ${Re(i.root," ")}`),i.root.reactions.length&&s.push(`Reactions: ${Te(i.root)}`);for(let e of i.root.replies)s.push(`- **${Ie(f(e))}** (${qe(e.at,r)}): ${Re(e," ")} \x3c!-- comment:${e.id} --\x3e`),e.reactions.length&&s.push(` - Reactions: ${Te(e)}`);return s.join("\n")+"\n"}function Le(e){let{thread:t,location:r}=e,n=[Ie(r.where)+(r.quote?`, on the text "${Ie(r.quote)}"`:""),`${Ie(f(t.root))}: ${Re(t.root," ")}`];t.root.reactions.length&&n.push(` Reactions: ${Te(t.root)}`);for(let e of t.root.replies)n.push(` ${Ie(f(e))}: ${Re(e," ")}`),e.reactions.length&&n.push(` Reactions: ${Te(e)}`);return n.join("\n")+"\n"}function Re(e,t){return e.deleted?"(deleted)":e.text.replace(/\r\n|\r|\n/g,"\n"+t)+(e.edited?" (edited)":"")}function De(e,t){return{markdown:Pe(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 Ue="0.8.2",Be="2026-10-19";export{m as AI_NAME,u as ANIMALS,Be as BUILT,c as COLOURS,Y as DEFAULT_PROFILE_NAME,te as IndexedDbStore,X as MemoryStore,J as PipeupDocument,Z as UnsavedChangeError,Ue as VERSION,De as agentComments,p as animalName,R as computeOpId,Pe as copyAll,je as copyThread,d as createIdentity,fe as describeElement,pe as describeRange,qe as formatAgo,g as isAiName,Se as labelOf,ee as loadOrCreateProfile,Me as locate,f as nameOf,B as newDocumentAttribute,_ as parseDocumentAttribute,K as readFeedbackFile,be as resolveAnchor,N as signOp};