pipeup 0.5.4 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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.5.4).** The API and the stored comment format may change before 1.0; pin an exact version.
5
+ > **Alpha (0.6.0).** 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.5.4/dist/pipeup.min.js" integrity="sha384-…" crossorigin="anonymous" defer></script>
24
+ <script src="https://cdn.jsdelivr.net/npm/pipeup@0.6.0/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/link.mjs ADDED
@@ -0,0 +1,133 @@
1
+ // pipeup watch / pipeup comments: the live link between a page shown from this computer and an agent on it.
2
+ // Everything stays on this computer: the server listens on 127.0.0.1 only, and answers only the page it serves.
3
+ import { randomBytes } from "node:crypto";
4
+ import { createServer } from "node:http";
5
+ import { readFile, rename, writeFile } from "node:fs/promises";
6
+ import { basename, dirname, extname, join, resolve, sep } from "node:path";
7
+
8
+ const TYPES = {
9
+ ".html": "text/html; charset=utf-8",
10
+ ".js": "text/javascript; charset=utf-8",
11
+ ".mjs": "text/javascript; charset=utf-8",
12
+ ".css": "text/css; charset=utf-8",
13
+ ".json": "application/json; charset=utf-8",
14
+ ".svg": "image/svg+xml",
15
+ ".png": "image/png",
16
+ ".jpg": "image/jpeg",
17
+ ".jpeg": "image/jpeg",
18
+ ".gif": "image/gif",
19
+ ".webp": "image/webp",
20
+ ".ico": "image/x-icon",
21
+ ".woff2": "font/woff2",
22
+ ".txt": "text/plain; charset=utf-8",
23
+ ".md": "text/markdown; charset=utf-8",
24
+ };
25
+ const MAX_BODY = 8 * 1024 * 1024;
26
+ const attr = (v) => v.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
27
+
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) => {
31
+ let tag = rest;
32
+ const listed = /\sdata-pipeup-agents\s*=\s*"([^"]*)"/i.exec(tag);
33
+ if (listed) tag = tag.replace(listed[0], ` data-pipeup-agents="${attr(`${listed[1]} ${key}`.trim())}"`);
34
+ else tag += ` data-pipeup-agents="${key}"`;
35
+ tag += ` data-pipeup-link="${base}" data-pipeup-link-agent="${attr(agent)}" data-pipeup-link-file="${attr(file)}"`;
36
+ return `<html${tag}>`;
37
+ });
38
+ }
39
+
40
+ /** Starts the link for a page file. Resolves to { url, close }. */
41
+ export async function watch({ page, agent, key, port = 0, log = console.log }) {
42
+ const file = resolve(page);
43
+ const dir = dirname(file);
44
+ const name = basename(file);
45
+ const base = `/__pipeup/${randomBytes(18).toString("base64url")}`;
46
+ const sidecar = file.replace(/\.[^./\\]*$/, "") + ".comments.json";
47
+ let origin = "";
48
+ let host = "";
49
+
50
+ const send = (res, status, body = "", type = "text/plain; charset=utf-8") => {
51
+ res.writeHead(status, {
52
+ "content-type": type,
53
+ "cache-control": "no-store",
54
+ "x-content-type-options": "nosniff",
55
+ });
56
+ res.end(body);
57
+ };
58
+
59
+ const server = createServer(async (req, res) => {
60
+ try {
61
+ // Only this computer's own address: a name that points here from another site is refused.
62
+ if (req.headers.host !== host) return send(res, 403, "wrong host");
63
+ const url = new URL(req.url, origin);
64
+ if (url.pathname.startsWith("/__pipeup/")) {
65
+ if (url.pathname !== `${base}/comments` || req.method !== "POST") return send(res, 404, "not found");
66
+ if (req.headers.origin !== origin) return send(res, 403, "wrong origin");
67
+ const chunks = [];
68
+ let size = 0;
69
+ for await (const c of req) {
70
+ size += c.length;
71
+ if (size > MAX_BODY) return send(res, 413, "too big");
72
+ chunks.push(c);
73
+ }
74
+ let body;
75
+ try {
76
+ body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
77
+ } catch {
78
+ return send(res, 400, "not json");
79
+ }
80
+ if (body?.v !== 1 || !body.open || !body.all) return send(res, 400, "not a comments snapshot");
81
+ const tmp = `${sidecar}.${process.pid}.tmp`;
82
+ await writeFile(tmp, JSON.stringify(body));
83
+ await rename(tmp, sidecar);
84
+ log(`Shared ${body.open.threads.length} open comment${body.open.threads.length === 1 ? "" : "s"}.`);
85
+ return send(res, 204);
86
+ }
87
+ if (req.method !== "GET" && req.method !== "HEAD") return send(res, 405, "method not allowed");
88
+ let path = decodeURIComponent(url.pathname);
89
+ if (path === "/") path = `/${name}`;
90
+ const target = resolve(join(dir, path));
91
+ if (target !== dir && !target.startsWith(dir + sep)) return send(res, 404, "not found");
92
+ let bytes;
93
+ try {
94
+ bytes = await readFile(target);
95
+ } catch {
96
+ return send(res, 404, "not found");
97
+ }
98
+ if (target === file) bytes = Buffer.from(served(bytes.toString("utf8"), { base, agent, key, file }));
99
+ send(
100
+ res,
101
+ 200,
102
+ req.method === "HEAD" ? "" : bytes,
103
+ TYPES[extname(target).toLowerCase()] ?? "application/octet-stream",
104
+ );
105
+ } catch {
106
+ send(res, 500, "error");
107
+ }
108
+ });
109
+ await new Promise((ok) => server.listen(port, "127.0.0.1", ok));
110
+ const { port: bound } = server.address();
111
+ origin = `http://127.0.0.1:${bound}`;
112
+ host = `127.0.0.1:${bound}`;
113
+ return {
114
+ url: `${origin}/${encodeURIComponent(name)}`,
115
+ sidecar,
116
+ close: () => new Promise((ok) => server.close(ok)),
117
+ };
118
+ }
119
+
120
+ /** What `pipeup comments` prints: the shared comments, as Markdown or as data. */
121
+ export async function comments({ page, all = false, json = false }) {
122
+ const sidecar = resolve(page).replace(/\.[^./\\]*$/, "") + ".comments.json";
123
+ let shared;
124
+ try {
125
+ shared = JSON.parse(await readFile(sidecar, "utf8"));
126
+ } catch {
127
+ throw new Error(
128
+ `nothing is shared for ${page} yet. Start the link (pipeup watch ${page}), open the page it prints, and switch on Share with my agent`,
129
+ );
130
+ }
131
+ const view = all ? shared.all : shared.open;
132
+ return json ? JSON.stringify({ at: shared.at, ...view }, null, 2) : view.markdown;
133
+ }
package/cli/pipeup.mjs ADDED
@@ -0,0 +1,211 @@
1
+ #!/usr/bin/env node
2
+ // pipeup agent / pipeup reply: how an AI agent answers comments on a Pipeup page.
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";
5
+ import { homedir } from "node:os";
6
+ import { basename, dirname, join, resolve } from "node:path";
7
+ import { comments, watch } from "./link.mjs";
8
+ import * as skills from "./skills.mjs";
9
+
10
+ // The page library, loaded only by the commands that sign or read a page: `skills` and `comments` need nothing built.
11
+ const core = () => import("../dist/pipeup.core.js");
12
+
13
+ const KEYFILE = process.env.PIPEUP_AGENT_FILE || join(homedir(), ".pipeup", "agent.json");
14
+ const AI = "AI assistant";
15
+
16
+ const USAGE = `pipeup skills install|remove|list [--project] [--agent claude|codex|all] [--yes] [--replace] [--dry-run]
17
+ Puts Pipeup's agent skills where Claude Code (.claude/skills) and Codex (.agents/skills) look: for you, in every
18
+ project, or with --project for this folder only. It says what it will write, asks first (--yes to go ahead without
19
+ asking), and never replaces a skill you changed unless you say --replace.
20
+
21
+ pipeup agent [--name <name>]
22
+ Makes this computer's agent key (once) and prints the public key to list on the page:
23
+ <html data-pipeup-agents="<key>">
24
+
25
+ pipeup watch <page.html> [--agent <name>] [--port <number>]
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.
28
+
29
+ pipeup comments <page.html> [--all] [--json]
30
+ Prints the comments the page has shared (open threads, or all with --all), as Markdown or, with --json, as data.
31
+
32
+ pipeup reply --page <file.html> --thread <id> "<words>" [--addressed "<short note>"]
33
+ Writes a signed reply (and, with --addressed, an addressed note) to <file>.replies.js next to the page.
34
+ It never resolves, reopens, edits or deletes anything: the author closes threads.`;
35
+
36
+ function fail(message) {
37
+ console.error(`pipeup: ${message}`);
38
+ process.exit(1);
39
+ }
40
+
41
+ function flags(argv) {
42
+ const out = { _: [] };
43
+ for (let i = 0; i < argv.length; i++) {
44
+ const a = argv[i];
45
+ if (a.startsWith("--")) {
46
+ const next = argv[i + 1];
47
+ if (next === undefined || next.startsWith("--")) out[a.slice(2)] = true;
48
+ else ((out[a.slice(2)] = next), i++);
49
+ } else out._.push(a);
50
+ }
51
+ return out;
52
+ }
53
+
54
+ const b64u = (bytes) => Buffer.from(bytes).toString("base64url");
55
+
56
+ async function loadAgent(name) {
57
+ let saved = null;
58
+ try {
59
+ saved = JSON.parse(await readFile(KEYFILE, "utf8"));
60
+ } catch {
61
+ // none yet
62
+ }
63
+ if (!saved) {
64
+ const pair = await crypto.subtle.generateKey({ name: "Ed25519" }, true, ["sign", "verify"]);
65
+ const raw = new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey));
66
+ saved = {
67
+ name: typeof name === "string" ? name : "Agent",
68
+ publicKey: b64u(raw),
69
+ privateKey: await crypto.subtle.exportKey("jwk", pair.privateKey),
70
+ };
71
+ await mkdir(dirname(KEYFILE), { recursive: true, mode: 0o700 });
72
+ await writeFile(KEYFILE, JSON.stringify(saved), { mode: 0o600 });
73
+ await chmod(KEYFILE, 0o600);
74
+ } else if (typeof name === "string" && name !== saved.name) {
75
+ saved.name = name;
76
+ await writeFile(KEYFILE, JSON.stringify(saved), { mode: 0o600 });
77
+ }
78
+ const privateKey = await crypto.subtle.importKey("jwk", saved.privateKey, { name: "Ed25519" }, false, [
79
+ "sign",
80
+ ]);
81
+ return { identity: { publicKey: saved.publicKey, privateKey }, name: saved.name };
82
+ }
83
+
84
+ /** A name that shows it is an agent: "AI assistant · Claude". */
85
+ const signedName = (name) => (name && name !== AI ? `${AI} · ${name}`.slice(0, 80) : AI);
86
+
87
+ async function pageDoc(file) {
88
+ const html = await readFile(file, "utf8");
89
+ const m = /<html\b[^>]*\sdata-pipeup-doc\s*=\s*["']([^"']+)["']/i.exec(html);
90
+ if (!m) fail(`${file} has no data-pipeup-doc attribute; add Pipeup to the page first`);
91
+ const { id } = await (await core()).parseDocumentAttribute(m[1]);
92
+ const listed = /<html\b[^>]*\sdata-pipeup-agents\s*=\s*["']([^"']*)["']/i.exec(html)?.[1] ?? "";
93
+ return { id, listed: listed.split(/[\s,]+/).filter(Boolean) };
94
+ }
95
+
96
+ const headerOf = (file) =>
97
+ `// Replies to the comments on ${basename(file)}. Written by \`pipeup reply\`; safe to keep with the page.\n`;
98
+
99
+ async function readReplies(path, doc) {
100
+ try {
101
+ const text = await readFile(path, "utf8");
102
+ const m = /push\((\{.*\})\);\s*$/m.exec(text);
103
+ const file = m && JSON.parse(m[1]);
104
+ return file && file.doc === doc && Array.isArray(file.ops) ? file.ops : [];
105
+ } catch {
106
+ return [];
107
+ }
108
+ }
109
+
110
+ async function reply(args) {
111
+ const page = args.page;
112
+ const thread = args.thread;
113
+ const words = args._[0]?.trim();
114
+ if (typeof page !== "string" || typeof thread !== "string" || !words)
115
+ fail(`missing words, --page or --thread\n\n${USAGE}`);
116
+ const note = typeof args.addressed === "string" ? args.addressed.trim() : "";
117
+ const { id: doc, listed } = await pageDoc(page);
118
+ const { identity, name } = await loadAgent();
119
+ const linked = await readFile(page.replace(/\.[^./\\]*$/, "") + ".comments.json", "utf8").then(
120
+ () => true,
121
+ () => false,
122
+ );
123
+ if (!listed.includes(identity.publicKey) && !linked)
124
+ console.warn(
125
+ `pipeup: this page doesn't list your key yet, so it will ignore these replies.\n Add: <html data-pipeup-agents="${identity.publicKey}">`,
126
+ );
127
+ const out = resolve(page.replace(/\.[^./\\]*$/, "") + ".replies.js");
128
+ const ops = await readReplies(out, doc);
129
+ // Seconds since 1970: later than any counter a browser has kept, so these follow the thread they answer.
130
+ let clock = Math.max(Math.floor(Date.now() / 1000), ...ops.map((o) => o.body.clock + 1));
131
+ let at = Date.now();
132
+ const make = async (fields) => {
133
+ const body = {
134
+ v: 1,
135
+ ...fields,
136
+ id: "",
137
+ doc,
138
+ author: identity.publicKey,
139
+ name: signedName(name),
140
+ clock: clock++,
141
+ at: at++,
142
+ };
143
+ const { computeOpId, signOp } = await core();
144
+ body.id = await computeOpId(body);
145
+ return signOp(body, identity);
146
+ };
147
+ const added = [await make({ kind: "reply", thread, target: thread, text: words })];
148
+ if (note) added.push(await make({ kind: "addressed", thread, text: note }));
149
+ const file = { format: "pipeup-replies", v: 1, doc, ops: [...ops, ...added] };
150
+ await writeFile(out, `${headerOf(page)}(globalThis.pipeupReplies ||= []).push(${JSON.stringify(file)});\n`);
151
+ console.log(`Wrote ${added.length} ${added.length === 1 ? "entry" : "entries"} to ${out}`);
152
+ }
153
+
154
+ const [command, ...rest] = process.argv.slice(2);
155
+ const args = flags(rest);
156
+ if (command === "agent") {
157
+ const { identity, name } = await loadAgent(args.name);
158
+ console.log(
159
+ `${name} (${KEYFILE})\n\nList this key on the page:\n <html data-pipeup-agents="${identity.publicKey}">`,
160
+ );
161
+ } else if (command === "reply") await reply(args);
162
+ else if (command === "skills") {
163
+ const sub = args._[0];
164
+ const opts = {
165
+ agent: typeof args.agent === "string" ? args.agent : "all",
166
+ project: args.project === true,
167
+ yes: args.yes === true,
168
+ replace: args.replace === true,
169
+ dryRun: args["dry-run"] === true,
170
+ };
171
+ try {
172
+ if (sub === "install" || sub === "update") await skills.install(opts);
173
+ else if (sub === "remove") await skills.remove(opts);
174
+ else if (sub === "list") await skills.list(opts);
175
+ else fail(`skills: say install, remove or list\n\n${USAGE}`);
176
+ } catch (e) {
177
+ fail(e.message);
178
+ }
179
+ } else if (command === "comments") {
180
+ const page = args._[0];
181
+ if (!page) fail(`missing the page\n\n${USAGE}`);
182
+ try {
183
+ console.log(await comments({ page, all: args.all === true, json: args.json === true }));
184
+ } catch (e) {
185
+ fail(e.message);
186
+ }
187
+ } else if (command === "watch") {
188
+ const page = args._[0];
189
+ if (!page) fail(`missing the page\n\n${USAGE}`);
190
+ await pageDoc(page);
191
+ 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
+ });
198
+ console.log(`Open this page: ${link.url}\n`);
199
+ console.log(
200
+ `While this runs, ${name} is listed for the page and the page offers "Share with my agent" (off until you switch it on).`,
201
+ );
202
+ console.log(
203
+ `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
+ );
205
+ const stop = () => link.close().then(() => process.exit(0));
206
+ process.on("SIGINT", stop);
207
+ process.on("SIGTERM", stop);
208
+ } else {
209
+ console.log(USAGE);
210
+ process.exit(command ? 1 : 0);
211
+ }
package/cli/skills.mjs ADDED
@@ -0,0 +1,154 @@
1
+ // pipeup skills install | remove | list: puts Pipeup's agent skills where Claude Code and Codex look for them.
2
+ // It writes only SKILL.md files and a small marker beside each (so it can tell its own from yours), asks before
3
+ // replacing one you changed, and makes no network request: the skills ship inside this package.
4
+ import { createHash } from "node:crypto";
5
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
6
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
7
+ import { homedir } from "node:os";
8
+ import { join } from "node:path";
9
+ import { createInterface } from "node:readline/promises";
10
+
11
+ const MARKER = ".pipeup-installed";
12
+ const sha = (text) => createHash("sha256").update(text).digest("hex");
13
+
14
+ /** Where the skills come from: inside this package, or (running from the repository) the one source. */
15
+ function sourceDir() {
16
+ for (const rel of ["../skills", "../../../../apps/agent-skills"]) {
17
+ const dir = new URL(`${rel}/`, import.meta.url).pathname;
18
+ if (existsSync(dir)) return dir;
19
+ }
20
+ throw new Error("this copy of pipeup doesn't carry the skills");
21
+ }
22
+
23
+ function loadSkills() {
24
+ const dir = sourceDir();
25
+ return readdirSync(dir)
26
+ .filter((n) => n.startsWith("pipeup-") && existsSync(join(dir, n, "SKILL.md")))
27
+ .sort()
28
+ .map((name) => ({ name, text: readFileSync(join(dir, name, "SKILL.md"), "utf8") }));
29
+ }
30
+
31
+ const version = () => JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
32
+
33
+ /** The places to write: each agent's skills folder, for the person (every project) or for this project only. */
34
+ export function targets({
35
+ agent = "all",
36
+ project = false,
37
+ home = process.env.PIPEUP_SKILLS_HOME || homedir(),
38
+ cwd = process.cwd(),
39
+ }) {
40
+ const base = project ? cwd : home;
41
+ const out = [];
42
+ if (agent === "all" || agent === "claude")
43
+ out.push({ agent: "Claude Code", dir: join(base, ".claude", "skills") });
44
+ if (agent === "all" || agent === "codex")
45
+ out.push({ agent: "Codex", dir: join(base, ".agents", "skills") });
46
+ if (!out.length) throw new Error(`unknown agent "${agent}": use claude, codex or all`);
47
+ return out;
48
+ }
49
+
50
+ /** What is there now for one skill: nothing, ours and unchanged, or changed by you (or not ours). */
51
+ async function stateOf(dir, name) {
52
+ const file = join(dir, name, "SKILL.md");
53
+ if (!existsSync(file)) return "new";
54
+ const text = await readFile(file, "utf8");
55
+ try {
56
+ const marker = JSON.parse(await readFile(join(dir, name, MARKER), "utf8"));
57
+ return marker.sha256 === sha(text) ? "ours" : "changed";
58
+ } catch {
59
+ return "changed";
60
+ }
61
+ }
62
+
63
+ async function ask(question) {
64
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
65
+ try {
66
+ return /^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim());
67
+ } finally {
68
+ rl.close();
69
+ }
70
+ }
71
+
72
+ export async function install(o) {
73
+ const skills = loadSkills();
74
+ const where = targets(o);
75
+ const plan = [];
76
+ for (const t of where)
77
+ for (const s of skills)
78
+ plan.push({ ...t, ...s, state: await stateOf(t.dir, s.name), path: join(t.dir, s.name, "SKILL.md") });
79
+ const say = o.log ?? console.log;
80
+ say(`Pipeup skills ${version()} (${skills.length}) will be written to:`);
81
+ for (const t of where) say(` ${t.agent}: ${t.dir}`);
82
+ const mine = (st) => plan.filter((p) => p.state === st).length;
83
+ say(
84
+ ` ${mine("new")} new, ${mine("ours")} already from Pipeup (updated if different), ${mine("changed")} you have changed or didn't come from here`,
85
+ );
86
+ if (mine("changed")) say(" Skills you have changed are left alone unless you choose to replace them.");
87
+ if (o.dryRun) return { written: 0, skipped: 0, dry: true };
88
+ if (!o.yes) {
89
+ if (!process.stdin.isTTY) {
90
+ say(
91
+ "Nothing written. Run it again with --yes to go ahead (--replace also replaces skills you changed).",
92
+ );
93
+ return { written: 0, skipped: plan.length };
94
+ }
95
+ if (!(await ask("Go ahead?"))) return { written: 0, skipped: plan.length };
96
+ }
97
+ let written = 0;
98
+ let skipped = 0;
99
+ for (const p of plan) {
100
+ if (p.state === "changed") {
101
+ const replace =
102
+ o.replace ||
103
+ (process.stdin.isTTY && !o.yes ? await ask(`${p.path} has been changed. Replace it?`) : false);
104
+ if (!replace) {
105
+ say(` kept yours: ${p.path}`);
106
+ skipped++;
107
+ continue;
108
+ }
109
+ }
110
+ await mkdir(join(p.dir, p.name), { recursive: true });
111
+ await writeFile(p.path, p.text);
112
+ await writeFile(
113
+ join(p.dir, p.name, MARKER),
114
+ JSON.stringify({ version: version(), sha256: sha(p.text) }) + "\n",
115
+ );
116
+ written++;
117
+ }
118
+ say(
119
+ `Wrote ${written} skill${written === 1 ? "" : "s"}${skipped ? `, kept ${skipped} of yours` : ""}. Restart the agent if it was open.`,
120
+ );
121
+ return { written, skipped };
122
+ }
123
+
124
+ export async function remove(o) {
125
+ const say = o.log ?? console.log;
126
+ const skills = loadSkills();
127
+ let removed = 0;
128
+ for (const t of targets(o))
129
+ for (const s of skills) {
130
+ const state = await stateOf(t.dir, s.name);
131
+ if (state === "new") continue;
132
+ if (state === "changed" && !o.replace) {
133
+ say(` kept (not from Pipeup, or changed by you): ${join(t.dir, s.name)}`);
134
+ continue;
135
+ }
136
+ if (o.dryRun) say(` would remove ${join(t.dir, s.name)}`);
137
+ else await rm(join(t.dir, s.name), { recursive: true, force: true });
138
+ removed++;
139
+ }
140
+ say(`${o.dryRun ? "Would remove" : "Removed"} ${removed} skill${removed === 1 ? "" : "s"}.`);
141
+ return { removed };
142
+ }
143
+
144
+ export async function list(o) {
145
+ const say = o.log ?? console.log;
146
+ const skills = loadSkills();
147
+ for (const t of targets(o)) {
148
+ say(`${t.agent}: ${t.dir}`);
149
+ for (const s of skills)
150
+ say(
151
+ ` ${s.name}: ${{ new: "not installed", ours: "installed", changed: "there, but not from Pipeup or changed" }[await stateOf(t.dir, s.name)]}`,
152
+ );
153
+ }
154
+ }
@@ -1 +1 @@
1
- function e(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function t(e){let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function r(e){return(new TextEncoder).encode(e)}function n(e){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return"["+e.map(n).join(",")+"]";let t=e;return"{"+Object.keys(t).filter(e=>void 0!==t[e]).sort().map(e=>JSON.stringify(e)+":"+n(t[e])).join(",")+"}"}function i(e){return e.replace(/\s+/g," ").trim()}function o(e){let t=i(e),r=2166136261;for(let e=0;e<t.length;e++)r^=t.charCodeAt(e),r=Math.imul(r,16777619)>>>0;return r.toString(16).padStart(8,"0")}var a=/^[A-Za-z0-9_-]{43}$/,s=new Map;async function l(){let t=await crypto.subtle.generateKey({name:"Ed25519"},!1,["sign","verify"]);return{publicKey:e(new Uint8Array(await crypto.subtle.exportKey("raw",t.publicKey))),privateKey:t.privateKey}}async function u(t,r){let n=await crypto.subtle.sign({name:"Ed25519"},t.privateKey,r);return e(new Uint8Array(n))}var d=1e4,c=2**40,h=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"]);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 u(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 E(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>c||"number"!=typeof n.at||!Number.isSafeInteger(n.at)||n.at<0||n.at>h||void 0!==n.text&&(!b(n.text,d)||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)&&!n.text||("reply"===n.kind||"edit"===n.kind||"delete"===n.kind)&&!n.target||"create"===n.kind&&(n.id!==n.thread||!A(n.anchor)))}function k(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;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(!E(r)||r.body.doc!==this.doc||this.ops.has(r.body.id)||r.body.id!==await S(r.body)||!await k(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,c),at:Math.min(Math.max(Date.now(),"create"===r.kind?(this.createAt.get(e.publicKey)??0)+1:(this.threadAt.get(r.thread)??0)+1),h)};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||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 u(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>d)throw new Error(`pipeup: comments are limited to ${d} 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 l(),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),l=X(a,e.startContainer,e.startOffset),u=X(a,e.endContainer,e.endOffset),d=s.slice(l,u);if(""===d)throw new Error("pipeup: select some text to comment on");if(d.length>p)throw new Error("pipeup: selections are limited to 10000 characters");let c=ne(s,Math.max(0,l-32),l),h=ne(s,u,u+32);return oe({...n?{id:n.getAttribute("data-pipeup-id")??""}:{},path:"",quote:{exact:d,prefix:c,suffix:h},...r?{view:r}:{},fingerprint:o(ae(e.startContainer,t).textContent??""),snapshot:ne(i(c+d+h),0,200)})}function le(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:ue(r.x),y:ue(r.y)}}:{},...n?{view:n}:{},fingerprint:o(e.textContent??""),snapshot:ne(i(e.textContent??""),0,200)})}function ue(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function de(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 ce=(e,t)=>de(e,t,!1).pop(),he={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),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=me(o,t.prefix)+fe(a,t.suffix);s>n&&(r=i,n=s)}return r}(s.text,t);if(l>=0){let i=Y(s,l,l+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(de(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=ce(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 he}(e,e.quote,n,t,!1!==r.fuzzy):function(e,t){if(!t)return he;let r=t;if(e.path){if(!e.path.startsWith(":scope > "))return he;try{r=t.querySelector(e.path)}catch{return he}}return r?{state:o(r.textContent??"")===e.fingerprint?"attached":"moved",element:r,range:null}:he}(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 l=[],u=e.view?.slide;if(u){let e=s.closest("[data-pipeup-slide]")?.querySelector("h1,h2,h3")?.textContent;l.push(`Slide ${u}`+(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&&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 "${xe(i(n.textContent??""))}"`)}let d=we(s);return l.push(d),{where:l.join(" › "),element:d,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.";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 Ee(e,t,r,n){return"ai"===t?Me(e,"## Comment thread",n,r):Se(e)}function ke(e,t,r){let n=e.filter(e=>!e.thread.resolved);if("text"===t)return n.map(Se).join("\n");let i=e.length-n.length,o=[`# Review comments: ${$e(r.title)}`,"",`- **Page:** ${$e(r.url)}`,`- **Exported:** ${r.exportedAt.toISOString()}`,`- **Open threads:** ${n.length}${i?` (${i} resolved, not 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":"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)}`),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.5.4";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,ke as copyAll,Ee as copyThread,l as createIdentity,le 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 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};