pipeup 0.6.0 → 0.7.0-beta.1

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.
Files changed (44) hide show
  1. package/README.md +3 -3
  2. package/cli/link.d.mts +17 -0
  3. package/cli/link.mjs +78 -4
  4. package/cli/pipeup.mjs +22 -7
  5. package/dist/pipeup.agents.js +2 -0
  6. package/dist/pipeup.core.js +1 -1
  7. package/dist/pipeup.esm.js +1 -1
  8. package/dist/pipeup.min.js +1 -1
  9. package/dist/types/core.d.ts +3 -1
  10. package/dist/types/crypto/portable.d.ts +15 -0
  11. package/dist/types/document.d.ts +20 -4
  12. package/dist/types/export/agent.d.ts +5 -0
  13. package/dist/types/export/format.d.ts +3 -1
  14. package/dist/types/index.d.ts +3 -1
  15. package/dist/types/model/animals.d.ts +7 -1
  16. package/dist/types/model/fold.d.ts +2 -0
  17. package/dist/types/model/ops.d.ts +5 -0
  18. package/dist/types/model/types.d.ts +28 -2
  19. package/dist/types/ui/addons.d.ts +22 -1
  20. package/dist/types/ui/animals.d.ts +1 -1
  21. package/dist/types/ui/app.d.ts +6 -0
  22. package/dist/types/ui/composer.d.ts +6 -1
  23. package/dist/types/ui/context.d.ts +16 -10
  24. package/dist/types/ui/draft-view.d.ts +5 -1
  25. package/dist/types/ui/highlights.d.ts +2 -0
  26. package/dist/types/ui/icons.d.ts +2 -0
  27. package/dist/types/ui/identity.d.ts +27 -0
  28. package/dist/types/ui/launcher.d.ts +0 -5
  29. package/dist/types/ui/legible.d.ts +27 -0
  30. package/dist/types/ui/mentions.d.ts +46 -0
  31. package/dist/types/ui/mount.d.ts +3 -0
  32. package/dist/types/ui/reactions.d.ts +31 -0
  33. package/dist/types/ui/styles.d.ts +1 -1
  34. package/dist/types/ui/theme.d.ts +31 -2
  35. package/dist/types/ui/thread-view.d.ts +12 -2
  36. package/package.json +1 -1
  37. package/skills/pipeup-add/SKILL.md +10 -5
  38. package/skills/pipeup-apply/SKILL.md +7 -5
  39. package/skills/pipeup-integrate/SKILL.md +20 -11
  40. package/skills/pipeup-send-to-git-setup/SKILL.md +1 -1
  41. package/skills/pipeup-summarise/SKILL.md +1 -1
  42. package/dist/types/export/prompt.d.ts +0 -12
  43. package/dist/types/ui/link.d.ts +0 -22
  44. package/dist/types/ui/replies.d.ts +0 -33
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.6.0).** The API and the stored comment format may change before 1.0; pin an exact version.
5
+ > **Alpha (0.7.0-beta.1).** 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,14 +21,14 @@ 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.6.0/dist/pipeup.min.js" integrity="sha384-…" crossorigin="anonymous" defer></script>
24
+ <script src="https://cdn.jsdelivr.net/npm/pipeup@0.7.0-beta.1/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
28
28
  (`node scripts/sri.mjs` prints it for a local build). Make a document key with
29
29
  `await Pipeup.newDocumentAttribute()` and keep it once people have commented.
30
30
 
31
- **Add-ons.** Optional extra scripts add features (`@pipeup/share`, `voice`, `live`, `assist`), and anyone can write their own
31
+ **Add-ons.** Optional extra scripts add features (`@pipeup/share`, `voice`, `live`, `assist`, `agents`, `emoji`, `github`, `updates`, `inbox`), and anyone can write their own
32
32
  (a company's, for example) without the Pipeup project's permission: see the
33
33
  [guide](https://pipeup-ai.github.io/pipeup/addons-guide.html). Add-ons run with the page's full power, so keep them
34
34
  intentional (best effort): pin each script with its `integrity` hash, name the add-ons that may run with
package/cli/link.d.mts ADDED
@@ -0,0 +1,17 @@
1
+ export type Support = "old" | "builtin" | "addon" | "unknown";
2
+ export function served(
3
+ html: string,
4
+ o: { base: string; agent: string; key: string; file: string; addon?: boolean },
5
+ ): string;
6
+ export function pageSupport(
7
+ html: string,
8
+ dir: string,
9
+ ): Promise<{ support: Support; version: string; loaded: boolean }>;
10
+ export function watch(o: {
11
+ page: string;
12
+ agent: string;
13
+ key: string;
14
+ port?: number;
15
+ log?: (line: string) => void;
16
+ }): Promise<{ url: string; sidecar: string; support: Support; addon: boolean; close(): Promise<void> }>;
17
+ export function comments(o: { page: string; all?: boolean; json?: boolean }): Promise<string>;
package/cli/link.mjs CHANGED
@@ -4,6 +4,10 @@ import { randomBytes } from "node:crypto";
4
4
  import { createServer } from "node:http";
5
5
  import { readFile, rename, writeFile } from "node:fs/promises";
6
6
  import { basename, dirname, extname, join, resolve, sep } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ /** The agents add-on that ships with this install; `watch` serves it to the pages that need it. */
10
+ const ADDON_FILE = fileURLToPath(new URL("../dist/pipeup.agents.js", import.meta.url));
7
11
 
8
12
  const TYPES = {
9
13
  ".html": "text/html; charset=utf-8",
@@ -25,9 +29,9 @@ const TYPES = {
25
29
  const MAX_BODY = 8 * 1024 * 1024;
26
30
  const attr = (v) => v.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
27
31
 
28
- /** The page for the browser: its own html tag, plus the link's address and the agent it lists, nothing else changed. */
29
- export function served(html, { base, agent, key, file }) {
30
- return html.replace(/<html\b([^>]*)>/i, (_, rest) => {
32
+ /** The page for the browser: its own html tag, plus the link's address and the agent it lists, and the agents add-on when it needs one. */
33
+ export function served(html, { base, agent, key, file, addon = false }) {
34
+ const out = html.replace(/<html\b([^>]*)>/i, (_, rest) => {
31
35
  let tag = rest;
32
36
  const listed = /\sdata-pipeup-agents\s*=\s*"([^"]*)"/i.exec(tag);
33
37
  if (listed) tag = tag.replace(listed[0], ` data-pipeup-agents="${attr(`${listed[1]} ${key}`.trim())}"`);
@@ -35,6 +39,55 @@ export function served(html, { base, agent, key, file }) {
35
39
  tag += ` data-pipeup-link="${base}" data-pipeup-link-agent="${attr(agent)}" data-pipeup-link-file="${attr(file)}"`;
36
40
  return `<html${tag}>`;
37
41
  });
42
+ if (!addon) return out;
43
+ // After the page's own scripts: an add-on registers in any order. The page's file on disk is not touched.
44
+ const tag = `<script src="${base}/agents.js"></script>`;
45
+ return /<\/body>/i.test(out) ? out.replace(/<\/body>/i, () => `${tag}</body>`) : out + tag;
46
+ }
47
+
48
+ /** Which of Pipeup's agent support a version has: before 0.6 none, 0.6.x built in, 0.7 and later in the agents add-on. */
49
+ function byVersion(v) {
50
+ const m = /^(\d+)\.(\d+)\.\d+/.exec(v);
51
+ if (!m) return null;
52
+ const [major, minor] = [Number(m[1]), Number(m[2])];
53
+ return major > 0 || minor >= 7 ? "addon" : minor === 6 ? "builtin" : "old";
54
+ }
55
+
56
+ /** The same, read from a Pipeup script's own text: it carries the names of what it supports. */
57
+ function bySignature(text) {
58
+ if (!text.includes("pipeup-root")) return null;
59
+ if (text.includes("pipeupReplies")) return "builtin";
60
+ return text.includes("listnote") ? "addon" : "old";
61
+ }
62
+
63
+ /**
64
+ * What the page's Pipeup can do for an agent, found without running the page: "old" (before 0.6, can't take an
65
+ * agent), "builtin" (0.6.x, agent support is part of it), "addon" (0.7 or later: the agents add-on serves an agent),
66
+ * or "unknown" (a floating address, or no Pipeup script to read). `loaded` says the page already includes the add-on.
67
+ */
68
+ export async function pageSupport(html, dir) {
69
+ const result = { support: "unknown", version: "", loaded: false };
70
+ for (const [, src] of html.matchAll(/<script\b[^>]*\bsrc\s*=\s*["']([^"']+)["']/gi)) {
71
+ if (/agents(\.min)?\.js|@pipeup\/agents/i.test(src)) result.loaded = true;
72
+ const named = /pipeup(?:@|-)(\d+\.\d+\.\d+(?:-[\w.]+)?)\b/.exec(src);
73
+ if (named && result.support === "unknown") {
74
+ result.support = byVersion(named[1]) ?? "unknown";
75
+ result.version = named[1];
76
+ continue;
77
+ }
78
+ if (result.support !== "unknown" || /^(https?:)?\/\//i.test(src)) continue;
79
+ try {
80
+ const path = /^file:/i.test(src)
81
+ ? fileURLToPath(src.split(/[?#]/)[0])
82
+ : resolve(dir, decodeURIComponent(src.split(/[?#]/)[0]));
83
+ result.support = bySignature(await readFile(path, "utf8")) ?? "unknown";
84
+ } catch {
85
+ // a script that can't be read says nothing about Pipeup
86
+ }
87
+ }
88
+ // A Pipeup carried inside the page itself.
89
+ if (result.support === "unknown") result.support = bySignature(html) ?? "unknown";
90
+ return result;
38
91
  }
39
92
 
40
93
  /** Starts the link for a page file. Resolves to { url, close }. */
@@ -47,6 +100,22 @@ export async function watch({ page, agent, key, port = 0, log = console.log }) {
47
100
  let origin = "";
48
101
  let host = "";
49
102
 
103
+ // Which Pipeup the page uses decides whether the agents add-on is added to what it shows.
104
+ const found = await pageSupport(await readFile(file, "utf8"), dir);
105
+ if (found.support === "old")
106
+ throw new Error(
107
+ `this page uses ${found.version ? `Pipeup ${found.version}` : "a Pipeup older than 0.6"}, which can't take an agent. Use Pipeup 0.6 or later (pin an exact version) and run this again`,
108
+ );
109
+ const addon = found.support !== "builtin" && !found.loaded;
110
+ let addonCode = "";
111
+ if (addon) {
112
+ try {
113
+ addonCode = await readFile(ADDON_FILE, "utf8");
114
+ } catch {
115
+ throw new Error("the agents add-on isn't in this install of pipeup (dist/pipeup.agents.js is missing)");
116
+ }
117
+ }
118
+
50
119
  const send = (res, status, body = "", type = "text/plain; charset=utf-8") => {
51
120
  res.writeHead(status, {
52
121
  "content-type": type,
@@ -62,6 +131,8 @@ export async function watch({ page, agent, key, port = 0, log = console.log }) {
62
131
  if (req.headers.host !== host) return send(res, 403, "wrong host");
63
132
  const url = new URL(req.url, origin);
64
133
  if (url.pathname.startsWith("/__pipeup/")) {
134
+ if (addon && url.pathname === `${base}/agents.js` && req.method === "GET")
135
+ return send(res, 200, addonCode, TYPES[".js"]);
65
136
  if (url.pathname !== `${base}/comments` || req.method !== "POST") return send(res, 404, "not found");
66
137
  if (req.headers.origin !== origin) return send(res, 403, "wrong origin");
67
138
  const chunks = [];
@@ -95,7 +166,8 @@ export async function watch({ page, agent, key, port = 0, log = console.log }) {
95
166
  } catch {
96
167
  return send(res, 404, "not found");
97
168
  }
98
- if (target === file) bytes = Buffer.from(served(bytes.toString("utf8"), { base, agent, key, file }));
169
+ if (target === file)
170
+ bytes = Buffer.from(served(bytes.toString("utf8"), { base, agent, key, file, addon }));
99
171
  send(
100
172
  res,
101
173
  200,
@@ -113,6 +185,8 @@ export async function watch({ page, agent, key, port = 0, log = console.log }) {
113
185
  return {
114
186
  url: `${origin}/${encodeURIComponent(name)}`,
115
187
  sidecar,
188
+ support: found.support,
189
+ addon,
116
190
  close: () => new Promise((ok) => server.close(ok)),
117
191
  };
118
192
  }
package/cli/pipeup.mjs CHANGED
@@ -24,7 +24,9 @@ pipeup agent [--name <name>]
24
24
 
25
25
  pipeup watch <page.html> [--agent <name>] [--port <number>]
26
26
  Shows the page from this computer, with a live link to the agent: the page offers "Share with my agent"
27
- (off until the person switches it on), and the agent is listed for this page while the link runs.
27
+ (off until the person switches it on), and the agent is listed for this page while the link runs. It adds the
28
+ agents add-on to the page it shows (the file is not changed), unless the page's Pipeup already has agent support
29
+ (0.6.x), and refuses a page whose Pipeup is older than 0.6.
28
30
 
29
31
  pipeup comments <page.html> [--all] [--json]
30
32
  Prints the comments the page has shared (open threads, or all with --all), as Markdown or, with --json, as data.
@@ -189,16 +191,29 @@ else if (command === "skills") {
189
191
  if (!page) fail(`missing the page\n\n${USAGE}`);
190
192
  await pageDoc(page);
191
193
  const { identity, name } = await loadAgent(typeof args.agent === "string" ? args.agent : undefined);
192
- const link = await watch({
193
- page,
194
- agent: name,
195
- key: identity.publicKey,
196
- port: typeof args.port === "string" ? Number(args.port) : 0,
197
- });
194
+ let link;
195
+ try {
196
+ link = await watch({
197
+ page,
198
+ agent: name,
199
+ key: identity.publicKey,
200
+ port: typeof args.port === "string" ? Number(args.port) : 0,
201
+ });
202
+ } catch (e) {
203
+ fail(e.message);
204
+ }
198
205
  console.log(`Open this page: ${link.url}\n`);
199
206
  console.log(
200
207
  `While this runs, ${name} is listed for the page and the page offers "Share with my agent" (off until you switch it on).`,
201
208
  );
209
+ if (link.addon)
210
+ console.log(
211
+ link.support === "unknown"
212
+ ? "It couldn't tell which Pipeup the page uses, so it adds the agents add-on to the page it shows (the add-on stays off on a Pipeup that already has agent support). The page's file is not changed."
213
+ : "It adds the agents add-on to the page it shows. The page's file is not changed.",
214
+ );
215
+ else if (link.support === "builtin")
216
+ console.log("This page's Pipeup (0.6) has agent support built in, so nothing is added to it.");
202
217
  console.log(
203
218
  `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)})`,
204
219
  );
@@ -0,0 +1,2 @@
1
+ "use strict";(()=>{function b(e){let t=globalThis;(t.pipeupAddons||=[]).push(e),typeof addEventListener=="function"&&addEventListener("load",()=>{t.Pipeup||console.error(`pipeup: the "${e.id}" add-on needs Pipeup on the page too; load pipeup.min.js.`)},{once:!0})}var re=2n**256n-2n**32n-977n;var L=/^\/__pipeup\/[A-Za-z0-9_-]{16,}$/;function P(e){let t=document.documentElement,n=t.getAttribute("data-pipeup-link")??"",s=L.test(n),o=!1,c=0,y=()=>{};async function r(){let d=!1;try{d=(await fetch(`${n}/comments`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(await e.snapshot())})).ok}catch{}if(!d)throw new Error("pipeup: the link to your agent isn't reachable; your comments are safe here")}let u=()=>{window.clearTimeout(c),y(),y=()=>{},o=!1};return{enabled:s,agent:t.getAttribute("data-pipeup-link-agent")??"",file:t.getAttribute("data-pipeup-link-file")??"",on:()=>o,set:async d=>{if(s){if(!d){u(),e.refresh();return}await r(),o=!0,y=e.changes(()=>{window.clearTimeout(c),c=window.setTimeout(()=>{r().catch(h=>{u(),e.refresh(),globalThis.reportError?.(h)})},300)}),e.refresh()}},destroy:u}}function T(e){let t=n=>n.replace(/\s+/g," ").trim();return[`Act on the review comments on this page, which uses Pipeup: ${t(e.title)} (${t(e.url)}).`,"",e.file?`1. Read the comments: \`npx pipeup comments ${e.file}\` (add --all for resolved ones). If it says nothing is shared, ask me to switch on Share with my agent.`:"1. Read the comments. Open the page in a browser and run `await Pipeup.comments()`, then read `.markdown`. If you can't run the page, ask me to paste its Copy as Markdown.","2. Work through the open threads in order. For each, make the change I approved, or say why you didn't. Ask me before changing anything I haven't approved, and answer a question with an answer.",e.replies?`3. Answer in each thread: \`npx pipeup reply --page ${e.file||"<the page's file>"} --thread <Thread id> "what you changed and where" --addressed "short note"\`. That writes ${t(e.replies)}.`+(e.listed?"":" The page doesn't list your key yet: run `npx pipeup agent --name <your name>` and tell me the attribute to add."):"3. Tell me what you would reply in each thread, in words I can paste.","4. Only mark a thread addressed. Never resolve, reopen, edit or delete: I close threads. Keep your key out of the page and its folder, and never answer as me.","","Guide: https://pipeup-ai.github.io/pipeup/skills/pipeup-apply/SKILL.md"].join(`
2
+ `)}var C=/^[A-Za-z0-9_-]{43}$/,_="pipeupReplies";var D=/^AI assistant\s*·?\s*/;function x(e=document.documentElement){let t=e.getAttribute("data-pipeup-agents")??"";return[...new Set(t.split(/[\s,]+/).filter(n=>C.test(n)))]}function k(e=location,t=document.documentElement){let n=t.getAttribute("data-pipeup-replies");try{let s=e.href.split(/[?#]/)[0],o=new URL(n??(/\/$/.test(s)?`${s}index.replies.js`:s.replace(/\.[^./]*$/,"")+".replies.js"),e.href),c=o.protocol==="file:"?e.protocol==="file:":o.origin===e.origin;return c||console.warn("pipeup: the replies file must be on this site or this computer; ignoring it"),c?o.href:null}catch{return null}}function E(e){let t=x(),n=0,s="",o=null;async function c(){let l=globalThis[_];if(!Array.isArray(l))return 0;let p=l.splice(0),g=[];for(let f of p){let m=f;if(!(m?.format!=="pipeup-replies"||m.doc!==e.document.id||!Array.isArray(m.ops)))for(let i of m.ops){let a=i?.body;a&&t.includes(a.author)&&(a.kind==="reply"||a.kind==="addressed"||a.kind==="react"||a.kind==="unreact")?(g.push(i),(a.name==="AI assistant"||a.name.startsWith("AI assistant "))&&(s=a.name.replace(D,""))):n++}}return g.length?e.merge(g):0}function y(){let l=k();return l?(o?.remove(),new Promise((p,g)=>{let f=document.createElement("script");o=f,f.src=`${l}?${Date.now()}`;let m=a=>{window.clearTimeout(i),f.remove(),o===f&&(o=null),a?g(new Error(`pipeup: ${a}`)):p()},i=window.setTimeout(()=>m("the replies file didn't answer"),4e3);f.addEventListener("load",()=>m()),f.addEventListener("error",()=>m("there is no replies file yet")),e.overlay().append(f)})):Promise.reject(new Error("pipeup: the replies file can't be read from here"))}async function r(){if(!t.length)return 0;let l=await c();return await y(),l+await c()}let u=!1,d=()=>{u||document.hidden||(u=!0,r().catch(()=>{}).finally(()=>u=!1))},h=0;return t.length?(d(),h=window.setInterval(d,4e3),document.addEventListener("visibilitychange",d)):c(),{enabled:t.length>0,ignored:()=>n,who:()=>s,check:r,tally:l=>{let p=l.filter(i=>!i.resolved),g=i=>i.root.replies.some(a=>t.includes(a.author)),f=new Set(l.map(i=>i.id));return{stray:new Set(e.document.ops().filter(i=>t.includes(i.body.author)&&!f.has(i.body.thread)).map(i=>i.body.thread)).size,open:p.length,answered:p.filter(g).length,addressed:p.filter(i=>i.addressed).length}},destroy:()=>{window.clearInterval(h),document.removeEventListener("visibilitychange",d),o?.remove()}}}var R=()=>globalThis.Pipeup??{},H=["M10 8h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-8a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2z","M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"],N=["M21 12L3.5 4.5 6.2 12l-2.7 7.5zM6.2 12H13"],z="Reads a replies file next to this page. When the page is shown through pipeup watch, and only after you switch it on, it sends this page's comments to the program running on this computer. Nothing leaves this computer.",S=e=>e instanceof Error?e.message.replace(/^pipeup: /,""):"Something went wrong";async function K(e,t){try{await navigator.clipboard.writeText(e);return}catch{}let n=document.createElement("textarea");n.value=e,n.setAttribute("readonly",""),n.style.cssText="position:fixed;opacity:0;pointer-events:none",t.append(n),n.select();let s=document.execCommand("copy");if(n.remove(),!s)throw new Error("pipeup: your browser blocked copying")}function U(){return{id:"agents",api:1,version:"0.6.0",needs:["menu","status","notify","listnote"],network:{when:"page-configured",to:["page"],says:z},setup(e){let t=E(e),n=P({snapshot:async()=>{let r=R();if(!r.comments)throw new Error("pipeup: this page has no Pipeup to read comments from");let[u,d]=await Promise.all([r.comments(),r.comments({all:!0})]);return{v:1,at:new Date().toISOString(),title:document.title,open:u,all:d}},changes:r=>e.document.onChange(r),refresh:()=>o()}),s=()=>t.who()||n.agent,o=()=>{if(e.setStatus(t.enabled||n.enabled?{text:n.on()?`Sharing comments with ${s()||"your agent"}`:`${s()||"An AI agent"} can answer comments here`}:null),!t.enabled)return e.setListNote(null);let r=t.tally(e.document.threads()),u=s()||"An agent",d=r.answered?`${u} has answered ${r.answered} of ${r.open} open comments${r.addressed?`; ${r.addressed} ${r.addressed===1?"is":"are"} marked addressed`:""}`:"No replies from an agent yet",h=t.ignored(),l=(n.on()?`Sharing with ${n.agent||"your agent"} \xB7 `:"")+d+(h?` \xB7 ${h} from other writers ignored`:"")+(r.stray?` \xB7 replies for ${r.stray} comment${r.stray===1?"":"s"} this page doesn't have`:"");e.setListNote({text:l,action:{label:"Check for replies",run:async()=>{try{let p=await t.check();e.notify(p?`${p} new ${p===1?"reply":"replies"}`:"No new replies")}catch(p){e.notify(S(p))}finally{o()}}}})},c=[e.addMenuItem({id:"prompt",icon:H,label:()=>"Copy a prompt for my agent",hint:()=>"Tells an AI agent where the comments are and how to answer them",select:async()=>{try{await K(T({title:document.title,url:location.href,replies:k(),file:n.enabled?n.file:"",listed:x().length>0}),e.overlay()),e.notify("Copied a prompt for your agent")}catch(r){e.notify(S(r))}}})];n.enabled&&c.push(e.addMenuItem({id:"link",icon:N,label:()=>"Share with my agent",hint:()=>"Sends this page's comments to the program running on this computer, and nothing else",checked:()=>n.on(),select:async()=>{try{await n.set(!n.on())}catch(r){e.notify(S(r))}o()}}));let y=e.document.onChange(o);return o(),()=>{y(),t.destroy(),n.destroy()}}}}b(U());})();
@@ -1 +1 @@
1
- function e(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function t(e){let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function r(e){return(new TextEncoder).encode(e)}function n(e){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return"["+e.map(n).join(",")+"]";let t=e;return"{"+Object.keys(t).filter(e=>void 0!==t[e]).sort().map(e=>JSON.stringify(e)+":"+n(t[e])).join(",")+"}"}function i(e){return e.replace(/\s+/g," ").trim()}function o(e){let t=i(e),r=2166136261;for(let e=0;e<t.length;e++)r^=t.charCodeAt(e),r=Math.imul(r,16777619)>>>0;return r.toString(16).padStart(8,"0")}var a=/^[A-Za-z0-9_-]{43}$/,s=new Map;async function 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=1e4,h=2**40,c=2**47,p=1e4,f=/^[0-9a-f]{8}$/,m=/^[A-Za-z0-9_-]{43}$/,y=/^[A-Za-z0-9_-]{43}$/,g=new Set(["create","reply","edit","delete","resolve","reopen","addressed"]);async function w(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 b=(e,t)=>"string"==typeof e&&e.length<=t,x=e=>!!e&&"object"==typeof e,v=e=>"number"==typeof e&&Number.isFinite(e)&&e>=0&&e<=1;function A(e){if(!x(e))return!1;let{id:t,path:r,fingerprint:n,snapshot:i,quote:o,point:a,view:s}=e;if(!(b(r,2e3)&&b(i,500)&&"string"==typeof n&&f.test(n)&&(void 0===t||b(t,200)&&""!==t)&&(void 0===o||x(o)&&b(o.exact,p)&&""!==o.exact&&b(o.prefix,64)&&b(o.suffix,64))&&(void 0===a||x(a)&&v(a.x)&&v(a.y))))return!1;if(void 0!==s){if(!x(s)||Array.isArray(s))return!1;let e=Object.entries(s);if(e.length>16||!e.every(([e,t])=>e.length<=64&&b(t,200)))return!1}return!0}function k(e){if(!x(e))return!1;let{body:t,sig:r}=e;if("string"!=typeof r||!x(t)||JSON.stringify({body:t,sig:r}).length>262144)return!1;let n=t;return!(1!==n.v||"string"!=typeof n.id||!m.test(n.id)||!g.has(n.kind)||!b(n.doc,64)||""===n.doc||"string"!=typeof n.thread||!m.test(n.thread)||"string"!=typeof n.author||!y.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>h||"number"!=typeof n.at||!Number.isSafeInteger(n.at)||n.at<0||n.at>c||void 0!==n.text&&(!b(n.text,u)||n.text!==n.text.trim())||void 0!==n.target&&("string"!=typeof n.target||!m.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||"create"===n.kind&&(n.id!==n.thread||!A(n.anchor)))}function E(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 $(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 M(e,t,r,n,i){return{id:e,author:t,name:r,text:n,at:i,edited:!1,deleted:!1,replies:[]}}async function S(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 C=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($)){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=M(i.id,i.author,i.name,i.text,i.at);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=M(i.id,i.author,i.name,i.text,i.at);e.root.replies.push(t),r.set(i.id,{comment:t,thread:i.thread});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),"delete"===i.kind&&(o.comment.text="",o.comment.deleted=!0))}}for(let{comment:e}of r.values())e.name||(e.unnamed=!0,e.name=n.get(e.author)??"");return[...t.values()]}(this.ops.values())}async add(e){let t=[];for(let r of e){if(!k(r)||r.body.doc!==this.doc||this.ops.has(r.body.id)||r.body.id!==await S(r.body)||!await E(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,h),at:Math.min(Math.max(Date.now(),"create"===r.kind?(this.createAt.get(e.publicKey)??0)+1:(this.threadAt.get(r.thread)??0)+1),c)};n.id=await S(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 w(n,e)]);if(!o)throw new Error("pipeup: could not record this change");return o}},N=["Otter","Fox","Owl","Bear","Rabbit"],O=["Red","Orange","Yellow","Green","Teal","Blue","Purple","Pink","Brown","Grey"];function q(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=>`${O[(e=>Math.floor(q(e)/N.length)%O.length)(e)]} ${N[(e=>q(e)%N.length)(e)]}`,T=e=>e.name.replace(/^AI assistant · /,"")||P(e.author),j="AI assistant",I=e=>e===j||e.startsWith(`${j} `),D=/^([A-Za-z0-9_-]{16}):([A-Za-z0-9_-]{43})$/;function F(){return`${function(t=16){return e(crypto.getRandomValues(new Uint8Array(t)))}(12)}:${e(crypto.getRandomValues(new Uint8Array(32)))}`}async function U(e){let r=D.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 R(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}`;var L=/^[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"}},K=class e{constructor(e,t){this.log=e,this.options=t,this.displayName=t.name.trim()?B(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 C(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=B(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){return this.enqueue(()=>this.write({kind:"create",anchor:e,text:_(t)}))}reply(e,t){return this.enqueue(()=>this.write({kind:"reply",thread:this.find(e).thread,target:e,text:_(t)}))}edit(e,t){return this.enqueue(async()=>{let{thread:r}=this.mine(e);await this.write({kind:"edit",thread:r,target:e,text:_(t)})})}remove(e){return this.enqueue(async()=>{let{thread:t}=this.mine(e);await this.write({kind:"delete",thread:t,target:e})})}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(!L.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 R(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 async function(e,n,i){if(e.length>5e6)throw new Error("pipeup: this feedback file is too large");let o,a,s;try{o=JSON.parse(e)}catch{throw new Error("pipeup: this is not an Pipeup feedback file")}if(!o||"object"!=typeof o||1!==o.pipeup||"string"!=typeof o.doc)throw new Error("pipeup: this is not an Pipeup feedback file");if(o.doc!==n)throw new Error("pipeup: this feedback is for a different document");if(!o.sealed)return Array.isArray(o.ops)?o.ops:[];if(!i)throw new Error("pipeup: this feedback is sealed, and this page has no document key");if("string"!=typeof o.iv||"string"!=typeof o.data)throw new Error("pipeup: this is not an Pipeup feedback file");try{a=await async function(e,n,i){try{let o=await crypto.subtle.decrypt({name:"AES-GCM",iv:t(n.iv),additionalData:r(i)},e,t(n.data));return(new TextDecoder).decode(o)}catch{throw new Error("pipeup: this feedback could not be opened with this document")}}(i,{iv:o.iv,data:o.data},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:[]}(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 _(e){let t=e.trim();if(!t)throw new Error("pipeup: a comment needs some words");if(t.length>u)throw new Error(`pipeup: comments are limited to ${u} characters`);return t}function B(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(I(t))throw new Error("pipeup: that name is kept for AI replies; choose another");return t}var G=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}},J="";async function V(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 W=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=Z(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=Z(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 Z(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 Q(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 X(e,t,r){let n=(e.ownerDocument??e).createRange();return n.setStart(e,0),n.setEnd(t,r),n.toString().length}function Y(e,t,r){let n=ee(e,t,!1),i=ee(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 ee(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 te(e){return e.nodeType===Node.ELEMENT_NODE?e:e.parentElement}function re(e,t){for(let r=te(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 ne(e,t,r){return e.slice(t,r).replace(/^[\uDC00-\uDFFF]|[\uD800-\uDBFF]$/g,"")}function ie(e,t){let r=function(e,t){if(e===t)return"";let r=[];for(let n=t;n&&n!==e;n=n.parentElement){let e=1;for(let t=n.previousElementSibling;t;t=t.previousElementSibling)t.tagName===n.tagName&&e++;r.unshift(`${n.tagName.toLowerCase()}:nth-of-type(${e})`)}return":scope > "+r.join(" > ")}(e,t);if(r.length>2e3)throw new Error("pipeup: this element is nested too deeply to comment on — give a nearby container a data-pipeup-id");return r}function oe(e){if(!A(e))throw new Error("pipeup: could not describe this place on the page");return e}function ae(e,t){let r=te(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 se(e,t,r){if(!t.contains(e.commonAncestorContainer))throw new Error("pipeup: the selection is outside the commentable area");let n=re(e.commonAncestorContainer,t),a=n??t,{text:s}=Q(a),d=X(a,e.startContainer,e.startOffset),l=X(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>p)throw new Error("pipeup: selections are limited to 10000 characters");let h=ne(s,Math.max(0,d-32),d),c=ne(s,l,l+32);return oe({...n?{id:n.getAttribute("data-pipeup-id")??""}:{},path:"",quote:{exact:u,prefix:h,suffix:c},...r?{view:r}:{},fingerprint:o(ae(e.startContainer,t).textContent??""),snapshot:ne(i(h+u+c),0,200)})}function de(e,t,r,n){let a=re(e,t);return oe({...a?{id:a.getAttribute("data-pipeup-id")??""}:{},path:ie(a??t,e),...r?{point:{x:le(r.x),y:le(r.y)}}:{},...n?{view:n}:{},fingerprint:o(e.textContent??""),snapshot:ne(i(e.textContent??""),0,200)})}function le(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function ue(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 he=(e,t)=>ue(e,t,!1).pop(),ce={state:"orphaned",element:null,range:null};function pe(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=Q(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=me(o,t.prefix)+fe(a,t.suffix);s>n&&(r=i,n=s)}return r}(s.text,t);if(d>=0){let i=Y(s,d,d+t.exact.length);if(i){let t=ae(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:Q(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(ue(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=he(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?Y(e,r.start,r.end):null;if(i)return{state:"moved",element:ae(i.startContainer,n),range:i}}}return ce}(e,e.quote,n,t,!1!==r.fuzzy):function(e,t){if(!t)return ce;let r=t;if(e.path){if(!e.path.startsWith(":scope > "))return ce;try{r=t.querySelector(e.path)}catch{return ce}}return r?{state:o(r.textContent??"")===e.fingerprint?"attached":"moved",element:r,range:null}:ce}(e,n)}function fe(e,t){let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)r++;return r}function me(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 ye={A:"Link",BUTTON:"Button",P:"Paragraph",LI:"List item",IMG:"Image",TABLE:"Table",TD:"Cell",TH:"Cell",FIGURE:"Figure",SVG:"Graphic",CANVAS:"Graphic",LABEL:"Label",INPUT:"Field",SELECT:"Field",TEXTAREA:"Field",SUMMARY:"Question",BLOCKQUOTE:"Quote",SECTION:"Section",H1:"Heading",H2:"Heading",H3:"Heading",H4:"Heading",H5:"Heading",H6:"Heading"};function ge(e){return e.getAttribute("data-pipeup-label")||ye[e.tagName.toUpperCase()]||"Block"}function we(e){let t=e.getAttribute("data-pipeup-label");if(t)return t;let r=function(e){return xe(i(e.getAttribute("aria-label")??e.getAttribute("alt")??e.innerText??e.textContent??""),40)}(e);return r?`${ge(e)} · ${r}`:ge(e)}function be(e,t,r){let n=e.id??null,o=e.quote?.exact??null,a=e.point?`${Math.round(100*e.point.x)}% across, ${Math.round(100*e.point.y)}% down the element`:null,s=t.element;if("orphaned"===t.state||!s)return{where:`No longer on the page (it read: "${e.snapshot}")`,element:null,id:n,quote:o,pin:a};let d=[],l=e.view?.slide;if(l){let e=s.closest("[data-pipeup-slide]")?.querySelector("h1,h2,h3")?.textContent;d.push(`Slide ${l}`+(e?` "${xe(i(e))}"`:""))}else{let t=function(e){return e?e.label||Object.entries(e).filter(([e,t])=>t&&"slide"!==e).map(([,e])=>e).join(" · "):""}(e.view);t&&d.push(t);let n=function(e,t){let r=null;for(let n of t.querySelectorAll("h1,h2,h3")){if(n===e||n.contains(e))break;if(!(4&n.compareDocumentPosition(e)))break;r=n}return r}(s,r);n&&d.push(`Section "${xe(i(n.textContent??""))}"`)}let u=we(s);return d.push(u),{where:d.join(" › "),element:u,id:n,quote:o,pin:a}}function xe(e,t=60){return e.length>t?e.slice(0,t-1)+"…":e}var ve="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 Ae(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 ke(e,t,r,n){return"ai"===t?Me(e,"## Comment thread",n,r):Se(e)}function Ee(e,t,r){let n=r.all?e:e.filter(e=>!e.thread.resolved);if("text"===t)return n.map(Se).join("\n");let i=r.all?0:e.length-n.length,o=[`# Review comments: ${$e(r.title)}`,"",`- **Page:** ${$e(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)":""}`,"",ve,"",""].join("\n"),a=r.exportedAt.getTime();return o+n.map((e,t)=>Me(e,`## Thread ${t+1}`,a)).join("\n")}function $e(e){return e.replace(/\s+/g," ").trim()}function Me(e,t,r,n){let{thread:i,location:o}=e,a=i.root.replies.length,s=[`${t} · ${i.resolved?"resolved":i.addressed?"open, addressed":"open"}`];if(s.push(`- **Thread:** ${i.id}`),n&&s.push(`- **Page:** ${$e(n)}`),s.push(`- **Where:** ${$e(o.where)}`),o.id){let e=$e(o.id.replace(/`/g,""));s.push(`- **Element:** \`[data-pipeup-id="${e}"]\`${o.element?` (${$e(o.element)})`:""}`)}o.quote&&s.push(`- **Quoted text:** "${$e(o.quote)}"`),o.pin&&s.push(`- **Pin:** ${$e(o.pin)}`),i.addressed&&!i.resolved&&s.push(`- **Addressed:** ${$e(i.addressed.text)} (${$e(T(i.addressed))}, ${Ae(i.addressed.at,r)})`),s.push(`- **Started by:** ${$e(T(i.root))}, ${Ae(i.root.at,r)}${a?` · ${a} ${1===a?"reply":"replies"}`:""}`,"",`**${$e(T(i.root))}** (${Ae(i.root.at,r)}): ${Ce(i.root," ")}`);for(let e of i.root.replies)s.push(`- **${$e(T(e))}** (${Ae(e.at,r)}): ${Ce(e," ")} \x3c!-- comment:${e.id} --\x3e`);return s.join("\n")+"\n"}function Se(e){let{thread:t,location:r}=e,n=[$e(r.where)+(r.quote?`, on the text "${$e(r.quote)}"`:""),`${$e(T(t.root))}: ${Ce(t.root," ")}`];for(let e of t.root.replies)n.push(` ${$e(T(e))}: ${Ce(e," ")}`);return n.join("\n")+"\n"}function Ce(e,t){return e.deleted?"(deleted)":e.text.replace(/\r\n|\r|\n/g,"\n"+t)+(e.edited?" (edited)":"")}var Ne="0.6.0";export{j as AI_NAME,N as ANIMALS,O as COLOURS,J as DEFAULT_PROFILE_NAME,W as IndexedDbStore,G as MemoryStore,K as PipeupDocument,z as UnsavedChangeError,Ne as VERSION,P as animalName,S as computeOpId,Ee as copyAll,ke as copyThread,d as createIdentity,de as describeElement,se as describeRange,Ae as formatAgo,I as isAiName,we as labelOf,V as loadOrCreateProfile,be as locate,T as nameOf,F as newDocumentAttribute,U as parseDocumentAttribute,pe as resolveAnchor,w 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 l(){let t=await crypto.subtle.generateKey({name:"Ed25519"},!1,["sign","verify"]);return{publicKey:e(new Uint8Array(await crypto.subtle.exportKey("raw",t.publicKey))),privateKey:t.privateKey}}async function d(t,r){let n=await crypto.subtle.sign({name:"Ed25519"},t.privateKey,r);return e(new Uint8Array(n))}var u="0123456789ABCDEFGHJKMNPQRSTVWXYZ";Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);var c=["Otter","Fox","Owl","Bear","Rabbit"],h=["Red","Orange","Yellow","Green","Teal","Blue","Purple","Pink","Brown","Grey"];function p(e){let t=2166136261;for(let r=0;r<e.length;r++)t=Math.imul(t^e.charCodeAt(r),16777619);return t=Math.imul(t^t>>>16,2246822507),t=Math.imul(t^t>>>13,3266489909),(t^t>>>16)>>>0}var f=e=>`${h[(e=>Math.floor(p(e)/c.length)%h.length)(e)]} ${c[(e=>p(e)%c.length)(e)]}`,m=e=>{let t=e.name.replace(/^AI assistant · /,"")||f(e.author);return e.alike?`${t} · ${function(e){let t=p(`id:${e}`),r="";for(let e=0;e<4;e++,t>>>=5)r+="0123456789ABCDEFGHJKMNPQRSTVWXYZ"[31&t];return r}(e.author)}`:t},g="AI assistant",y=e=>e===g||e.startsWith(`${g} `),w=1e4,b=2**40,x=2**47,v=1e4,k=/^[0-9a-f]{8}$/,A=/^[A-Za-z0-9_-]{43}$/,E=/^(?:[^\s@<>"]{1,64}@[^\s@<>"]{1,190}\.[^\s@<>"]{2,24}|gh:[A-Za-z0-9-]{1,39})$/,$=/^(?:[A-Za-z0-9_-]{43}|(?:host|gh):[A-Za-z0-9._@-]{1,64})$/,M=/^[A-Za-z0-9_-]{43}$/,S=new Set(["create","reply","edit","delete","resolve","reopen","addressed","react","unreact","seen","contact","uncontact"]),C=/^(?:\p{Regional_Indicator}{2}|[#*0-9]\uFE0F?\u20E3|\p{Extended_Pictographic}(?:\uFE0F|\p{Emoji_Modifier})?(?:\u200D\p{Extended_Pictographic}(?:\uFE0F|\p{Emoji_Modifier})?)*)$/u,N=e=>"string"==typeof e&&C.test(e)&&[...e].length<=16;async function O(e,t){if(e.author!==t.publicKey)throw new Error("pipeup: an op must be signed by its author");return{body:e,sig:await d(t,r(n(e)))}}var P=(e,t)=>"string"==typeof e&&e.length<=t,q=e=>!!e&&"object"==typeof e,j=e=>"number"==typeof e&&Number.isFinite(e)&&e>=0&&e<=1;function T(e){if(!q(e))return!1;let{id:t,path:r,fingerprint:n,snapshot:i,quote:o,point:a,view:s}=e;if(!(P(r,2e3)&&P(i,500)&&"string"==typeof n&&k.test(n)&&(void 0===t||P(t,200)&&""!==t)&&(void 0===o||q(o)&&P(o.exact,v)&&""!==o.exact&&P(o.prefix,64)&&P(o.suffix,64))&&(void 0===a||q(a)&&j(a.x)&&j(a.y))))return!1;if(void 0!==s){if(!q(s)||Array.isArray(s))return!1;let e=Object.entries(s);if(e.length>16||!e.every(([e,t])=>e.length<=64&&P(t,200)))return!1}return!0}function I(e){if(!q(e))return!1;let{body:t,sig:r}=e;if("string"!=typeof r||!q(t)||JSON.stringify({body:t,sig:r}).length>262144)return!1;let n=t;if(1!==n.v||"string"!=typeof n.id||!A.test(n.id)||!S.has(n.kind)||!P(n.doc,64)||""===n.doc||"string"!=typeof n.thread||!A.test(n.thread)||"string"!=typeof n.author||!M.test(n.author)||"string"!=typeof n.name||n.name.length>80||n.name!==n.name.trim()||"number"!=typeof n.clock||!Number.isSafeInteger(n.clock)||n.clock<1||n.clock>b||"number"!=typeof n.at||!Number.isSafeInteger(n.at)||n.at<0||n.at>x||void 0!==n.text&&(!P(n.text,w)||n.text!==n.text.trim())||void 0!==n.target&&("string"!=typeof n.target||!A.test(n.target))||("create"===n.kind||"reply"===n.kind||"edit"===n.kind||"addressed"===n.kind)&&!n.text||("reply"===n.kind||"edit"===n.kind||"delete"===n.kind)&&!n.target)return!1;if(void 0!==n.mentions){if("create"!==n.kind&&"reply"!==n.kind&&"edit"!==n.kind||!Array.isArray(n.mentions)||n.mentions.length>20)return!1;let e=n.text?.length??0;for(let t of n.mentions){if(!q(t)||!Number.isSafeInteger(t.start)||!Number.isSafeInteger(t.end))return!1;let{start:r,end:n,ref:i}=t;if(r<0||n<=r||n>e||"string"!=typeof i||!$.test(i))return!1}}return!(!("contact"!==n.kind||"string"==typeof n.text&&E.test(n.text))||"seen"===n.kind&&!n.target||!("react"!==n.kind&&"unreact"!==n.kind||n.target&&N(n.text))||!("create"!==n.kind||n.id===n.thread&&T(n.anchor)))}function F(i){return async function(r,n,i){if(!a.test(r))return!1;try{if(e(t(r))!==r)return!1;let o=s.get(r);if(!o){s.size>=512&&s.delete(s.keys().next().value),o=crypto.subtle.importKey("raw",t(r),{name:"Ed25519"},!0,["verify"]),s.set(r,o);let e=o;e.catch(()=>{s.get(r)===e&&s.delete(r)})}return await crypto.subtle.verify({name:"Ed25519"},await o,t(i),n)}catch{return!1}}(i.body.author,r(n(i.body)),i.sig)}function D(e,t){return e.body.clock!==t.body.clock?e.body.clock-t.body.clock:e.body.at!==t.body.at?e.body.at-t.body.at:e.body.author!==t.body.author?e.body.author<t.body.author?-1:1:e.body.id!==t.body.id?e.body.id<t.body.id?-1:1:0}function R(e,t,r,n,i,o){let a={id:e,author:t,name:r,text:n,at:i,edited:!1,deleted:!1,replies:[],reactions:[]};return o?.length&&(a.mentions=o),a}async function U(t){let i={...t,id:void 0,thread:"create"===t.kind?void 0:t.thread},o=await crypto.subtle.digest("SHA-256",r(n(i)));return e(new Uint8Array(o))}var K=class{constructor(e){this.doc=e}ops=new Map;clock=0;createAt=new Map;threadAt=new Map;get size(){return this.ops.size}all(){return[...this.ops.values()]}threads(){return function(e){let t=new Map,r=new Map,n=new Map;for(let{body:i}of[...e].sort(D)){if(i.name&&n.set(i.author,i.name),"create"===i.kind){if(t.has(i.id)||!i.anchor||void 0===i.text)continue;let e=R(i.id,i.author,i.name,i.text,i.at,i.mentions);t.set(i.id,{id:i.id,anchor:i.anchor,root:e,resolved:!1}),r.set(i.id,{comment:e,thread:i.id});continue}let e=t.get(i.thread);if(!e)continue;if("resolve"===i.kind||"reopen"===i.kind){e.resolved="resolve"===i.kind,"reopen"===i.kind&&delete e.addressed;continue}if("addressed"===i.kind){void 0!==i.text&&(e.addressed={text:i.text,author:i.author,name:i.name,at:i.at});continue}let o=i.target?r.get(i.target):void 0;if(o&&o.thread===i.thread){if("reply"===i.kind){if(r.has(i.id)||void 0===i.text)continue;let t=R(i.id,i.author,i.name,i.text,i.at,i.mentions);e.root.replies.push(t),r.set(i.id,{comment:t,thread:i.thread});continue}if("seen"===i.kind){let e=o.comment.seenBy??=[];e.includes(i.author)||e.push(i.author);continue}if("react"===i.kind||"unreact"===i.kind){if(void 0===i.text||o.comment.deleted)continue;let e=o.comment.reactions,t=e.find(e=>e.emoji===i.text);if("react"===i.kind){let r={author:i.author,name:i.name};t?t.by.some(e=>e.author===i.author)||t.by.push(r):e.length<12&&e.push({emoji:i.text,by:[r]})}else t&&(t.by=t.by.filter(e=>e.author!==i.author),t.by.length||e.splice(e.indexOf(t),1));continue}i.author!==o.comment.author||o.comment.deleted||("edit"===i.kind&&void 0!==i.text&&(o.comment.text=i.text,o.comment.edited=!0,i.mentions?o.comment.mentions=i.mentions:delete o.comment.mentions),"delete"===i.kind&&(o.comment.text="",o.comment.deleted=!0,o.comment.reactions=[],delete o.comment.mentions))}}for(let{comment:e}of r.values()){e.name||(e.unnamed=!0,e.name=n.get(e.author)??"");for(let t of e.reactions)for(let e of t.by)e.name||=n.get(e.author)??""}let i=new Map,o=(e,t)=>{let r=m({author:e,name:t}).toLowerCase();(i.get(r)??i.set(r,new Set).get(r)).add(e)};for(let{comment:e}of r.values()){o(e.author,e.name);for(let t of e.reactions)for(let e of t.by)o(e.author,e.name)}let a=(e,t)=>(i.get(m({author:e,name:t}).toLowerCase())?.size??0)>1;for(let{comment:e}of r.values()){a(e.author,e.name)&&(e.alike=!0);for(let t of e.reactions)for(let e of t.by)a(e.author,e.name)&&(e.alike=!0)}return[...t.values()]}(this.ops.values())}async add(e){let t=[];for(let r of e){if(!I(r)||r.body.doc!==this.doc||this.ops.has(r.body.id)||r.body.id!==await U(r.body)||!await F(r))continue;let e={body:r.body,sig:r.sig};this.ops.set(e.body.id,e),this.clock=Math.max(this.clock,e.body.clock),"create"===e.body.kind&&this.createAt.set(e.body.author,Math.max(this.createAt.get(e.body.author)??0,e.body.at)),this.threadAt.set(e.body.thread,Math.max(this.threadAt.get(e.body.thread)??0,e.body.at)),t.push(e)}return t}async append(e,t,r){let n={v:1,...r,id:"",thread:"create"===r.kind?"":r.thread,doc:this.doc,author:e.publicKey,name:t,clock:Math.min(this.clock+1,b),at:Math.min(Math.max(Date.now(),"create"===r.kind?(this.createAt.get(e.publicKey)??0)+1:(this.threadAt.get(r.thread)??0)+1),x)};n.id=await U(n);let i=this.ops.get(n.id);if(i)return i;"create"===n.kind&&(n.thread=n.id);let[o]=await this.add([await O(n,e)]);if(!o)throw new Error("pipeup: could not record this change");return o}},H=/^([A-Za-z0-9_-]{16}):([A-Za-z0-9_-]{43})$/;function L(){return`${function(t=16){return e(crypto.getRandomValues(new Uint8Array(t)))}(12)}:${e(crypto.getRandomValues(new Uint8Array(32)))}`}async function _(e){let r=H.exec(e.trim()),n=r?.[1],i=r?.[2];if(!n||!i)throw new Error('pipeup: data-pipeup-doc must look like "<id>:<key>", as made by newDocumentAttribute()');return{id:n,key:await crypto.subtle.importKey("raw",t(i),{name:"AES-GCM"},!1,["encrypt","decrypt"])}}async function z(t,n,i){let o=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:o,additionalData:r(i)},t,r(n));return{iv:e(o),data:e(new Uint8Array(a))}}var B=e=>`pipeup-file:${e}`;var G=/^[a-z][a-z0-9-]{1,23}\/[a-z][a-z0-9-]{0,31}$/,Z=class extends Error{constructor(e,t,r=1){super("pipeup: shown here, but not saved yet"),this.id=e,this.cause=t,this.count=r,this.name="UnsavedChangeError"}},J=class e{constructor(e,t){this.log=e,this.options=t,this.displayName=t.name.trim()?Q(t.name):""}listeners=new Set;cache=[];comments=new Map;displayName;e=Promise.resolve();unsaved=[];static async open(t){if("string"!=typeof t.doc||""===t.doc||t.doc.length>64)throw new Error("pipeup: the document id must be 1 to 64 characters");let r=new K(t.doc),n=await t.store.load(t.doc),i=n.length-(await r.add(n)).length;i&&console.warn(`pipeup: ${i} saved change${1===i?"":"s"} on this page couldn't be read; kept as saved`);let o=new e(r,t);return o.refresh(!1),o}get id(){return this.options.doc}get me(){return this.options.identity.publicKey}get name(){return this.displayName}set name(e){this.displayName=Q(e),this.refresh(!0,[],"")}threads(){return this.cache}ops(){return this.log.all()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}comment(e,t,r){return this.enqueue(()=>this.write({kind:"create",anchor:e,text:V(t),...r?.length?{mentions:r}:{}}))}reply(e,t,r){return this.enqueue(()=>this.write({kind:"reply",thread:this.find(e).thread,target:e,text:V(t),...r?.length?{mentions:r}:{}}))}edit(e,t,r){return this.enqueue(async()=>{let{thread:n}=this.mine(e);await this.write({kind:"edit",thread:n,target:e,text:V(t),...r?.length?{mentions:r}:{}})})}remove(e){return this.enqueue(async()=>{let{thread:t}=this.mine(e);await this.write({kind:"delete",thread:t,target:e})})}contact(e){let t=e.trim();return E.test(t)?this.enqueue(async()=>{await this.write({kind:"contact",thread:this.me,text:t})}):Promise.reject(new Error("pipeup: that isn't an email address or a GitHub name"))}uncontact(){return this.enqueue(async()=>{await this.write({kind:"uncontact",thread:this.me})})}contacts(){let e=new Map;for(let{body:t}of[...this.log.all()].sort(D))"contact"===t.kind&&t.text?e.set(t.author,t.text):"uncontact"===t.kind&&e.delete(t.author);return e}get portable(){return this.options.identity.privateKey.extractable}identityCode(){return async function(e){if(!e.privateKey.extractable)return null;let r=await crypto.subtle.exportKey("jwk",e.privateKey);return r.d?function(e){let t=(function(e){let t=0,r=0,n="";for(let i of e)for(r=r<<8|i,t+=8;t>=5;)n+=u[r>>>t-5&31],t-=5;return t&&(n+=u[r<<5-t&31]),n}(e)+function(e){let t=2166136261;for(let r of e)t=Math.imul(t^r,16777619);t=Math.imul(t^t>>>15,739982445);let r="";for(let e=0;e<4;e++,t>>>=5)r+=u[31&t];return r}(e)).match(/.{1,4}/g).join("-");return`PU1-${t}`}(t(r.d)):null}(this.options.identity)}seen(e){return this.enqueue(async()=>{for(let t of e){let e=this.comments.get(t);e&&!e.comment.seenBy?.includes(this.me)&&await this.write({kind:"seen",thread:e.thread,target:t})}})}react(e,t){return this.enqueue(async()=>{await this.write({kind:"react",thread:this.find(e).thread,target:e,text:W(t)})})}unreact(e,t){return this.enqueue(async()=>{await this.write({kind:"unreact",thread:this.find(e).thread,target:e,text:W(t)})})}resolve(e){return this.enqueue(async()=>{await this.write({kind:"resolve",thread:this.thread(e)})})}reopen(e){return this.enqueue(async()=>{await this.write({kind:"reopen",thread:this.thread(e)})})}sign(e,t){if(!G.test(e))throw new Error('pipeup: a signing purpose looks like "<add-on id>/<name>"');return d(this.options.identity,r(`pipeup:${e}\n${t}`))}flush(){return this.enqueue(()=>this.persist())}exportFile(){return async function(e,t,r){let n=r?{pipeup:1,doc:e,sealed:!0,...await z(r,JSON.stringify(t),B(e))}:{pipeup:1,doc:e,sealed:!1,ops:t};return JSON.stringify(n,null,2)}(this.options.doc,this.log.all(),this.options.key)}async importFile(e){return this.merge(await async function(e,n,i){if(e.length>5e6)throw new Error("pipeup: this feedback file is too large");let o,a,s;try{o=JSON.parse(e)}catch{throw new Error("pipeup: this is not an Pipeup feedback file")}if(!o||"object"!=typeof o||1!==o.pipeup||"string"!=typeof o.doc)throw new Error("pipeup: this is not an Pipeup feedback file");if(o.doc!==n)throw new Error("pipeup: this feedback is for a different document");if(!o.sealed)return Array.isArray(o.ops)?o.ops:[];if(!i)throw new Error("pipeup: this feedback is sealed, and this page has no document key");if("string"!=typeof o.iv||"string"!=typeof o.data)throw new Error("pipeup: this is not an Pipeup feedback file");try{a=await async function(e,n,i){try{let o=await crypto.subtle.decrypt({name:"AES-GCM",iv:t(n.iv),additionalData:r(i)},e,t(n.data));return(new TextDecoder).decode(o)}catch{throw new Error("pipeup: this feedback could not be opened with this document")}}(i,{iv:o.iv,data:o.data},B(n))}catch{throw new Error("pipeup: this feedback could not be opened with this document's key")}try{s=JSON.parse(a)}catch{throw new Error("pipeup: this is not an Pipeup feedback file")}return Array.isArray(s)?s:[]}(e,this.options.doc,this.options.key),"file")}merge(e,t){return e.length>5e3?Promise.reject(new RangeError("pipeup: too many changes to merge at once")):this.enqueue(async()=>{let r=await this.log.add([...e]);this.unsaved.push(...r),r.length>0&&this.refresh(!0,r,t);try{await this.persist()}catch(e){throw r.length>0?new Z(r[0].body.id,e,r.length):e}return r.length})}enqueue(e){let t=this.e.then(e);return this.e=t.catch(()=>{}),t}async write(e){let t=await this.log.append(this.options.identity,this.displayName,e);this.unsaved.push(t),this.refresh(!0,[t],"local");try{await this.persist()}catch(e){throw new Z(t.body.id,e)}return t.body.id}async persist(){if(0===this.unsaved.length)return;let e=[...this.unsaved];await this.options.store.append(this.options.doc,e),this.unsaved=this.unsaved.filter(t=>!e.includes(t))}refresh(e,t=[],r=""){this.cache=this.log.threads(),this.comments.clear();let n=(e,t)=>{e.unnamed&&e.author===this.me&&this.displayName&&(e.name=this.displayName),this.comments.set(e.id,{comment:e,thread:t});for(let r of e.replies)n(r,t)};for(let e of this.cache)n(e.root,e.id);if(e)for(let e of this.listeners)try{e(this.cache,t,r)}catch(e){globalThis.reportError?.(e)}}find(e){let t=this.comments.get(e);if(!t)throw new Error("pipeup: there is no comment with that id");return t}mine(e){let t=this.find(e);if(t.comment.author!==this.me)throw new Error("pipeup: only the writer can change a comment");return t}thread(e){if(!this.cache.some(t=>t.id===e))throw new Error("pipeup: there is no thread with that id");return e}};function V(e){let t=e.trim();if(!t)throw new Error("pipeup: a comment needs some words");if(t.length>w)throw new Error(`pipeup: comments are limited to ${w} characters`);return t}function W(e){if(!N(e))throw new Error("pipeup: a reaction is one emoji");return e}function Q(e){let t=e.replace(/\s+/g," ").trim();if(!t||t.length>80)throw new Error("pipeup: choose a name of 1 to 80 characters");if(y(t))throw new Error("pipeup: that name is kept for AI replies; choose another");return t}var X=class{docs=new Map;profile=null;async load(e){return[...this.docs.get(e)?.values()??[]]}async append(e,t){let r=this.docs.get(e);r||this.docs.set(e,r=new Map);for(let e of t)r.set(e.body.id,e)}async loadProfile(){return this.profile}async saveProfile(e){this.profile=e}async saveProfileIfAbsent(e){return this.profile||(this.profile=e),this.profile}},Y="";async function ee(e,t=""){let r=await e.loadProfile();if(r)return"Reviewer"===r.name?{...r,name:""}:r;let n={identity:await l(),name:t};return e.saveProfileIfAbsent(n)}var te=class e{constructor(e){this.db=e}static open(t="pipeup"){return new Promise((r,n)=>{let i=indexedDB.open(t,1);i.onupgradeneeded=()=>{let e=i.result;e.createObjectStore("ops",{keyPath:["doc","id"]}).createIndex("doc","doc"),e.createObjectStore("meta")},i.onsuccess=()=>{let t=i.result;t.onversionchange=()=>t.close(),r(new e(t))},i.onerror=()=>n(i.error??new Error("pipeup: could not open local storage"))})}close(){this.db.close()}async load(e){return(await this.request("ops","readonly",t=>t.index("doc").getAll(e))).map(e=>e.op)}async append(e,t){if(0===t.length)return;let r=this.db.transaction("ops","readwrite"),n=r.objectStore("ops"),i=re(r);try{for(let r of t)n.put({doc:e,id:r.body.id,op:r})}catch(e){throw r.abort(),i.catch(()=>{}),e}await i}async loadProfile(){return await this.request("meta","readonly",e=>e.get("profile"))??null}async saveProfile(e){await this.request("meta","readwrite",t=>t.put(e,"profile"))}async saveProfileIfAbsent(e){let t=this.db.transaction("meta","readwrite"),r=t.objectStore("meta"),n=re(t),i=e,o=r.get("profile");return o.onsuccess=()=>{o.result?i=o.result:r.put(e,"profile")},await n,i}request(e,t,r){return new Promise((n,i)=>{let o=r(this.db.transaction(e,t).objectStore(e));o.onsuccess=()=>n(o.result),o.onerror=()=>i(o.error??new Error("pipeup: local storage request failed"))})}};function re(e){return new Promise((t,r)=>{e.oncomplete=()=>t(),e.onerror=()=>r(e.error??new Error("pipeup: local storage write failed")),e.onabort=()=>r(e.error??new Error("pipeup: local storage write aborted"))})}function ne(e){let t=(e.ownerDocument??e).createTreeWalker(e,NodeFilter.SHOW_TEXT),r=[],n="";for(let e=t.nextNode();e;e=t.nextNode())r.push({node:e,start:n.length}),n+=e.data;return{text:n,nodes:r}}function ie(e,t,r){let n=(e.ownerDocument??e).createRange();return n.setStart(e,0),n.setEnd(t,r),n.toString().length}function oe(e,t,r){let n=ae(e,t,!1),i=ae(e,r,!0);if(!n||!i||r<t)return null;let o=n.node.ownerDocument.createRange();return o.setStart(n.node,n.offset),o.setEnd(i.node,i.offset),o}function ae(e,t,r){let n=e.nodes.find(e=>t>=e.start&&t<e.start+e.node.data.length+Number(r));return n&&{node:n.node,offset:t-n.start}}function se(e){return e.nodeType===Node.ELEMENT_NODE?e:e.parentElement}function le(e,t){for(let r=se(e)?.closest("[data-pipeup-id]")??null;r;){if(!t.contains(r))return null;let e=r.getAttribute("data-pipeup-id")??"";if(""!==e&&e.length<=200)return r;r=r.parentElement?.closest("[data-pipeup-id]")??null}return null}function de(e,t,r){return e.slice(t,r).replace(/^[\uDC00-\uDFFF]|[\uD800-\uDBFF]$/g,"")}function ue(e,t){let r=function(e,t){if(e===t)return"";let r=[];for(let n=t;n&&n!==e;n=n.parentElement){let e=1;for(let t=n.previousElementSibling;t;t=t.previousElementSibling)t.tagName===n.tagName&&e++;r.unshift(`${n.tagName.toLowerCase()}:nth-of-type(${e})`)}return":scope > "+r.join(" > ")}(e,t);if(r.length>2e3)throw new Error("pipeup: this element is nested too deeply to comment on — give a nearby container a data-pipeup-id");return r}function ce(e){if(!T(e))throw new Error("pipeup: could not describe this place on the page");return e}function he(e,t){let r=se(e),n=r?.closest("p,li,h1,h2,h3,h4,h5,h6,td,th,blockquote,pre,figcaption,dt,dd,summary,caption")??null;return n&&t.contains(n)?n:r&&t.contains(r)?r:t}function pe(e,t,r){if(!t.contains(e.commonAncestorContainer))throw new Error("pipeup: the selection is outside the commentable area");let n=le(e.commonAncestorContainer,t),a=n??t,{text:s}=ne(a),l=ie(a,e.startContainer,e.startOffset),d=ie(a,e.endContainer,e.endOffset),u=s.slice(l,d);if(""===u)throw new Error("pipeup: select some text to comment on");if(u.length>v)throw new Error("pipeup: selections are limited to 10000 characters");let c=de(s,Math.max(0,l-32),l),h=de(s,d,d+32);return ce({...n?{id:n.getAttribute("data-pipeup-id")??""}:{},path:"",quote:{exact:u,prefix:c,suffix:h},...r?{view:r}:{},fingerprint:o(he(e.startContainer,t).textContent??""),snapshot:de(i(c+u+h),0,200)})}function fe(e,t,r,n){let a=le(e,t);return ce({...a?{id:a.getAttribute("data-pipeup-id")??""}:{},path:ue(a??t,e),...r?{point:{x:me(r.x),y:me(r.y)}}:{},...n?{view:n}:{},fingerprint:o(e.textContent??""),snapshot:de(i(e.textContent??""),0,200)})}function me(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function ge(e,t,r){let n=Array.from({length:t.length+1},(e,t)=>t),i=[...n],o=[t.length];for(let a=1;a<=e.length;a++){i[0]=r?0:a;for(let r=1;r<=t.length;r++){let o=e.charCodeAt(a-1)===t.charCodeAt(r-1)?0:1;i[r]=Math.min(n[r]+1,i[r-1]+1,n[r-1]+o)}o.push(i[t.length]),[n,i]=[i,n]}return o}var ye=(e,t)=>ge(e,t,!1).pop(),we={state:"orphaned",element:null,range:null};function be(e,t,r={}){let n=e.id?function(e,t){for(let r of e.querySelectorAll("[data-pipeup-id]"))if(r.getAttribute("data-pipeup-id")===t)return r;return null}(t,e.id):t;return e.quote?function(e,t,r,n,i){let a=r??n,s=ne(a),l=function(e,t){if(!t.exact)return-1;let r=-1,n=-1;for(let i=e.indexOf(t.exact);-1!==i;i=e.indexOf(t.exact,i+1)){let o=e.slice(Math.max(0,i-t.prefix.length),i),a=e.slice(i+t.exact.length,i+t.exact.length+t.suffix.length),s=ve(o,t.prefix)+xe(a,t.suffix);s>n&&(r=i,n=s)}return r}(s.text,t);if(l>=0){let i=oe(s,l,l+t.exact.length);if(i){let t=he(i.startContainer,n);return{state:null!==r&&o(t.textContent??"")===e.fingerprint?"attached":"moved",element:t,range:i}}}if(i){let e=a===n?s:ne(n);if(e.text.length<=5e4&&t.exact.length>=12&&t.exact.length<=300){let r=function(e,t,r){let n=t.length;if(0===n)return null;let i=-1,o=1/0;if(ge(e,t,!0).forEach((e,t)=>{t&&e<o&&(o=e,i=t)}),o>r)return null;let a=Math.max(0,i-n),s=1/0;for(let o=Math.max(0,i-n-r);o<=Math.min(i,i-n+r);o++){let r=ye(e.slice(o,i),t);r<s&&(s=r,a=o)}return{start:a,end:i,distance:s}}(e.text,t.exact,Math.floor(t.exact.length/4)),i=r?oe(e,r.start,r.end):null;if(i)return{state:"moved",element:he(i.startContainer,n),range:i}}}return we}(e,e.quote,n,t,!1!==r.fuzzy):function(e,t){if(!t)return we;let r=t;if(e.path){if(!e.path.startsWith(":scope > "))return we;try{r=t.querySelector(e.path)}catch{return we}}return r?{state:o(r.textContent??"")===e.fingerprint?"attached":"moved",element:r,range:null}:we}(e,n)}function xe(e,t){let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)r++;return r}function ve(e,t){let r=0;for(;r<e.length&&r<t.length&&e[e.length-1-r]===t[t.length-1-r];)r++;return r}var ke={A:"Link",BUTTON:"Button",P:"Paragraph",LI:"List item",IMG:"Image",TABLE:"Table",TD:"Cell",TH:"Cell",FIGURE:"Figure",SVG:"Graphic",CANVAS:"Graphic",LABEL:"Label",INPUT:"Field",SELECT:"Field",TEXTAREA:"Field",SUMMARY:"Question",BLOCKQUOTE:"Quote",SECTION:"Section",H1:"Heading",H2:"Heading",H3:"Heading",H4:"Heading",H5:"Heading",H6:"Heading"};function Ae(e){return e.getAttribute("data-pipeup-label")||ke[e.tagName.toUpperCase()]||"Block"}function Ee(e){let t=e.getAttribute("data-pipeup-label");if(t)return t;let r=function(e){return Me(i(e.getAttribute("aria-label")??e.getAttribute("alt")??e.innerText??e.textContent??""),40)}(e);return r?`${Ae(e)} · ${r}`:Ae(e)}function $e(e,t,r){let n=e.id??null,o=e.quote?.exact??null,a=e.point?`${Math.round(100*e.point.x)}% across, ${Math.round(100*e.point.y)}% down the element`:null,s=t.element;if("orphaned"===t.state||!s)return{where:`No longer on the page (it read: "${e.snapshot}")`,element:null,id:n,quote:o,pin:a};let l=[],d=e.view?.slide;if(d){let e=s.closest("[data-pipeup-slide]")?.querySelector("h1,h2,h3")?.textContent;l.push(`Slide ${d}`+(e?` "${Me(i(e))}"`:""))}else{let t=function(e){return e?e.label||Object.entries(e).filter(([e,t])=>t&&"slide"!==e).map(([,e])=>e).join(" · "):""}(e.view);t&&l.push(t);let n=function(e,t){let r=null;for(let n of t.querySelectorAll("h1,h2,h3")){if(n===e||n.contains(e))break;if(!(4&n.compareDocumentPosition(e)))break;r=n}return r}(s,r);n&&l.push(`Section "${Me(i(n.textContent??""))}"`)}let u=Ee(s);return l.push(u),{where:l.join(" › "),element:u,id:n,quote:o,pin:a}}function Me(e,t=60){return e.length>t?e.slice(0,t-1)+"…":e}var Se="Each thread says where it is: the slide or section, the element (its data-pipeup-id attribute in the HTML), and the exact quoted text or pin position. Work through the open threads in order, and for each one say what you changed or why you did not. Answer in the thread (the Pipeup skill says how) and mark it addressed; never resolve it, the author does.";function Ce(e,t){let r=Math.max(0,Math.round((t-e)/1e3));if(r<60)return"just now";let n=Math.round(r/60);if(n<60)return`${n}m ago`;let i=Math.round(n/60);return i<48?`${i}h ago`:`${Math.round(i/24)}d ago`}function Ne(e,t,r,n){return"ai"===t?je(e,"## Comment thread",n,r):Te(e)}function Oe(e,t,r){let n=r.all?e:e.filter(e=>!e.thread.resolved);if("text"===t)return n.map(Te).join("\n");let i=r.all?0:e.length-n.length,o=[`# Review comments: ${qe(r.title)}`,"",`- **Page:** ${qe(r.url)}`,`- **Exported:** ${r.exportedAt.toISOString()}`,`- **Open threads:** ${e.length-e.filter(e=>e.thread.resolved).length}${i?` (${i} resolved, not included)`:r.all?" (resolved ones included)":""}`,"",Se,"",""].join("\n"),a=r.exportedAt.getTime();return o+n.map((e,t)=>je(e,`## Thread ${t+1}`,a)).join("\n")}function Pe(e){return e.reactions.map(e=>`${e.emoji} ${e.by.length} (${e.by.map(e=>qe(m(e))).join(", ")})`).join(" · ")}function qe(e){return e.replace(/\s+/g," ").trim()}function je(e,t,r,n){let{thread:i,location:o}=e,a=i.root.replies.length,s=[`${t} · ${i.resolved?"resolved":i.addressed?"open, addressed":"open"}`];if(s.push(`- **Thread:** ${i.id}`),n&&s.push(`- **Page:** ${qe(n)}`),s.push(`- **Where:** ${qe(o.where)}`),o.id){let e=qe(o.id.replace(/`/g,""));s.push(`- **Element:** \`[data-pipeup-id="${e}"]\`${o.element?` (${qe(o.element)})`:""}`)}o.quote&&s.push(`- **Quoted text:** "${qe(o.quote)}"`),o.pin&&s.push(`- **Pin:** ${qe(o.pin)}`),i.addressed&&!i.resolved&&s.push(`- **Addressed:** ${qe(i.addressed.text)} (${qe(m(i.addressed))}, ${Ce(i.addressed.at,r)})`),s.push(`- **Started by:** ${qe(m(i.root))}, ${Ce(i.root.at,r)}${a?` · ${a} ${1===a?"reply":"replies"}`:""}`,"",`**${qe(m(i.root))}** (${Ce(i.root.at,r)}): ${Ie(i.root," ")}`),i.root.reactions.length&&s.push(`Reactions: ${Pe(i.root)}`);for(let e of i.root.replies)s.push(`- **${qe(m(e))}** (${Ce(e.at,r)}): ${Ie(e," ")} \x3c!-- comment:${e.id} --\x3e`),e.reactions.length&&s.push(` - Reactions: ${Pe(e)}`);return s.join("\n")+"\n"}function Te(e){let{thread:t,location:r}=e,n=[qe(r.where)+(r.quote?`, on the text "${qe(r.quote)}"`:""),`${qe(m(t.root))}: ${Ie(t.root," ")}`];t.root.reactions.length&&n.push(` Reactions: ${Pe(t.root)}`);for(let e of t.root.replies)n.push(` ${qe(m(e))}: ${Ie(e," ")}`),e.reactions.length&&n.push(` Reactions: ${Pe(e)}`);return n.join("\n")+"\n"}function Ie(e,t){return e.deleted?"(deleted)":e.text.replace(/\r\n|\r|\n/g,"\n"+t)+(e.edited?" (edited)":"")}var Fe="0.7.0-beta.1",De="2026-10-13";export{g as AI_NAME,c as ANIMALS,De as BUILT,h as COLOURS,Y as DEFAULT_PROFILE_NAME,te as IndexedDbStore,X as MemoryStore,J as PipeupDocument,Z as UnsavedChangeError,Fe as VERSION,f as animalName,U as computeOpId,Oe as copyAll,Ne as copyThread,l as createIdentity,fe as describeElement,pe as describeRange,Ce as formatAgo,y as isAiName,Ee as labelOf,ee as loadOrCreateProfile,$e as locate,m as nameOf,L as newDocumentAttribute,_ as parseDocumentAttribute,be as resolveAnchor,O as signOp};