@phnx-labs/artifacts-cli 0.3.9 → 0.4.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 (41) hide show
  1. package/CHANGELOG.md +101 -0
  2. package/README.md +43 -14
  3. package/dist/cli.d.ts +2 -1
  4. package/dist/cli.js +47 -14
  5. package/dist/cli.js.map +1 -1
  6. package/dist/commands/new.d.ts +1 -0
  7. package/dist/commands/new.js +11 -2
  8. package/dist/commands/new.js.map +1 -1
  9. package/dist/lib/collab.d.ts +61 -0
  10. package/dist/lib/collab.js +714 -0
  11. package/dist/lib/collab.js.map +1 -0
  12. package/dist/lib/fonts.d.ts +3 -0
  13. package/dist/lib/fonts.js +68 -12
  14. package/dist/lib/fonts.js.map +1 -1
  15. package/dist/lib/highlights.d.ts +11 -1
  16. package/dist/lib/highlights.js +38 -71
  17. package/dist/lib/highlights.js.map +1 -1
  18. package/dist/lib/reader-anchors.d.ts +16 -0
  19. package/dist/lib/reader-anchors.js +146 -0
  20. package/dist/lib/reader-anchors.js.map +1 -0
  21. package/dist/lib/render.d.ts +11 -1
  22. package/dist/lib/render.js +189 -13
  23. package/dist/lib/render.js.map +1 -1
  24. package/dist/lib/section-collapse.d.ts +17 -0
  25. package/dist/lib/section-collapse.js +113 -0
  26. package/dist/lib/section-collapse.js.map +1 -0
  27. package/dist/lib/share.d.ts +17 -0
  28. package/dist/lib/share.js +52 -23
  29. package/dist/lib/share.js.map +1 -1
  30. package/dist/lib/templates.d.ts +23 -1
  31. package/dist/lib/templates.js +113 -3
  32. package/dist/lib/templates.js.map +1 -1
  33. package/dist/lib/tokens.d.ts +2 -0
  34. package/dist/lib/tokens.js +5 -1
  35. package/dist/lib/tokens.js.map +1 -1
  36. package/fonts/Inter-OFL.txt +92 -0
  37. package/fonts/InterVariable.woff2 +0 -0
  38. package/fonts/JetBrainsMono-OFL.txt +93 -0
  39. package/fonts/JetBrainsMono-wght.woff2 +0 -0
  40. package/fonts/README.md +16 -0
  41. package/package.json +4 -1
@@ -0,0 +1,714 @@
1
+ import { createHash } from 'node:crypto';
2
+ /**
3
+ * Hosted review threads.
4
+ *
5
+ * The rendered artifact is a static file. It carries no endpoint, token, or
6
+ * account id: the viewer asks its own origin whether collaboration exists, and
7
+ * every other call is same-origin and relative. A `file://` page, a loopback dev
8
+ * server, and a BYO bucket therefore behave exactly as they did before — the
9
+ * discovery call either never happens or does not answer, and no chrome appears.
10
+ *
11
+ * Same-origin contract (fixed, so the Worker, the API, and this client agree):
12
+ *
13
+ * GET /__collab/context?share=<encoded path>
14
+ * GET /__collab/threads?share=<path>[&after=<cursor>]
15
+ * POST /__collab/threads { share, anchor, body }
16
+ * POST /__collab/threads/:threadId/replies { share, body }
17
+ * PATCH /__collab/comments/:commentId { share, body } | { share, deleted: true }
18
+ * PATCH /__collab/threads/:threadId { share, status: "open" | "resolved" }
19
+ * GET /__collab/events?share=<path> (text/event-stream)
20
+ */
21
+ /** The `<meta>` name carrying the canonical revision comment anchors are bound to. */
22
+ export const BODY_REVISION_META = 'artifacts-body-revision';
23
+ /**
24
+ * The canonical artifact revision.
25
+ *
26
+ * One revision, agreed by three parties, or anchors drift: it is the SHA-256 of
27
+ * the exact UTF-8 bytes of the `<article class="artifact-body">` inner HTML —
28
+ * the rendered body and nothing else. The hero, the header and footer, the
29
+ * provenance line, the table of contents, the embedded Markdown source, and all
30
+ * reader/collaboration scripts sit outside it, so re-rendering the same content
31
+ * with a new `updated:` date or a new session id does not invalidate a single
32
+ * comment.
33
+ *
34
+ * It is computed once here, at render time, and stamped into the document as
35
+ * `<meta name="artifacts-body-revision">`. The viewer reads that meta rather
36
+ * than re-deriving it from the live DOM (browser serialization is not
37
+ * byte-identical to the renderer's output), and the Worker/API read the same
38
+ * meta out of the stored object. The R2 object revision reported by
39
+ * `/__collab/context` identifies the upload; it is deliberately *not* what
40
+ * anchors are keyed by.
41
+ */
42
+ export function bodyRevision(articleHtml) {
43
+ return `sha256:${createHash('sha256').update(articleHtml, 'utf8').digest('hex')}`;
44
+ }
45
+ /**
46
+ * The share key sent to the collaboration endpoints: this page's own location
47
+ * path, normalized so that `/u/plan`, `/u/plan/`, and `/u/plan/index.html` are
48
+ * one share rather than three.
49
+ *
50
+ * Serialized into the browser bundle via `Function.prototype.toString()`, so it
51
+ * must stay self-contained — no imports, no module-scope references.
52
+ */
53
+ export function normalizeSharePath(pathname) {
54
+ let path = String(pathname || '/');
55
+ if (!path.startsWith('/'))
56
+ path = `/${path}`;
57
+ path = path.replace(/\/{2,}/g, '/');
58
+ path = path.replace(/\/index\.html?$/i, '/');
59
+ if (path.length > 1)
60
+ path = path.replace(/\/+$/, '');
61
+ return path || '/';
62
+ }
63
+ /**
64
+ * The reader-facing name for a share's visibility. `org` is *Company*, never
65
+ * *Public* — conflating the two would tell a viewer their company-internal
66
+ * review thread is on the open web. An unrecognized value returns null and the
67
+ * label is omitted: an unlabeled share is recoverable, a mislabeled one is not.
68
+ *
69
+ * Serialized into the browser bundle via `Function.prototype.toString()`, so it
70
+ * must stay self-contained — no imports, no module-scope references.
71
+ */
72
+ export function visibilityLabel(value) {
73
+ const labels = {
74
+ me: 'Only me',
75
+ org: 'Company',
76
+ unlisted: 'Anyone with link',
77
+ private: 'Anyone with link',
78
+ public: 'Public',
79
+ };
80
+ return typeof value === 'string' && Object.prototype.hasOwnProperty.call(labels, value) ? labels[value] : null;
81
+ }
82
+ const COLLAB_CSS = [
83
+ '.collab-mark{background:color-mix(in srgb,var(--accent-alt,#3b82f6) 26%,var(--bg,#fff));border-bottom:2px solid var(--accent-alt,#3b82f6);color:inherit;border-radius:2px;box-decoration-break:clone;-webkit-box-decoration-break:clone;cursor:pointer}',
84
+ '.collab-mark.is-resolved{background:color-mix(in srgb,var(--muted,#888) 18%,var(--bg,#fff));border-bottom-color:var(--muted,#888)}',
85
+ '.collab-mark.is-selected{background:color-mix(in srgb,var(--accent-alt,#3b82f6) 42%,var(--bg,#fff))}',
86
+ '.collab-mark:focus-visible{outline:2px solid var(--accent,#16a34a);outline-offset:2px}',
87
+ '.collab-rail{position:fixed;top:0;right:0;z-index:35;display:flex;flex-direction:column;width:var(--collab-rail-width);height:100vh;border-left:1px solid var(--line,#ddd);background:var(--surface,#fff);color:var(--text,#111);font:13px/1.5 var(--font-body,sans-serif)}',
88
+ '.collab-rail[hidden],.collab-launcher[hidden]{display:none}',
89
+ '.collab-head{display:flex;flex-wrap:wrap;align-items:center;gap:8px;padding:14px 16px;border-bottom:1px solid var(--line,#ddd)}',
90
+ '.collab-head-title{font:650 12px/1 var(--font-mono,monospace);letter-spacing:.1em;text-transform:uppercase;color:var(--muted,#666)}',
91
+ '.collab-visibility{margin-left:auto;padding:3px 9px;border:1px solid var(--line,#ddd);border-radius:999px;font:500 11px/1.4 var(--font-mono,monospace);color:var(--muted,#666)}',
92
+ '.collab-visibility[hidden]{display:none}',
93
+ '.collab-filters{display:flex;gap:6px;width:100%}',
94
+ '.collab-rail button{border:1px solid var(--line,#ddd);border-radius:999px;background:var(--surface-alt,#f5f5f5);color:inherit;padding:5px 11px;font:500 11.5px/1.3 var(--font-mono,monospace);cursor:pointer}',
95
+ '.collab-rail button:hover{border-color:var(--accent,#16a34a);color:var(--accent,#16a34a)}',
96
+ '.collab-rail button:focus-visible,.collab-launcher:focus-visible{outline:2px solid var(--accent,#16a34a);outline-offset:2px}',
97
+ '.collab-rail button[aria-pressed="true"]{border-color:var(--accent,#16a34a);color:var(--accent,#16a34a);background:color-mix(in srgb,var(--accent,#16a34a) 12%,transparent)}',
98
+ '.collab-close{margin-left:auto}',
99
+ '.collab-list{flex:1;overflow-y:auto;padding:10px 12px 24px;margin:0;list-style:none}',
100
+ '.collab-thread{margin:0 0 10px;padding:12px;border:1px solid var(--line,#ddd);border-radius:10px;background:var(--bg,#fff)}',
101
+ '.collab-thread.is-selected{border-color:var(--accent-alt,#3b82f6);box-shadow:0 0 0 1px var(--accent-alt,#3b82f6)}',
102
+ '.collab-thread:focus-visible{outline:2px solid var(--accent,#16a34a);outline-offset:2px}',
103
+ '.collab-quote{margin:0 0 8px;padding-left:9px;border-left:2px solid var(--accent-alt,#3b82f6);color:var(--muted,#666);font-style:italic;overflow-wrap:anywhere}',
104
+ '.collab-stale{margin:0 0 8px;font:500 11px/1.4 var(--font-mono,monospace);color:var(--warn,#b45309)}',
105
+ '.collab-comments{margin:0;padding:0;list-style:none;display:grid;gap:9px}',
106
+ '.collab-byline{display:flex;flex-wrap:wrap;gap:6px;align-items:baseline;font:500 11px/1.4 var(--font-mono,monospace);color:var(--muted,#666)}',
107
+ '.collab-author{color:var(--text,#111)}',
108
+ '.collab-body{margin:3px 0 0;white-space:pre-wrap;overflow-wrap:anywhere}',
109
+ '.collab-body.is-deleted,.collab-body.is-pending{color:var(--muted,#666);font-style:italic}',
110
+ '.collab-actions{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}',
111
+ '.collab-rail textarea{width:100%;min-height:60px;resize:vertical;border:1px solid var(--line,#ddd);border-radius:8px;padding:8px;background:var(--bg,#fff);color:inherit;font:13px/1.45 var(--font-body,sans-serif)}',
112
+ '.collab-rail textarea:focus-visible{outline:2px solid var(--accent,#16a34a);outline-offset:1px}',
113
+ '.collab-empty{margin:14px 12px;color:var(--muted,#666)}',
114
+ '.collab-error{margin:6px 0 0;color:var(--danger,#b91c1c);font:500 11.5px/1.4 var(--font-mono,monospace)}',
115
+ '.collab-provenance{padding:10px 16px;border-top:1px solid var(--line,#ddd);color:var(--muted,#666);font:11px/1.5 var(--font-mono,monospace);overflow-wrap:anywhere}',
116
+ '.collab-provenance[hidden]{display:none}',
117
+ '.collab-launcher{position:fixed;right:18px;bottom:18px;z-index:34;display:inline-flex;align-items:center;gap:7px;height:38px;padding:0 15px;border:1px solid var(--line,#ddd);border-radius:999px;background:var(--surface,#fff);color:var(--text,#111);font:600 12px/1 var(--font-mono,monospace);box-shadow:0 8px 26px rgba(0,0,0,.16);cursor:pointer}',
118
+ '.collab-count{padding:1px 7px;border-radius:999px;background:color-mix(in srgb,var(--accent-alt,#3b82f6) 18%,transparent);color:var(--accent-alt,#3b82f6)}',
119
+ '.collab-live{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}',
120
+ '@media(min-width:981px){body.collab-rail-open{padding-right:var(--collab-rail-width)}body.collab-rail-open .collab-launcher{display:none}}',
121
+ // The contents rail is fixed and centres itself on the viewport, while the
122
+ // open review rail re-centres the article inside the remaining column. Give
123
+ // the article back the width the review rail took before letting the two
124
+ // fixed rails coexist; below that, the contents rail returns inline rather
125
+ // than landing on top of the prose.
126
+ '@media(min-width:981px) and (max-width:1719px){body.collab-rail-open .toc{position:static;width:auto;max-height:none;margin:24px 0 8px;overflow:visible}}',
127
+ '@media(min-width:1720px){body.collab-rail-open .toc{left:max(20px,calc(50% - var(--content-width)/2 - 236px - var(--collab-rail-width)/2))}}',
128
+ // Narrow viewports get a bottom sheet, never a rail pushed off-screen: the
129
+ // artifact keeps the full column width and the sheet is dismissible.
130
+ '@media(max-width:980px){.collab-rail{top:auto;bottom:0;left:0;width:auto;height:auto;max-height:72vh;border-left:none;border-top:1px solid var(--line,#ddd);border-radius:16px 16px 0 0;box-shadow:0 -10px 34px rgba(0,0,0,.22)}.collab-list{padding-bottom:16px}}',
131
+ '@media(prefers-reduced-motion:reduce){.collab-rail,.collab-launcher,.collab-mark{transition:none!important;animation:none!important}}',
132
+ '@media print{.collab-rail,.collab-launcher{display:none}.collab-mark{background:none;border-bottom:1px solid var(--line,#ddd)}}',
133
+ ].join('');
134
+ export const COLLAB_SCRIPT = `<script>
135
+ (() => {
136
+ const reader = window.__artifactsReader;
137
+ if (!reader) return;
138
+ // file:// and any other non-web scheme keep the standalone reader untouched.
139
+ if (location.protocol !== 'http:' && location.protocol !== 'https:') return;
140
+
141
+ const normalizeSharePath = ${normalizeSharePath};
142
+ const visibilityLabel = ${visibilityLabel};
143
+
144
+ const share = normalizeSharePath(location.pathname);
145
+ const revision = document.querySelector('meta[name=${JSON.stringify(BODY_REVISION_META)}]')?.content || '';
146
+ const endpoint = (path, params) => path + '?' + new URLSearchParams(params).toString();
147
+
148
+ const threads = new Map();
149
+ const seen = new Set();
150
+ let context = null;
151
+ let cursor = '';
152
+ let appliedEvents = 0;
153
+ let filter = 'open';
154
+ let selected = null;
155
+ let draft = null;
156
+ let stream = null;
157
+ // The thread whose marker opened the rail. Stored as an id, not an element:
158
+ // repainting replaces every marker node, so the element would be stale by the
159
+ // time focus has to go back to it.
160
+ let returnTo = null;
161
+
162
+ const canComment = () => Boolean(context && context.permissions && context.permissions.comment === true);
163
+ const canResolve = () => Boolean(context && context.permissions && context.permissions.resolve === true);
164
+ const viewerId = () => (context && context.viewer && context.viewer.id) || null;
165
+ const visible = (thread) => (filter === 'resolved' ? thread.status === 'resolved' : thread.status !== 'resolved');
166
+ const idempotencyKey = () => (crypto.randomUUID ? crypto.randomUUID() : Date.now().toString(36) + Math.random().toString(36).slice(2));
167
+ const when = (value) => { const date = new Date(value); return Number.isNaN(date.getTime()) ? '' : date.toLocaleString(); };
168
+
169
+ // One key per intent, reused across every retry of that intent, so a response
170
+ // lost on the wire cannot become a second thread or a duplicate reply.
171
+ const send = async (method, path, payload, key) => {
172
+ let failure = null;
173
+ for (let attempt = 0; attempt < 2; attempt += 1) {
174
+ try {
175
+ const response = await fetch(path, {
176
+ method,
177
+ headers: { 'content-type': 'application/json', 'idempotency-key': key },
178
+ body: JSON.stringify({ share, ...payload }),
179
+ });
180
+ if (response.status >= 500) { failure = new Error('server error ' + response.status); continue; }
181
+ if (!response.ok) throw new Error('request failed (' + response.status + ')');
182
+ return await response.json();
183
+ } catch (error) { failure = error; }
184
+ }
185
+ throw failure || new Error('request failed');
186
+ };
187
+
188
+ const style = document.createElement('style');
189
+ style.textContent = ':root{--collab-rail-width:340px}' + ${JSON.stringify(COLLAB_CSS)};
190
+ document.head.append(style);
191
+
192
+ const rail = document.createElement('aside');
193
+ rail.className = 'collab-rail';
194
+ rail.hidden = true;
195
+ rail.setAttribute('aria-label', 'Review threads');
196
+ rail.innerHTML = '<div class="collab-head">'
197
+ + '<span class="collab-head-title">Review</span>'
198
+ + '<span class="collab-visibility" hidden></span>'
199
+ + '<button type="button" class="collab-close" aria-label="Close review">Close</button>'
200
+ + '<div class="collab-filters" role="group" aria-label="Filter review threads">'
201
+ + '<button type="button" data-collab-filter="open" aria-pressed="true">Open</button>'
202
+ + '<button type="button" data-collab-filter="resolved" aria-pressed="false">Resolved</button>'
203
+ + '</div></div>'
204
+ + '<div class="collab-list" role="list"></div>'
205
+ + '<p class="collab-provenance" hidden></p>';
206
+ const launcher = document.createElement('button');
207
+ launcher.type = 'button';
208
+ launcher.className = 'collab-launcher';
209
+ launcher.hidden = true;
210
+ launcher.setAttribute('aria-expanded', 'false');
211
+ launcher.innerHTML = 'Review <span class="collab-count">0</span>';
212
+ const live = document.createElement('div');
213
+ live.className = 'collab-live';
214
+ live.setAttribute('role', 'status');
215
+ live.setAttribute('aria-live', 'polite');
216
+ const list = rail.querySelector('.collab-list');
217
+ const announce = (message) => { live.textContent = message; };
218
+
219
+ const openRail = (focus) => {
220
+ rail.hidden = false;
221
+ document.body.classList.add('collab-rail-open');
222
+ launcher.setAttribute('aria-expanded', 'true');
223
+ if (focus) { const first = list.querySelector('.collab-thread'); (first || rail.querySelector('.collab-close')).focus(); }
224
+ };
225
+ const closeRail = () => {
226
+ rail.hidden = true;
227
+ document.body.classList.remove('collab-rail-open');
228
+ launcher.setAttribute('aria-expanded', 'false');
229
+ selected = null;
230
+ const target = returnTo;
231
+ returnTo = null;
232
+ paintAll();
233
+ const mark = target && reader.root.querySelector('mark[data-collab-thread="' + CSS.escape(target) + '"]');
234
+ // A reader can collapse the quoted section while Review is open. Focusing
235
+ // its hidden mark would leave focus in the now-hidden rail.
236
+ (mark && mark.getClientRects().length ? mark : launcher).focus();
237
+ };
238
+
239
+ const paintAll = () => {
240
+ reader.clearMarks('mark[data-collab-thread]');
241
+ for (const thread of threads.values()) {
242
+ if (thread.draft) continue;
243
+ const found = reader.quoteAt(thread.anchor);
244
+ // Repaint only on an unambiguous anchor resolution AND an exact quote
245
+ // match. Anything else leaves the prose alone; the thread stays legible in
246
+ // the rail instead of decorating the wrong sentence.
247
+ thread.stale = found === null || reader.normalizeQuote(found) !== reader.normalizeQuote(thread.anchor.quote);
248
+ if (thread.stale || !visible(thread)) continue;
249
+ reader.paint(thread.anchor, () => {
250
+ const mark = document.createElement('mark');
251
+ mark.className = 'collab-mark' + (thread.status === 'resolved' ? ' is-resolved' : '') + (thread.id === selected ? ' is-selected' : '');
252
+ mark.dataset.collabThread = thread.id;
253
+ mark.tabIndex = 0;
254
+ mark.setAttribute('role', 'button');
255
+ const first = thread.comments.find((comment) => !comment.deleted);
256
+ mark.setAttribute('aria-label', 'Review thread, ' + thread.comments.length + ' comment' + (thread.comments.length === 1 ? '' : 's') + (first ? ': ' + first.body.slice(0, 80) : ''));
257
+ mark.addEventListener('click', (event) => { event.preventDefault(); event.stopPropagation(); select(thread.id, thread.id); });
258
+ mark.addEventListener('keydown', (event) => {
259
+ if (event.key !== 'Enter' && event.key !== ' ' && event.key !== 'Spacebar') return;
260
+ event.preventDefault(); event.stopPropagation(); select(thread.id, thread.id);
261
+ });
262
+ return mark;
263
+ });
264
+ }
265
+ };
266
+
267
+ const select = (id, focusBack) => {
268
+ selected = id;
269
+ if (focusBack) returnTo = focusBack;
270
+ const thread = threads.get(id);
271
+ if (thread && thread.status === 'resolved' && filter !== 'resolved') setFilter('resolved');
272
+ openRail(false);
273
+ renderRail();
274
+ paintAll();
275
+ const item = list.querySelector('[data-thread-id="' + CSS.escape(id) + '"]');
276
+ if (item) { item.scrollIntoView({ block: 'nearest' }); item.focus(); }
277
+ };
278
+
279
+ const setFilter = (next) => {
280
+ filter = next;
281
+ for (const button of rail.querySelectorAll('[data-collab-filter]')) {
282
+ button.setAttribute('aria-pressed', button.dataset.collabFilter === next ? 'true' : 'false');
283
+ }
284
+ };
285
+
286
+ const button = (action, label, extra) => {
287
+ const element = document.createElement('button');
288
+ element.type = 'button';
289
+ element.dataset.collabAction = action;
290
+ element.textContent = label;
291
+ if (extra) element.dataset.collabTarget = extra;
292
+ return element;
293
+ };
294
+
295
+ const commentItem = (thread, comment) => {
296
+ const item = document.createElement('li');
297
+ item.className = 'collab-comment';
298
+ item.dataset.commentId = comment.id;
299
+ const byline = document.createElement('div');
300
+ byline.className = 'collab-byline';
301
+ const author = document.createElement('span');
302
+ author.className = 'collab-author';
303
+ author.textContent = (comment.author && comment.author.name) || 'Unknown';
304
+ byline.append(author);
305
+ if (comment.created_at) { const time = document.createElement('time'); time.dateTime = comment.created_at; time.textContent = when(comment.created_at); byline.append(time); }
306
+ if (comment.edited) { const edited = document.createElement('span'); edited.textContent = 'edited'; byline.append(edited); }
307
+ if (comment.pending) { const pendingTag = document.createElement('span'); pendingTag.textContent = 'sending…'; byline.append(pendingTag); }
308
+ const body = document.createElement('p');
309
+ body.className = 'collab-body' + (comment.deleted ? ' is-deleted' : '') + (comment.pending ? ' is-pending' : '');
310
+ body.textContent = comment.deleted ? 'Comment deleted' : comment.body;
311
+ item.append(byline, body);
312
+ const mine = !comment.deleted && !comment.pending && comment.author && comment.author.id && comment.author.id === viewerId();
313
+ if (mine && canComment()) {
314
+ const actions = document.createElement('div');
315
+ actions.className = 'collab-actions';
316
+ actions.append(button('edit', 'Edit', comment.id), button('delete', 'Delete', comment.id));
317
+ item.append(actions);
318
+ }
319
+ return item;
320
+ };
321
+
322
+ const threadItem = (thread) => {
323
+ const item = document.createElement('article');
324
+ item.className = 'collab-thread' + (thread.id === selected ? ' is-selected' : '');
325
+ item.dataset.threadId = thread.id;
326
+ item.setAttribute('role', 'listitem');
327
+ item.tabIndex = 0;
328
+
329
+ const quote = document.createElement('p');
330
+ quote.className = 'collab-quote';
331
+ quote.textContent = '“' + thread.anchor.quote + '”';
332
+ item.append(quote);
333
+
334
+ if (thread.stale) {
335
+ const stale = document.createElement('p');
336
+ stale.className = 'collab-stale';
337
+ // The exact wording is part of the cross-repo contract: a thread whose
338
+ // text moved is reported honestly rather than silently re-anchored.
339
+ stale.textContent = thread.anchor.revision && thread.anchor.revision !== revision
340
+ ? 'From an earlier revision'
341
+ : 'Anchored text not found';
342
+ item.append(stale);
343
+ }
344
+
345
+ const comments = document.createElement('ul');
346
+ comments.className = 'collab-comments';
347
+ for (const comment of thread.comments) comments.append(commentItem(thread, comment));
348
+ item.append(comments);
349
+
350
+ const actions = document.createElement('div');
351
+ actions.className = 'collab-actions';
352
+ if (canComment() && !thread.draft) actions.append(button('reply', 'Reply'));
353
+ if (canResolve() && !thread.draft) actions.append(button(thread.status === 'resolved' ? 'reopen' : 'resolve', thread.status === 'resolved' ? 'Reopen' : 'Resolve'));
354
+ if (actions.children.length) item.append(actions);
355
+
356
+ if (thread.composer || thread.draft) {
357
+ const form = document.createElement('form');
358
+ form.className = 'collab-composer';
359
+ const textarea = document.createElement('textarea');
360
+ textarea.setAttribute('aria-label', thread.draft ? 'Comment' : 'Reply');
361
+ textarea.placeholder = thread.draft ? 'Comment on this selection…' : 'Reply…';
362
+ textarea.value = thread.composerValue || '';
363
+ const row = document.createElement('div');
364
+ row.className = 'collab-actions';
365
+ const submit = document.createElement('button');
366
+ submit.type = 'submit';
367
+ submit.textContent = thread.draft ? 'Post comment' : 'Send reply';
368
+ row.append(submit, button('cancel', 'Cancel'));
369
+ form.append(textarea, row);
370
+ if (thread.error) { const error = document.createElement('p'); error.className = 'collab-error'; error.textContent = thread.error; form.append(error); }
371
+ form.addEventListener('submit', (event) => {
372
+ event.preventDefault();
373
+ const value = textarea.value.trim();
374
+ if (!value) return;
375
+ if (thread.draft) createThread(value); else replyTo(thread, value);
376
+ });
377
+ item.append(form);
378
+ } else if (thread.error) {
379
+ const error = document.createElement('p');
380
+ error.className = 'collab-error';
381
+ error.textContent = thread.error;
382
+ item.append(error);
383
+ }
384
+
385
+ item.addEventListener('keydown', (event) => {
386
+ if (event.key === 'Enter' && event.target === item) { event.preventDefault(); select(thread.id, returnTo); }
387
+ });
388
+ return item;
389
+ };
390
+
391
+ const renderRail = () => {
392
+ const shown = [...threads.values()].filter((thread) => thread.draft || visible(thread));
393
+ list.replaceChildren();
394
+ if (!shown.length) {
395
+ const empty = document.createElement('p');
396
+ empty.className = 'collab-empty';
397
+ empty.textContent = filter === 'resolved' ? 'No resolved threads.' : 'No open threads yet. Select text to comment.';
398
+ list.append(empty);
399
+ }
400
+ for (const thread of shown) list.append(threadItem(thread));
401
+ const open = [...threads.values()].filter((thread) => !thread.draft && thread.status !== 'resolved').length;
402
+ launcher.querySelector('.collab-count').textContent = String(open);
403
+ launcher.setAttribute('aria-label', open === 1 ? '1 open review thread' : open + ' open review threads');
404
+ };
405
+
406
+ // The single door every server snapshot comes through, from the stream, from
407
+ // catch-up, and from a write's own response. Snapshots are whole threads and
408
+ // each carries the cursor it was written at, so the rule is simply that a
409
+ // thread never moves backwards: a slow write response that lands after a
410
+ // teammate's newer change must not revert it. Without this an awaited reply
411
+ // whose response is overtaken by someone else's resolve would silently reopen
412
+ // that thread on the replying reader's screen and stay wrong.
413
+ const upsert = (thread) => {
414
+ if (!thread || !thread.id) return false;
415
+ const existing = threads.get(thread.id);
416
+ if (existing && Number(thread.cursor || 0) < Number(existing.cursor || 0)) return false;
417
+ threads.set(thread.id, { ...existing, ...thread, draft: false, composer: false, error: null });
418
+ return true;
419
+ };
420
+
421
+ // Every durable change reaches the client as a cursored envelope, whether it
422
+ // arrived on the stream or through catch-up. Applying is keyed by that cursor,
423
+ // so a reconnect that replays and a catch-up that refetches land exactly once.
424
+ const applyEnvelope = (rawId, payload) => {
425
+ // SSE hands back a string cursor and JSON hands back a number; both name the
426
+ // same durable change, so the dedupe key is normalized or catch-up applies
427
+ // an event the stream already delivered.
428
+ const id = rawId === null || rawId === undefined ? '' : String(rawId);
429
+ if (!id || seen.has(id)) return false;
430
+ seen.add(id);
431
+ // Envelopes carry whole-thread snapshots, so one at or before the newest
432
+ // change already materialized holds nothing new. A server that replays its
433
+ // whole stream to a fresh subscriber would otherwise walk a resolved thread
434
+ // back to open, because the newest event is the one already deduped.
435
+ if (Number(id) <= Number(cursor || 0)) return false;
436
+ appliedEvents += 1;
437
+ cursor = String(id);
438
+ if (payload && payload.thread) {
439
+ // The stream can outrun the POST response for the author's own write. The
440
+ // server echoes the idempotency key, so the optimistic row is retired by
441
+ // the event instead of briefly double-painting its own selection.
442
+ if (payload.thread.idempotency_key) threads.delete('pending:' + payload.thread.idempotency_key);
443
+ const previous = threads.get(payload.thread.id);
444
+ upsert(payload.thread);
445
+ const last = payload.thread.comments[payload.thread.comments.length - 1];
446
+ const mine = last && last.author && last.author.id === viewerId();
447
+ if (!mine) {
448
+ if (!previous) announce('New review thread from ' + ((last && last.author && last.author.name) || 'a teammate'));
449
+ else if (previous.status !== payload.thread.status) announce('Thread ' + payload.thread.status);
450
+ else announce('New comment from ' + ((last && last.author && last.author.name) || 'a teammate'));
451
+ }
452
+ }
453
+ return true;
454
+ };
455
+
456
+ const loadThreads = async (after) => {
457
+ const params = after ? { share, after } : { share };
458
+ const response = await fetch(endpoint('/__collab/threads', params), { headers: { accept: 'application/json' } });
459
+ if (!response.ok) throw new Error('threads request failed (' + response.status + ')');
460
+ const payload = await response.json();
461
+ for (const thread of payload.threads || []) {
462
+ if (after) applyEnvelope(thread.cursor, { thread });
463
+ else { upsert(thread); if (thread.cursor) { seen.add(String(thread.cursor)); if (Number(thread.cursor) > Number(cursor || 0)) cursor = String(thread.cursor); } }
464
+ }
465
+ if (!after && payload.cursor && Number(payload.cursor) > Number(cursor || 0)) cursor = String(payload.cursor);
466
+ renderRail();
467
+ paintAll();
468
+ };
469
+
470
+ const connect = () => {
471
+ stream = new EventSource(endpoint('/__collab/events', { share }));
472
+ // The browser resends Last-Event-ID on its own reconnect; the explicit
473
+ // catch-up covers everything the server could not replay from memory. Both
474
+ // paths funnel through applyEnvelope, so the overlap is deduped, not doubled.
475
+ stream.addEventListener('open', () => { loadThreads(cursor || '0').catch(() => {}); });
476
+ stream.addEventListener('thread', (event) => {
477
+ let payload = null;
478
+ try { payload = JSON.parse(event.data); } catch { return; }
479
+ if (applyEnvelope(event.lastEventId, payload)) { renderRail(); paintAll(); }
480
+ });
481
+ };
482
+
483
+ const createThread = async (body) => {
484
+ const anchor = { ...draft.anchor, revision };
485
+ const key = idempotencyKey();
486
+ const optimisticId = 'pending:' + key;
487
+ threads.delete('draft');
488
+ draft = null;
489
+ threads.set(optimisticId, {
490
+ id: optimisticId, status: 'open', anchor, stale: false, pending: true,
491
+ comments: [{ id: optimisticId + ':1', body, author: context.viewer, created_at: new Date().toISOString(), pending: true }],
492
+ });
493
+ selected = optimisticId;
494
+ renderRail(); paintAll();
495
+ try {
496
+ const result = await send('POST', '/__collab/threads', { anchor, body }, key);
497
+ threads.delete(optimisticId);
498
+ settleWrite(result);
499
+ selected = result.thread.id;
500
+ renderRail(); paintAll();
501
+ } catch (error) {
502
+ // Roll the optimistic thread back and hand the text to the reader again,
503
+ // rather than leaving a comment on screen that the server never stored.
504
+ threads.delete(optimisticId);
505
+ draft = { id: 'draft', draft: true, status: 'open', anchor, comments: [], composerValue: body, error: 'Not sent: ' + error.message };
506
+ threads.set('draft', draft);
507
+ selected = 'draft';
508
+ renderRail(); paintAll();
509
+ announce('Comment could not be sent. ' + error.message);
510
+ }
511
+ };
512
+
513
+ // Re-reads the thread out of the map rather than trusting the object captured
514
+ // when the button was clicked. A concurrent write replaces the map entry with
515
+ // a fresh object, so an in-place edit of the captured one — in particular the
516
+ // rollback and its error message — would be written to a detached object and
517
+ // never reach the screen, losing the failure silently.
518
+ const revise = (id, change) => {
519
+ const current = threads.get(id);
520
+ if (!current) return null;
521
+ const next = { ...current, ...change(current) };
522
+ threads.set(id, next);
523
+ return next;
524
+ };
525
+
526
+ const settleWrite = (result) => {
527
+ upsert(result.thread);
528
+ if (result.cursor) { seen.add(String(result.cursor)); if (Number(result.cursor) > Number(cursor || 0)) cursor = String(result.cursor); }
529
+ };
530
+
531
+ // A rollback only undoes this write. If a newer server snapshot landed while
532
+ // the request was in flight it already carries the truth, so the optimistic
533
+ // change is gone anyway and only the error is worth adding.
534
+ const overtaken = (before, current) => Number(current.cursor || 0) > Number(before);
535
+
536
+ const replyTo = async (thread, body) => {
537
+ const id = thread.id;
538
+ const key = idempotencyKey();
539
+ const optimisticId = 'pending:' + key;
540
+ revise(id, (current) => ({
541
+ comments: [...current.comments, { id: optimisticId, body, author: context.viewer, created_at: new Date().toISOString(), pending: true }],
542
+ composer: false, composerValue: '', error: null,
543
+ }));
544
+ renderRail();
545
+ try {
546
+ settleWrite(await send('POST', '/__collab/threads/' + encodeURIComponent(id) + '/replies', { body }, key));
547
+ } catch (error) {
548
+ revise(id, (current) => ({
549
+ comments: current.comments.filter((comment) => comment.id !== optimisticId),
550
+ composer: true, composerValue: body, error: 'Not sent: ' + error.message,
551
+ }));
552
+ announce('Reply could not be sent. ' + error.message);
553
+ }
554
+ renderRail(); paintAll();
555
+ };
556
+
557
+ const patchComment = async (thread, commentId, payload, failureMessage) => {
558
+ const id = thread.id;
559
+ const key = idempotencyKey();
560
+ const before = thread.comments.find((comment) => comment.id === commentId);
561
+ const restore = before ? { body: before.body, edited: before.edited, deleted: before.deleted } : null;
562
+ const baseCursor = Number(thread.cursor || 0);
563
+ revise(id, (current) => ({
564
+ comments: current.comments.map((comment) => (comment.id === commentId
565
+ ? { ...comment, ...(payload.deleted ? { deleted: true } : { body: payload.body, edited: true }) }
566
+ : comment)),
567
+ error: null,
568
+ }));
569
+ renderRail();
570
+ try {
571
+ settleWrite(await send('PATCH', '/__collab/comments/' + encodeURIComponent(commentId), payload, key));
572
+ } catch (error) {
573
+ revise(id, (current) => ({
574
+ comments: restore && !overtaken(baseCursor, current)
575
+ ? current.comments.map((comment) => (comment.id === commentId ? { ...comment, ...restore } : comment))
576
+ : current.comments,
577
+ error: failureMessage + ' ' + error.message,
578
+ }));
579
+ announce(failureMessage + ' ' + error.message);
580
+ }
581
+ renderRail(); paintAll();
582
+ };
583
+
584
+ const setStatus = async (thread, status) => {
585
+ const id = thread.id;
586
+ const previous = thread.status;
587
+ const baseCursor = Number(thread.cursor || 0);
588
+ const key = idempotencyKey();
589
+ revise(id, () => ({ status, error: null }));
590
+ renderRail(); paintAll();
591
+ try {
592
+ settleWrite(await send('PATCH', '/__collab/threads/' + encodeURIComponent(id), { status }, key));
593
+ } catch (error) {
594
+ revise(id, (current) => ({
595
+ status: overtaken(baseCursor, current) ? current.status : previous,
596
+ error: 'Status not saved: ' + error.message,
597
+ }));
598
+ announce('Status not saved. ' + error.message);
599
+ }
600
+ renderRail(); paintAll();
601
+ };
602
+
603
+ list.addEventListener('click', (event) => {
604
+ const target = event.target.closest('[data-collab-action]');
605
+ if (!target) return;
606
+ const item = target.closest('[data-thread-id]');
607
+ const thread = item && threads.get(item.dataset.threadId);
608
+ if (!thread) return;
609
+ const action = target.dataset.collabAction;
610
+ if (action === 'reply') { thread.composer = true; thread.composerValue = ''; renderRail(); item.querySelector('textarea')?.focus(); return; }
611
+ if (action === 'cancel') {
612
+ if (thread.draft) { threads.delete('draft'); draft = null; selected = null; }
613
+ else { thread.composer = false; thread.composerValue = ''; thread.error = null; }
614
+ renderRail(); paintAll(); return;
615
+ }
616
+ if (action === 'resolve') { setStatus(thread, 'resolved'); return; }
617
+ if (action === 'reopen') { setStatus(thread, 'open'); return; }
618
+ if (action === 'delete') { patchComment(thread, target.dataset.collabTarget, { deleted: true }, 'Delete failed.'); return; }
619
+ if (action === 'edit') {
620
+ const commentId = target.dataset.collabTarget;
621
+ const comment = thread.comments.find((value) => value.id === commentId);
622
+ if (!comment) return;
623
+ const holder = item.querySelector('[data-comment-id="' + CSS.escape(commentId) + '"]');
624
+ const form = document.createElement('form');
625
+ const textarea = document.createElement('textarea');
626
+ textarea.setAttribute('aria-label', 'Edit comment');
627
+ textarea.value = comment.body;
628
+ const row = document.createElement('div');
629
+ row.className = 'collab-actions';
630
+ const save = document.createElement('button');
631
+ save.type = 'submit';
632
+ save.textContent = 'Save';
633
+ row.append(save, button('cancel-edit', 'Cancel'));
634
+ form.append(textarea, row);
635
+ form.addEventListener('submit', (submitEvent) => {
636
+ submitEvent.preventDefault();
637
+ const value = textarea.value.trim();
638
+ if (value) patchComment(thread, commentId, { body: value }, 'Edit failed.');
639
+ });
640
+ form.addEventListener('click', (clickEvent) => {
641
+ if (clickEvent.target.closest('[data-collab-action="cancel-edit"]')) { clickEvent.preventDefault(); clickEvent.stopPropagation(); renderRail(); }
642
+ });
643
+ holder.replaceChildren(form);
644
+ textarea.focus();
645
+ }
646
+ });
647
+
648
+ list.addEventListener('focusin', (event) => {
649
+ const item = event.target.closest('[data-thread-id]');
650
+ if (!item || item.dataset.threadId === selected) return;
651
+ selected = item.dataset.threadId;
652
+ paintAll();
653
+ });
654
+
655
+ rail.addEventListener('click', (event) => { if (event.target.closest('.collab-close')) closeRail(); });
656
+ rail.addEventListener('keydown', (event) => { if (event.key === 'Escape') { event.preventDefault(); closeRail(); } });
657
+ for (const filterButton of rail.querySelectorAll('[data-collab-filter]')) {
658
+ filterButton.addEventListener('click', () => { setFilter(filterButton.dataset.collabFilter); selected = null; renderRail(); paintAll(); });
659
+ }
660
+ launcher.addEventListener('click', () => { returnTo = null; openRail(true); });
661
+
662
+ const mount = async () => {
663
+ document.body.append(rail, launcher, live);
664
+ launcher.hidden = false;
665
+ const label = visibilityLabel(context.visibility);
666
+ const chip = rail.querySelector('.collab-visibility');
667
+ if (label) { chip.textContent = label; chip.hidden = false; }
668
+ if (context.producer && (context.producer.agent || context.producer.session)) {
669
+ const provenance = rail.querySelector('.collab-provenance');
670
+ provenance.textContent = 'Produced by ' + [context.producer.agent, context.producer.session].filter(Boolean).join(' · ');
671
+ provenance.hidden = false;
672
+ }
673
+ if (canComment()) {
674
+ window.__artifactsHighlights?.addAction('comment', 'Comment', (pending) => {
675
+ if (!pending) return;
676
+ window.__artifactsHighlights.dismiss();
677
+ threads.delete('draft');
678
+ draft = { id: 'draft', draft: true, status: 'open', comments: [], composerValue: '', anchor: { revision, quote: pending.quote, section: pending.section, start: pending.start, end: pending.end } };
679
+ threads.set('draft', draft);
680
+ selected = 'draft';
681
+ returnTo = null;
682
+ openRail(false);
683
+ renderRail();
684
+ list.querySelector('[data-thread-id="draft"] textarea')?.focus();
685
+ });
686
+ }
687
+ await loadThreads();
688
+ connect();
689
+ window.__artifactsCollab = {
690
+ share, revision,
691
+ appliedEvents: () => appliedEvents,
692
+ appliedCursors: () => [...seen],
693
+ cursor: () => cursor,
694
+ threads: () => [...threads.values()],
695
+ producer: () => (context && context.producer) || null,
696
+ };
697
+ };
698
+
699
+ (async () => {
700
+ let discovered = null;
701
+ try {
702
+ const response = await fetch(endpoint('/__collab/context', { share }), { headers: { accept: 'application/json' } });
703
+ if (!response.ok) return;
704
+ discovered = await response.json();
705
+ } catch { return; }
706
+ // Fail closed on anything short of an explicit read grant: no rail, no
707
+ // launcher, no markers — the page stays exactly the standalone artifact.
708
+ if (!discovered || !discovered.permissions || discovered.permissions.read !== true) return;
709
+ context = discovered;
710
+ mount().catch(() => {});
711
+ })();
712
+ })();
713
+ </script>`;
714
+ //# sourceMappingURL=collab.js.map