@stefan.inc/feedback-engine 1.7.2 → 1.9.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
@@ -198,7 +198,7 @@ export function Feedback() {
198
198
  - Client components are in the capture under their own names, as in a Vite app. A server component leaves no component in the page, so it is not a node. The elements it draws are, each with its own `file:line`.
199
199
  - On a deployed preview, such as a Vercel preview link, pass `withFeedbackEngine(config, { elementSources: true })` so a production build keeps every element's `file:line`. Components keep theirs in every build without it. The attribute puts your file paths in the page's HTML, so leave it off a public production deploy, for example with `elementSources: process.env.VERCEL_ENV === 'preview'`.
200
200
  - To keep Feedback off a production deploy, render `<Feedback />` only where you want it, for example behind `process.env.NEXT_PUBLIC_VERCEL_ENV !== 'production'`.
201
- - `feedbackProcrastimate()` is a Vite plugin, so a Next.js app has no ProcrastiMate entry unless you pass `procrastimate: { url }` for a proxy of your own.
201
+ - `feedbackProcrastimate()` is a Vite plugin, so a Next.js app has no ProcrastiMate entry unless you pass `procrastimate: { url, projects }` for a proxy of your own.
202
202
 
203
203
  ## Component data and untagged content
204
204
 
@@ -227,23 +227,45 @@ The editor works as on iOS, with these differences:
227
227
 
228
228
  ## Post to ProcrastiMate
229
229
 
230
- Optional, and off until the dev server has a token. [ProcrastiMate](https://github.com/smirea/procrastimate) is the task app that Feedback's author files feedback into. A page cannot call ProcrastiMate from another origin, and a token in the page would be public, so the dev server forwards the calls and adds the token:
230
+ Optional, and off until you configure it. [ProcrastiMate](https://github.com/smirea/procrastimate) is the task app that Feedback's author files feedback into.
231
+
232
+ ### With the signed-in ProcrastiMate account (recommended)
233
+
234
+ Pass the whitelisted `projects` to `setupFeedbackEngine()` with no `url` and no token:
235
+
236
+ ```ts
237
+ setupFeedbackEngine({
238
+ app: 'My App',
239
+ procrastimate: { projects: ['Website'] },
240
+ });
241
+ ```
242
+
243
+ Choosing **ProcrastiMate** opens a popup on `https://procrastimate.stf.lol/feedback` (or `procrastimate.app`) and hands over the annotated screenshot and `feedback.json` via `postMessage`. Because the popup runs on ProcrastiMate's own origin, it uses whoever is signed into ProcrastiMate in that browser (or lets them sign in there) with no hardcoded token, no backend proxy, and no CORS setup, so it works on deployed static sites, Vite, and Next.js alike. Anyone with an `edit` share on a listed project posts under their own account. Pass `space` (the project owner's user id) only if two spaces share the same project name.
244
+
245
+ ### With a dev-server proxy and token
246
+
247
+ For local development with a fixed personal token instead of the browser's ProcrastiMate login, `feedbackProcrastimate()` forwards calls from the Vite dev and preview servers and adds the token there:
231
248
 
232
249
  ```ts
233
250
  // vite.config.ts
234
251
  import { feedbackProcrastimate } from '@stefan.inc/feedback-engine/vite';
235
252
 
236
253
  export default defineConfig({
237
- plugins: [feedbackProcrastimate({ token: process.env.PROCRASTIMATE_TOKEN }) /* and the plugins above */],
254
+ plugins: [
255
+ feedbackProcrastimate({ token: process.env.PROCRASTIMATE_TOKEN, projects: ['Website'] }),
256
+ /* and the plugins above */
257
+ ],
238
258
  });
239
259
  ```
240
260
 
241
- The token is the switch. With `PROCRASTIMATE_TOKEN` set, **ProcrastiMate** shows in the Share menu, with the same picker and task as on iOS. Without it, the entry is not there, and nothing else changes. `setupFeedbackEngine()` needs no option for either case.
261
+ With the proxy plugin, the token is the switch: when `PROCRASTIMATE_TOKEN` is set, **ProcrastiMate** shows in the Share menu without any `setupFeedbackEngine()` option.
242
262
 
243
263
  - The token is a ProcrastiMate personal token, from Settings › Personal token. An AI account's token lists the projects but cannot upload the image, so the post fails with `Not for AI accounts`. `feedbackProcrastimate({ url })` names another ProcrastiMate server.
244
- - `feedbackProcrastimate({ project })` names the project the picker opens on, by name (ignoring case) or id, so an app's feedback lands in its own project. Without it, the picker opens on the last project posted to. A name ProcrastiMate does not have shows as an error above the list.
245
- - The proxy runs in `vite dev` and `vite preview`. A build reads the token too. Build a site you deploy without it, because a static host has no proxy.
246
- - For a proxy of your own, pass its address to the page instead: `setupFeedbackEngine({ procrastimate: { url: '/my-proxy' } })`.
264
+ - `projects` is required in every mode: the only projects Feedback posts to, by name (ignoring case) or id, in the picker's order. There is no way to allow every project, and the Inbox is never offered. The picker opens on the last of them posted to, or the first. A listed name ProcrastiMate does not have shows as an error above the list.
265
+ - Both the Vite proxy and ProcrastiMate's `/feedback` popup enforce the list. The proxy shows the page only the listed projects, creates a task only in one of them, and forwards nothing but the calls a post makes; anything else answers 403.
266
+ - Each project in the picker has a ↗ link to its page in ProcrastiMate, which opens in a new tab for someone signed in to its space.
267
+ - `project` names the project the picker opens on, by name (ignoring case) or id, so an app's feedback lands in its own project. It has to be one of `projects`. Without it, the picker opens on the last project posted to.
268
+ - For a proxy or same-origin API of your own, pass its address and the projects to the page instead: `setupFeedbackEngine({ procrastimate: { url: '/my-proxy', projects: ['Website'] } })`. Your proxy should refuse tasks anywhere else, as this one does.
247
269
 
248
270
  ## How capture works
249
271
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stefan.inc/feedback-engine",
3
- "version": "1.7.2",
3
+ "version": "1.9.0",
4
4
  "description": "In-app feedback for Svelte and React: point at a component, write what should change, and export its name, file:line, and data for an agent.",
5
5
  "keywords": [
6
6
  "accessibility",
@@ -1,24 +1,39 @@
1
1
  import { Problem } from '../core/problem.ts';
2
+ import { postId } from './webhook.ts';
2
3
 
3
4
  export type ProcrastimateConfig = {
4
- /** Where ProcrastiMate's API answers: the Vite plugin's proxy path, or a server that allows this origin. */
5
- url: string;
6
- /** Sent as a bearer token. Leave it out behind the proxy, which adds its own. */
5
+ /**
6
+ * Where ProcrastiMate's API answers: the Vite plugin's proxy path, or a server that allows this origin. Leave it out
7
+ * to open a popup on the ProcrastiMate web app (`app`) that posts using whoever is signed in there, with no token
8
+ * and no proxy.
9
+ */
10
+ url?: string;
11
+ /** Sent as a bearer token. Leave it out behind the proxy or when posting through the popup. */
7
12
  token?: string;
8
- /** The ProcrastiMate web app, for the link to a posted task. */
13
+ /** The ProcrastiMate web app, for the popup and for links to posted tasks and projects. */
9
14
  app?: string;
10
15
  /** The project the picker opens on, by name (ignoring case) or id, in place of the last one posted to. */
11
16
  project?: string;
17
+ /**
18
+ * The only projects the picker offers, by name (ignoring case) or id, in this order. The Inbox is not offered.
19
+ * Required, and not empty. A proxy of your own should refuse tasks anywhere else.
20
+ */
21
+ projects: string[];
22
+ /**
23
+ * Another user's space (their ProcrastiMate user id) whose shared projects the picker lists. Leave it out to match
24
+ * across the signed-in user's own and edit-shared projects in the popup, or the token's space behind a proxy.
25
+ */
26
+ space?: string;
12
27
  };
13
28
 
14
29
  export type Section = { id: string; name: string };
15
30
  export type Project = { id: string; name: string; sections: Section[] };
16
- /** Where a task goes: the Inbox without a project, and the project's top, above its sections, without a section. */
31
+ /** Where a task goes: the project's top, above its sections, without a section. No project yet while none is listed. */
17
32
  export type Place = { projectId?: string; sectionId?: string };
18
33
 
19
34
  /** ProcrastiMate's `FILE_PART_BYTES` (`shared/images.ts` there): the most it takes as a file in one request. */
20
- const fileMaxBytes = 16 * 1024 * 1024;
21
- const defaultApp = 'https://procrastimate.stf.lol';
35
+ export const fileMaxBytes = 16 * 1024 * 1024;
36
+ export const defaultProcrastimateApp = 'https://procrastimate.stf.lol';
22
37
 
23
38
  const projectsKey = 'feedback.procrastimate.projects';
24
39
  const lastProjectKey = 'feedback.procrastimate.project';
@@ -51,8 +66,37 @@ export const namedProject = (projects: Project[], name: string) =>
51
66
  projects.find(project => project.id === name) ??
52
67
  projects.find(project => project.name.toLowerCase() === name.toLowerCase());
53
68
 
69
+ /** The projects the picker lists: those `names` lists, in its order. `missing` has the names ProcrastiMate lacks. */
70
+ export function listedProjects(all: Project[], names: string[]) {
71
+ const projects: Project[] = [];
72
+ const missing: string[] = [];
73
+ for (const name of names) {
74
+ const project = namedProject(all, name);
75
+ if (!project) missing.push(name);
76
+ else if (!projects.includes(project)) projects.push(project);
77
+ }
78
+ return { projects, missing };
79
+ }
80
+
81
+ /**
82
+ * The project the picker opens on, among the listed ones: the one the app names, else the last one posted to, else
83
+ * the first. `undefined` only while none is listed.
84
+ */
85
+ export function startingProject(listed: Project[], config: ProcrastimateConfig, last: string | undefined) {
86
+ if (config.project) return namedProject(listed, config.project)?.id;
87
+ if (listed.some(project => project.id === last)) return last;
88
+ return listed[0]?.id;
89
+ }
90
+
91
+ export const procrastimateAppURL = (config: ProcrastimateConfig) =>
92
+ (config.app ?? defaultProcrastimateApp).replace(/\/$/, '');
93
+
94
+ /** The project's page in the ProcrastiMate web app, which opens for someone signed in to its space. */
95
+ export const projectLink = (config: ProcrastimateConfig, id: string) =>
96
+ `${procrastimateAppURL(config)}/projects/${encodeURIComponent(id)}`;
97
+
54
98
  export const taskLink = (config: ProcrastimateConfig, id: string) =>
55
- `${(config.app ?? defaultApp).replace(/\/$/, '')}/inbox?task=${encodeURIComponent(id)}`;
99
+ `${procrastimateAppURL(config)}/inbox?task=${encodeURIComponent(id)}`;
56
100
 
57
101
  async function send(
58
102
  config: ProcrastimateConfig,
@@ -62,7 +106,11 @@ async function send(
62
106
  body?: BodyInit,
63
107
  type?: string,
64
108
  ) {
65
- const search = new URLSearchParams(Object.entries(query).toSorted(([a], [b]) => a.localeCompare(b)));
109
+ if (config.url === undefined) {
110
+ throw new Error('ProcrastiMate has no API URL; popup mode posts from the ProcrastiMate web app.');
111
+ }
112
+ const fullQuery = config.space ? { space: config.space, ...query } : query;
113
+ const search = new URLSearchParams(Object.entries(fullQuery).toSorted(([a], [b]) => a.localeCompare(b)));
66
114
  const url = `${config.url.replace(/\/$/, '')}/${path}${search.size ? `?${search}` : ''}`;
67
115
  let response: Response;
68
116
  try {
@@ -124,13 +172,13 @@ export async function loadProjects(config: ProcrastimateConfig): Promise<Project
124
172
  return projects;
125
173
  }
126
174
 
127
- type Encoded = { blob: Blob; width: number; height: number };
175
+ export type EncodedImage = { blob: Blob; width: number; height: number };
128
176
 
129
177
  /**
130
178
  * A JPEG of the image no wider than `width` and no larger than `maxBytes`. ProcrastiMate's own clients fit the long
131
179
  * side. A full-length capture is many times taller than wide, so this fits the width, which keeps its text readable.
132
180
  */
133
- async function jpeg(image: HTMLCanvasElement, width: number, maxBytes: number): Promise<Encoded> {
181
+ async function jpeg(image: HTMLCanvasElement, width: number, maxBytes: number): Promise<EncodedImage> {
134
182
  for (let target = Math.min(width, image.width); target >= 64; target = Math.floor((target * 3) / 4)) {
135
183
  const scaled = document.createElement('canvas');
136
184
  scaled.width = target;
@@ -146,6 +194,13 @@ async function jpeg(image: HTMLCanvasElement, width: number, maxBytes: number):
146
194
  throw new Error('The image could not be made small enough to upload.');
147
195
  }
148
196
 
197
+ /** Encodes the full-size image and thumbnail JPEGs within ProcrastiMate's upload caps. */
198
+ export async function encodeTaskImages(image: HTMLCanvasElement): Promise<{ full: EncodedImage; thumb: EncodedImage }> {
199
+ const full = await jpeg(image, 2048, 1_500_000);
200
+ const thumb = await jpeg(image, 320, 200_000);
201
+ return { full, thumb };
202
+ }
203
+
149
204
  /**
150
205
  * Creates one task with the image export and `feedback.json` attached, and returns its id. The attachments upload
151
206
  * before the task that lists them, as ProcrastiMate's own clients do, so the task never names bytes the server
@@ -163,10 +218,10 @@ export async function postTask(
163
218
  if (bytes.length > fileMaxBytes)
164
219
  throw new Error('The JSON report is over the 16 MB ProcrastiMate takes in one upload.');
165
220
  step('Encoding the image');
166
- const full = await jpeg(image, 2048, 1_500_000);
167
- const thumb = await jpeg(image, 320, 200_000);
168
- const imageId = crypto.randomUUID();
169
- const reportId = crypto.randomUUID();
221
+ const { full, thumb } = await encodeTaskImages(image);
222
+ const imageId = postId();
223
+ const reportId = postId();
224
+ const taskId = postId();
170
225
  step('Uploading the image');
171
226
  await send(config, 'PUT', 'api/images', { id: imageId, size: 'full' }, full.blob, 'image/jpeg');
172
227
  step('Uploading the thumbnail');
@@ -186,30 +241,19 @@ export async function postTask(
186
241
  'POST',
187
242
  'api/tasks',
188
243
  {},
189
- JSON.stringify({ title, projectId: place.projectId ?? null, sectionId: place.sectionId ?? null }),
244
+ JSON.stringify({
245
+ id: taskId,
246
+ title,
247
+ projectId: place.projectId ?? null,
248
+ sectionId: place.sectionId ?? null,
249
+ attachments: [
250
+ { id: imageId, width: full.width, height: full.height },
251
+ { id: reportId, name: 'feedback.json', type: 'application/json', bytes: bytes.length },
252
+ ],
253
+ }),
190
254
  'application/json',
191
255
  );
192
256
  const { id } = (await created.json()) as { id: string };
193
- // The agent API cannot create a task with attachments, so a failed attach would leave a task without them, and a retry would add a second one.
194
- step('Attaching the files');
195
- try {
196
- await send(
197
- config,
198
- 'PATCH',
199
- 'api/tasks',
200
- { id },
201
- JSON.stringify({
202
- attachments: [
203
- { id: imageId, width: full.width, height: full.height },
204
- { id: reportId, name: 'feedback.json', type: 'application/json', bytes: bytes.length },
205
- ],
206
- }),
207
- 'application/json',
208
- );
209
- } catch (error) {
210
- await send(config, 'DELETE', 'api/tasks', { id }).catch(() => {});
211
- throw error;
212
- }
213
257
  store(lastProjectKey, place.projectId);
214
258
  return id;
215
259
  }
@@ -0,0 +1,194 @@
1
+ import type { Annotations } from '../core/annotations.ts';
2
+ import { Problem, type Fact } from '../core/problem.ts';
3
+ import type { Screen } from './capture.ts';
4
+ import { annotatedImage } from './image.ts';
5
+ import { encodeTaskImages, fileMaxBytes, procrastimateAppURL, type ProcrastimateConfig } from './procrastimate.ts';
6
+ import { postId } from './webhook.ts';
7
+
8
+ export const FEEDBACK_READY = 'feedback:ready';
9
+ export const FEEDBACK_DRAFT = 'feedback:draft';
10
+ export const FEEDBACK_POSTED = 'feedback:posted';
11
+ export const FEEDBACK_CANCELLED = 'feedback:cancelled';
12
+
13
+ export type PopupReply =
14
+ | { kind: 'ready' }
15
+ | { kind: 'posted'; id: string; destination: string; url: string }
16
+ | { kind: 'cancelled' };
17
+
18
+ function isHttpURL(value: unknown): value is string {
19
+ if (typeof value !== 'string') return false;
20
+ try {
21
+ const parsed = new URL(value);
22
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:';
23
+ } catch {
24
+ return false;
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Validates a message posted back from ProcrastiMate's `/feedback` popup. Every message must come from the configured
30
+ * ProcrastiMate origin, from the popup window we opened, and carry this handoff's nonce.
31
+ */
32
+ export function parsePopupReply(
33
+ event: { origin: string; source: unknown; data: unknown },
34
+ expected: { origin: string; source: unknown; nonce: string },
35
+ ): PopupReply | null {
36
+ if (event.origin !== expected.origin || event.source !== expected.source) return null;
37
+ const data = event.data;
38
+ if (!data || typeof data !== 'object') return null;
39
+ const record = data as Record<string, unknown>;
40
+ if (record.nonce !== expected.nonce) return null;
41
+ if (record.type === FEEDBACK_READY) return { kind: 'ready' };
42
+ if (record.type === FEEDBACK_CANCELLED) return { kind: 'cancelled' };
43
+ if (
44
+ record.type === FEEDBACK_POSTED &&
45
+ typeof record.id === 'string' &&
46
+ typeof record.destination === 'string' &&
47
+ isHttpURL(record.url)
48
+ ) {
49
+ return { kind: 'posted', id: record.id, destination: record.destination, url: record.url };
50
+ }
51
+ return null;
52
+ }
53
+
54
+ function popupFeatures() {
55
+ const width = 460;
56
+ const height = 680;
57
+ const left = Math.max(0, Math.round((window.screenX ?? 0) + (window.outerWidth - width) / 2));
58
+ const top = Math.max(0, Math.round((window.screenY ?? 0) + (window.outerHeight - height) / 2));
59
+ return `popup,width=${width},height=${height},left=${left},top=${top}`;
60
+ }
61
+
62
+ /**
63
+ * Opens ProcrastiMate's `/feedback` popup synchronously (so the browser's click gesture allows `window.open`) while
64
+ * encoding the screenshot in parallel, then hands over the draft over `postMessage` once the popup signals ready.
65
+ * No credential ever leaves ProcrastiMate's own origin.
66
+ */
67
+ export function openProcrastimatePopup({
68
+ config,
69
+ title,
70
+ app,
71
+ screen,
72
+ annotations,
73
+ report,
74
+ onposted,
75
+ onerror,
76
+ onclose,
77
+ }: {
78
+ config: ProcrastimateConfig;
79
+ title: string;
80
+ app?: string;
81
+ screen: Screen;
82
+ annotations: Annotations;
83
+ report: string;
84
+ onposted: (result: { id: string; destination: string; url: string }) => void;
85
+ onerror: (problem: Problem) => void;
86
+ onclose?: () => void;
87
+ }): { cancel: () => void } {
88
+ const base = procrastimateAppURL(config);
89
+ const expectedOrigin = new URL(base, location.href).origin;
90
+ const nonce = postId();
91
+ const url = `${base}/feedback?nonce=${encodeURIComponent(nonce)}`;
92
+ const environment: Fact[] = screen.capture.environment.map(entry => ({ label: entry.name, value: entry.value }));
93
+ const reportBytes = new TextEncoder().encode(report).byteLength;
94
+ if (reportBytes > fileMaxBytes) {
95
+ onerror(
96
+ Problem.from(new Error('The JSON report is over the 16 MB ProcrastiMate takes in one upload.')).with(
97
+ [{ label: 'Report', value: `${reportBytes} bytes` }],
98
+ environment,
99
+ ),
100
+ );
101
+ return { cancel() {} };
102
+ }
103
+
104
+ const popup = window.open(url, 'feedback-procrastimate', popupFeatures());
105
+ if (!popup) {
106
+ onerror(
107
+ new Problem('The browser blocked ProcrastiMate’s window. Allow pop-ups for this site and try again.', [
108
+ { label: 'URL', value: url },
109
+ ...environment,
110
+ ]),
111
+ );
112
+ return { cancel() {} };
113
+ }
114
+
115
+ // Render synchronously before any await; encode JPEGs while the popup loads.
116
+ let prepared: Promise<{ full: Blob; thumb: Blob; width: number; height: number }>;
117
+ try {
118
+ const canvas = annotatedImage(screen, annotations);
119
+ prepared = encodeTaskImages(canvas).then(({ full, thumb }) => ({
120
+ full: full.blob,
121
+ thumb: thumb.blob,
122
+ width: full.width,
123
+ height: full.height,
124
+ }));
125
+ } catch (error) {
126
+ prepared = Promise.reject(error);
127
+ }
128
+ // Prevent an unhandled rejection if the user closes the popup before encoding settles.
129
+ prepared.catch(() => {});
130
+
131
+ let done = false;
132
+ const cleanup = () => {
133
+ if (done) return;
134
+ done = true;
135
+ window.removeEventListener('message', onMessage);
136
+ clearInterval(closedCheck);
137
+ };
138
+
139
+ const onMessage = (event: MessageEvent) => {
140
+ const reply = parsePopupReply(event, { origin: expectedOrigin, source: popup, nonce });
141
+ if (!reply) return;
142
+ if (reply.kind === 'ready') {
143
+ void prepared
144
+ .then(image => {
145
+ if (done || popup.closed) return;
146
+ popup.postMessage(
147
+ {
148
+ type: FEEDBACK_DRAFT,
149
+ nonce,
150
+ title,
151
+ app,
152
+ project: config.project,
153
+ projects: config.projects,
154
+ space: config.space,
155
+ image,
156
+ report,
157
+ },
158
+ expectedOrigin,
159
+ );
160
+ })
161
+ .catch((error: unknown) => {
162
+ cleanup();
163
+ try {
164
+ popup.close();
165
+ } catch {
166
+ // Ignore if already closed.
167
+ }
168
+ onerror(
169
+ Problem.from(error).with(
170
+ [
171
+ { label: 'Step', value: 'Encoding the image' },
172
+ { label: 'URL', value: url },
173
+ ],
174
+ environment,
175
+ ),
176
+ );
177
+ });
178
+ return;
179
+ }
180
+ cleanup();
181
+ if (reply.kind === 'posted') onposted(reply);
182
+ else onclose?.();
183
+ };
184
+
185
+ window.addEventListener('message', onMessage);
186
+ const closedCheck = setInterval(() => {
187
+ if (popup.closed) {
188
+ cleanup();
189
+ onclose?.();
190
+ }
191
+ }, 400);
192
+
193
+ return { cancel: cleanup };
194
+ }
@@ -9,11 +9,13 @@
9
9
  Problem,
10
10
  Session,
11
11
  tag,
12
+ taskTitle,
12
13
  title,
13
14
  type Frame,
14
15
  type SavedWebhook,
15
16
  } from '../core/index.ts';
16
17
  import type { Screen } from '../dom/capture.ts';
18
+ import { openProcrastimatePopup } from '../dom/procrastimatePopup.ts';
17
19
  import {
18
20
  buildExport,
19
21
  canShare,
@@ -98,7 +100,10 @@
98
100
  let showsItems = $state(matchMedia('(min-width: 900px)').matches);
99
101
  let showsShare = $state(false);
100
102
  let showsProcrastimate = $state(false);
103
+ let popup = { cancel() {} };
101
104
  let posting = $state<Delivery>();
105
+
106
+ $effect(() => () => popup.cancel());
102
107
  let saved = $state(loadSavedWebhooks());
103
108
  /** The dialog for a saved webhook, `webhook` unset for a new one. */
104
109
  let editing = $state<{ webhook?: SavedWebhook }>();
@@ -263,6 +268,8 @@
263
268
  // The error is drawn over the other sheets, so it is the one to leave first.
264
269
  if (failure) {
265
270
  failure = undefined;
271
+ } else if (confirmsClose) {
272
+ confirmsClose = false;
266
273
  } else if (showsInfo || showsShare || showsProcrastimate || posting || pending || editing) {
267
274
  showsInfo = showsShare = showsProcrastimate = false;
268
275
  posting = pending = editing = undefined;
@@ -275,8 +282,36 @@
275
282
 
276
283
  function send(destination: Destination) {
277
284
  showsShare = false;
278
- if (destination.kind === 'procrastimate') showsProcrastimate = true;
279
- else if (destination.kind === 'saved') edit(destination.saved);
285
+ if (destination.kind === 'procrastimate') {
286
+ const config = engine.options.procrastimate;
287
+ if (!config) return;
288
+ if (config.url !== undefined) {
289
+ showsProcrastimate = true;
290
+ } else {
291
+ popup.cancel();
292
+ const items = [...session.items];
293
+ const names = taskTitle(session.capture, items);
294
+ popup = openProcrastimatePopup({
295
+ config,
296
+ title: names.placeholder,
297
+ app: engine.options.app ?? (document.title.trim() || undefined),
298
+ screen,
299
+ annotations: session.annotations,
300
+ report: session.compactJSON,
301
+ onposted: ({ destination: where, url }) => {
302
+ act(() => {
303
+ session.markShared(items);
304
+ session.toast = { text: `Added to ${where} in ProcrastiMate`, link: url };
305
+ });
306
+ },
307
+ onerror: problem => {
308
+ act(() => {
309
+ session.toast = { text: 'Couldn’t open ProcrastiMate', problem };
310
+ });
311
+ },
312
+ });
313
+ }
314
+ } else if (destination.kind === 'saved') edit(destination.saved);
280
315
  else posting = destination.delivery;
281
316
  }
282
317
 
@@ -345,7 +380,10 @@
345
380
  class="editor"
346
381
  aria-label="Feedback"
347
382
  onpointerdown={event => {
348
- if (showsInfo && !(event.target as Element).closest('.title')) showsInfo = false;
383
+ const target = event.target as Element;
384
+ if (showsInfo && !target.closest('.title')) showsInfo = false;
385
+ // The close button leaves the menu itself, as Escape does, instead of the editor behind it.
386
+ if (showsShare && !target.closest('.menu, .close')) showsShare = false;
349
387
  }}
350
388
  oncancel={event => {
351
389
  event.preventDefault();
@@ -353,7 +391,7 @@
353
391
  }}
354
392
  >
355
393
  <header>
356
- <button type="button" class="nav" aria-label="Close" onclick={requestClose}>
394
+ <button type="button" class="nav close" aria-label="Close" title="Close" onclick={requestClose}>
357
395
  <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18" /></svg>
358
396
  </button>
359
397
  <h1>Feedback</h1>
@@ -696,7 +734,11 @@
696
734
  {/if}
697
735
 
698
736
  {#if confirmsClose}
699
- <div class="scrim" role="presentation">
737
+ <div
738
+ class="scrim"
739
+ role="presentation"
740
+ onclick={event => event.target === event.currentTarget && (confirmsClose = false)}
741
+ >
700
742
  <div class="sheet actions" role="alertdialog" tabindex="-1" aria-label="Discard feedback?">
701
743
  <h2>Discard feedback?</h2>
702
744
  <p>
@@ -7,9 +7,11 @@
7
7
  import {
8
8
  cachedProjects,
9
9
  lastProject,
10
+ listedProjects,
10
11
  loadProjects,
11
- namedProject,
12
12
  postTask,
13
+ projectLink,
14
+ startingProject,
13
15
  taskLink,
14
16
  type Place,
15
17
  type ProcrastimateConfig,
@@ -34,11 +36,10 @@
34
36
  // svelte-ignore state_referenced_locally
35
37
  const names = taskTitle(session.capture, session.items);
36
38
  let name = $state(names.placeholder);
37
- let projects = $state(cachedProjects());
39
+ let all = $state(cachedProjects());
40
+ const projects = $derived(listedProjects(all, config.projects).projects);
38
41
  // svelte-ignore state_referenced_locally
39
- let place = $state<Place>({
40
- projectId: config.project ? namedProject(projects, config.project)?.id : lastProject(),
41
- });
42
+ let place = $state<Place>({ projectId: startingProject(projects, config, lastProject()) });
42
43
  let loading = $state(true);
43
44
  /** Whether the user chose a place, which a project list that finishes loading must not undo. */
44
45
  let chosen = false;
@@ -47,8 +48,8 @@
47
48
  /** What the post is doing, while it runs. */
48
49
  let step = $state<string>();
49
50
  const posting = $derived(step !== undefined);
50
- /** Until the projects load, a post would land in the Inbox instead of the project the app named. */
51
- const unresolved = $derived(loading && !!config.project && !place.projectId);
51
+ /** Without a project, a post would land in the Inbox, which Feedback never posts to. */
52
+ const unresolved = $derived(!place.projectId);
52
53
  let status = $state<HTMLElement>();
53
54
  // svelte-ignore state_referenced_locally
54
55
  const environment: Fact[] = session.capture.environment.map(entry => ({ label: entry.name, value: entry.value }));
@@ -56,15 +57,18 @@
56
57
  $effect(() => {
57
58
  loadProjects(config)
58
59
  .then(loaded => {
59
- projects = loaded;
60
- if (config.project) {
61
- const named = namedProject(loaded, config.project);
62
- if (!named) throw new Error(`ProcrastiMate has no project named "${config.project}"`);
63
- if (!chosen) place = { projectId: named.id };
64
- }
65
- const project = loaded.find(candidate => candidate.id === place.projectId);
66
- if (!project) place = {};
60
+ all = loaded;
61
+ const listed = listedProjects(loaded, config.projects);
62
+ if (!chosen) place = { projectId: startingProject(listed.projects, config, lastProject()) };
63
+ const project = listed.projects.find(candidate => candidate.id === place.projectId);
64
+ if (!project) place = { projectId: listed.projects[0]?.id };
67
65
  else if (!project.sections.some(section => section.id === place.sectionId)) place = { projectId: project.id };
66
+ const missing = [...listed.missing];
67
+ if (config.project && !startingProject(listed.projects, config, undefined)) missing.push(config.project);
68
+ if (missing.length) {
69
+ const names = [...new Set(missing)].map(name => `"${name}"`).join(', ');
70
+ throw new Error(`ProcrastiMate has no project named ${names} among the projects Feedback may post to`);
71
+ }
68
72
  })
69
73
  .catch(
70
74
  (error: unknown) =>
@@ -84,18 +88,18 @@
84
88
  const facts: Fact[] = [
85
89
  {
86
90
  label: 'Place',
87
- value: [project ? `${project.name} (${project.id})` : 'Inbox', section && `${section.name} (${section.id})`]
91
+ value: [project && `${project.name} (${project.id})`, section && `${section.name} (${section.id})`]
88
92
  .filter(Boolean)
89
93
  .join(' / '),
90
94
  },
91
95
  { label: 'Report', value: `${new TextEncoder().encode(report).length} bytes` },
92
- { label: 'Server', value: config.url },
96
+ { label: 'Server', value: config.url ?? '' },
93
97
  ];
94
98
  try {
95
99
  const image = annotatedImage(screen, session.annotations);
96
100
  facts.push({ label: 'Image', value: `${image.width} × ${image.height} px` });
97
101
  const id = await postTask(config, name.trim(), place, image, report, text => (step = text));
98
- const destination = [project?.name ?? 'Inbox', section?.name].filter(Boolean).join(' / ');
102
+ const destination = [project?.name, section?.name].filter(Boolean).join(' / ');
99
103
  onposted(items, { text: `Added to ${destination} in ProcrastiMate`, link: taskLink(config, id) });
100
104
  } catch (error) {
101
105
  const elapsed = { label: 'Elapsed', value: `${((performance.now() - started) / 1000).toFixed(1)} s` };
@@ -113,22 +117,32 @@
113
117
  });
114
118
  </script>
115
119
 
116
- {#snippet row(label: string, picked: boolean, indented: boolean, pick: () => void)}
117
- <button
118
- type="button"
119
- class="row"
120
- class:indented
121
- role="option"
122
- aria-selected={picked}
123
- disabled={posting}
124
- onclick={() => {
125
- chosen = true;
126
- pick();
127
- }}
128
- >
129
- <span>{label}</span>
130
- {#if picked}<span class="check" aria-hidden="true">✓</span>{/if}
131
- </button>
120
+ {#snippet row(label: string, picked: boolean, indented: boolean, pick: () => void, link?: string)}
121
+ <div class="row" class:indented>
122
+ <button
123
+ type="button"
124
+ role="option"
125
+ aria-selected={picked}
126
+ disabled={posting}
127
+ onclick={() => {
128
+ chosen = true;
129
+ pick();
130
+ }}
131
+ >
132
+ <span>{label}</span>
133
+ {#if picked}<span class="check" aria-hidden="true">✓</span>{/if}
134
+ </button>
135
+ {#if link}
136
+ <a
137
+ class="open"
138
+ href={link}
139
+ target="_blank"
140
+ rel="noopener"
141
+ aria-label="Open {label} in ProcrastiMate"
142
+ title="Open in ProcrastiMate">↗</a
143
+ >
144
+ {/if}
145
+ </div>
132
146
  {/snippet}
133
147
 
134
148
  <Sheet label="Add to ProcrastiMate" onsubmit={() => void post()}>
@@ -151,7 +165,6 @@
151
165
  </label>
152
166
  <span class="caption">Project{loading ? ' · loading…' : ''}</span>
153
167
  <div class="list" role="listbox" aria-label="Project">
154
- {@render row('Inbox', !place.projectId, false, () => (place = {}))}
155
168
  {#each projects as project (project.id)}
156
169
  {@const open = project.id === place.projectId && project.sections.length > 0}
157
170
  {@render row(
@@ -159,6 +172,7 @@
159
172
  project.id === place.projectId && !open,
160
173
  false,
161
174
  () => (place = { projectId: project.id }),
175
+ projectLink(config, project.id),
162
176
  )}
163
177
  {#if open}
164
178
  {@render row('No section', !place.sectionId, true, () => (place = { projectId: project.id }))}
@@ -189,17 +203,31 @@
189
203
 
190
204
  .row {
191
205
  display: flex;
206
+ border-bottom: 1px solid rgb(255 255 255 / 0.08);
207
+ }
208
+
209
+ .row > button {
210
+ display: flex;
211
+ flex: 1;
192
212
  justify-content: space-between;
193
213
  gap: 8px;
194
- border-bottom: 1px solid rgb(255 255 255 / 0.08);
195
214
  padding: 11px 12px;
196
215
  text-align: left;
197
216
  }
198
217
 
199
- .row.indented {
218
+ .row.indented > button {
200
219
  padding-left: 40px;
201
220
  }
202
221
 
222
+ .open {
223
+ display: grid;
224
+ place-items: center;
225
+ width: 44px;
226
+ border-left: 1px solid rgb(255 255 255 / 0.08);
227
+ color: #0a84ff;
228
+ text-decoration: none;
229
+ }
230
+
203
231
  .check {
204
232
  color: #0a84ff;
205
233
  font-weight: 700;
@@ -63,6 +63,7 @@
63
63
  <button type="button" onclick={onclose}>Cancel</button>
64
64
  {:else}
65
65
  <p role="status">{step}…</p>
66
+ <button type="button" onclick={onclose}>Cancel</button>
66
67
  {/if}
67
68
  </div>
68
69
  </div>
@@ -26,8 +26,10 @@ export type FeedbackOptions = {
26
26
  */
27
27
  threeFingerHold?: boolean;
28
28
  /**
29
- * Adds ProcrastiMate to the Share menu. Leave it out behind `feedbackProcrastimate()` from the Vite entry point,
30
- * which adds the entry by itself when it has a token. Set it for a proxy of your own.
29
+ * Adds ProcrastiMate to the Share menu. Pass `{ projects: ['Website'] }` (with no `url`) to post through a popup on
30
+ * the ProcrastiMate web app using whoever is signed in there, with no token and no proxy. Pass `{ url, projects }`
31
+ * for a same-origin API or a proxy of your own. Leave it out behind `feedbackProcrastimate()` from the Vite entry
32
+ * point, which adds the entry by itself when it has a token.
31
33
  */
32
34
  procrastimate?: ProcrastimateConfig;
33
35
  /**
@@ -60,10 +60,15 @@ export function setupFeedbackEngine(options: FeedbackOptions = {}): FeedbackEngi
60
60
  type Meta = { env?: Record<string, string | undefined> };
61
61
  const proxy = (import.meta as Meta).env && (import.meta as Meta).env!.FEEDBACK_PROCRASTIMATE;
62
62
  const project = (import.meta as Meta).env && (import.meta as Meta).env!.FEEDBACK_PROCRASTIMATE_PROJECT;
63
- const engine = new Engine({
64
- ...options,
65
- procrastimate: options.procrastimate ?? (proxy ? { url: proxy, project: project || undefined } : undefined),
66
- });
63
+ const projects = (import.meta as Meta).env && (import.meta as Meta).env!.FEEDBACK_PROCRASTIMATE_PROJECTS;
64
+ const procrastimate =
65
+ options.procrastimate ??
66
+ (proxy
67
+ ? { url: proxy, project: project || undefined, projects: JSON.parse(projects || '[]') as string[] }
68
+ : undefined);
69
+ if (procrastimate && !procrastimate.projects?.length)
70
+ throw new Error('setupFeedbackEngine({ procrastimate }) needs the projects Feedback may post to, by name or id.');
71
+ const engine = new Engine({ ...options, procrastimate });
67
72
  const host = document.createElement('div');
68
73
  host.setAttribute(hostAttribute, '');
69
74
  // The shadow root keeps the app's styles out of the editor and the editor's styles out of the app.
@@ -24,18 +24,34 @@ export type FeedbackOptions = {
24
24
  */
25
25
  threeFingerHold?: boolean;
26
26
  /**
27
- * Adds ProcrastiMate to the Share menu. Leave it out behind `feedbackProcrastimate()` from the Vite entry point,
28
- * which adds the entry by itself when it has a token. Set it for a proxy of your own.
27
+ * Adds ProcrastiMate to the Share menu. Pass `{ projects: ['Website'] }` (with no `url`) to post through a popup on
28
+ * the ProcrastiMate web app using whoever is signed in there, with no token and no proxy. Pass `{ url, projects }`
29
+ * for a same-origin API or a proxy of your own. Leave it out behind `feedbackProcrastimate()` from the Vite entry
30
+ * point, which adds the entry by itself when it has a token.
29
31
  */
30
32
  procrastimate?: {
31
- /** Where ProcrastiMate's API answers: the Vite plugin's proxy path, or a server that allows this origin. */
32
- url: string;
33
- /** Sent as a bearer token. Leave it out behind the proxy, which adds its own. */
33
+ /**
34
+ * Where ProcrastiMate's API answers: the Vite plugin's proxy path, or a server that allows this origin. Leave it
35
+ * out to open a popup on the ProcrastiMate web app (`app`) that posts using whoever is signed in there, with no
36
+ * token and no proxy.
37
+ */
38
+ url?: string;
39
+ /** Sent as a bearer token. Leave it out behind the proxy or when posting through the popup. */
34
40
  token?: string;
35
- /** The ProcrastiMate web app, for the link to a posted task. */
41
+ /** The ProcrastiMate web app, for the popup and for links to posted tasks and projects. */
36
42
  app?: string;
37
43
  /** The project the picker opens on, by name (ignoring case) or id, in place of the last one posted to. */
38
44
  project?: string;
45
+ /**
46
+ * The only projects the picker offers, by name (ignoring case) or id, in this order. The Inbox is not offered.
47
+ * Required, and not empty. A proxy of your own should refuse tasks anywhere else.
48
+ */
49
+ projects: string[];
50
+ /**
51
+ * Another user's space (their ProcrastiMate user id) whose shared projects the picker lists. Leave it out to match
52
+ * across the signed-in user's own and edit-shared projects in the popup, or the token's space behind a proxy.
53
+ */
54
+ space?: string;
39
55
  };
40
56
  /**
41
57
  * Adds one entry to the Share menu per webhook. Choosing it posts the image export and the JSON export to the
@@ -14,9 +14,10 @@ export function feedbackEngine(options?: {
14
14
 
15
15
  /**
16
16
  * A Vite plugin that forwards `path` on the dev and preview servers to ProcrastiMate and adds the token there. With a
17
- * token, the Share menu lists ProcrastiMate. Without one it does not.
17
+ * token, the Share menu lists ProcrastiMate. Without one it does not. It forwards only what a post needs, and creates
18
+ * tasks only in the listed projects.
18
19
  */
19
- export function feedbackProcrastimate(options?: {
20
+ export function feedbackProcrastimate(options: {
20
21
  /** ProcrastiMate's origin. Defaults to `https://procrastimate.stf.lol`. */
21
22
  url?: string;
22
23
  /** A ProcrastiMate API token. Pass `process.env.PROCRASTIMATE_TOKEN`, so the entry shows only where it is set. */
@@ -25,6 +26,11 @@ export function feedbackProcrastimate(options?: {
25
26
  path?: string;
26
27
  /** The project the picker opens on, by name (ignoring case) or id, in place of the last one posted to. */
27
28
  project?: string;
29
+ /**
30
+ * The only projects Feedback posts to, by name (ignoring case) or id, in the picker's order, each with a link to its
31
+ * page in ProcrastiMate. The proxy refuses a task anywhere else, the Inbox included. Required, and not empty.
32
+ */
33
+ projects: string[];
28
34
  }): Plugin;
29
35
 
30
36
  /**
package/src/vite/index.js CHANGED
@@ -1,14 +1,11 @@
1
1
  import { basename, relative, sep } from 'node:path';
2
2
  import { parse } from 'svelte/compiler';
3
3
 
4
+ export { feedbackProcrastimate } from './procrastimate.js';
4
5
  export { addReact, feedbackEngineReact, sourceAttribute } from './react.js';
5
6
 
6
7
  const entry = '@stefan.inc/feedback-engine/svelte';
7
8
 
8
- /** What `setupFeedbackEngine()` reads for the proxy's path. `editor/setup.ts` spells the same name. */
9
- const procrastimateDefine = 'import.meta.env.FEEDBACK_PROCRASTIMATE';
10
- const procrastimateProjectDefine = 'import.meta.env.FEEDBACK_PROCRASTIMATE_PROJECT';
11
-
12
9
  /**
13
10
  * The name a tag gets without one: the file's, as `.feedback(self)` uses the type's on iOS. A SvelteKit route file is
14
11
  * named after its folder, so `routes/lists/[id]/+page.svelte` is `ListsIdPage`.
@@ -146,68 +143,3 @@ export function feedbackEngine(options = {}) {
146
143
  },
147
144
  };
148
145
  }
149
-
150
- /**
151
- * A Vite plugin that lets the page post to ProcrastiMate. A browser on another origin cannot call ProcrastiMate, and a
152
- * token in the page would be public, so the dev and preview servers forward `path` to ProcrastiMate and add the
153
- * token there.
154
- *
155
- * The token is the switch. With one, the plugin tells the page where the proxy is, and the Share menu lists
156
- * ProcrastiMate. Without one the page is told nothing, so the entry is not there. A page that names the path itself
157
- * then gets a 501 that says why.
158
- *
159
- * @param {{ url?: string, token?: string, path?: string, project?: string }} [options]
160
- */
161
- export function feedbackProcrastimate(options = {}) {
162
- const path = options.path ?? '/__feedback/procrastimate';
163
- const target = (options.url ?? 'https://procrastimate.stf.lol').replace(/\/$/, '');
164
- /** @type {import('vite').Connect.NextHandleFunction} */
165
- const handler = async (request, response, next) => {
166
- if (!request.url?.startsWith(`${path}/`)) return next();
167
- const reply = (/** @type {number} */ status, /** @type {string} */ message) => {
168
- response.statusCode = status;
169
- response.setHeader('Content-Type', 'application/json');
170
- response.end(JSON.stringify({ message }));
171
- };
172
- if (!options.token)
173
- return reply(501, 'the dev server has no ProcrastiMate token. Pass one to feedbackProcrastimate().');
174
- try {
175
- const chunks = [];
176
- for await (const chunk of request) chunks.push(chunk);
177
- const body = Buffer.concat(chunks);
178
- const upstream = await fetch(target + request.url.slice(path.length), {
179
- method: request.method,
180
- headers: {
181
- Authorization: `Bearer ${options.token}`,
182
- 'User-Agent': 'Feedback',
183
- ...(request.headers['content-type'] ? { 'Content-Type': request.headers['content-type'] } : {}),
184
- },
185
- body: body.length ? body : undefined,
186
- });
187
- response.statusCode = upstream.status;
188
- response.setHeader('Content-Type', upstream.headers.get('content-type') ?? 'application/json');
189
- response.end(Buffer.from(await upstream.arrayBuffer()));
190
- } catch (error) {
191
- reply(502, `the dev server could not reach ${target}: ${/** @type {Error} */ (error).message}`);
192
- }
193
- };
194
- return {
195
- name: 'feedback-engine-procrastimate',
196
- config() {
197
- return {
198
- define: {
199
- [procrastimateDefine]: JSON.stringify(options.token ? path : ''),
200
- [procrastimateProjectDefine]: JSON.stringify(options.project ?? ''),
201
- },
202
- };
203
- },
204
- /** @param {import('vite').ViteDevServer} server */
205
- configureServer(server) {
206
- server.middlewares.use(handler);
207
- },
208
- /** @param {import('vite').PreviewServer} server */
209
- configurePreviewServer(server) {
210
- server.middlewares.use(handler);
211
- },
212
- };
213
- }
@@ -0,0 +1,11 @@
1
+ export { feedbackProcrastimate } from './index.js';
2
+
3
+ type Project = { id: string; name: string };
4
+ type View = { projects: Project[]; sections: { id: string; projectId: string }[] };
5
+
6
+ export function allowedProjectIds(projects: Project[], names: string[]): Set<string>;
7
+ export function refusal(
8
+ call: { method: string; route: string; query: URLSearchParams; body: string },
9
+ state: { allowed?: Set<string>; created: Set<string> },
10
+ ): string | undefined;
11
+ export function allowedView(view: View, allowed: Set<string>): View;
@@ -0,0 +1,187 @@
1
+ /** What `setupFeedbackEngine()` reads. `editor/setup.ts` spells the same names. */
2
+ const pathDefine = 'import.meta.env.FEEDBACK_PROCRASTIMATE';
3
+ const projectDefine = 'import.meta.env.FEEDBACK_PROCRASTIMATE_PROJECT';
4
+ const projectsDefine = 'import.meta.env.FEEDBACK_PROCRASTIMATE_PROJECTS';
5
+
6
+ /**
7
+ * @typedef {{ id: string, name: string }} Project
8
+ * @typedef {{ projects: Project[], sections: { id: string, projectId: string }[] }} View
9
+ */
10
+
11
+ /**
12
+ * The ids of the projects `names` lists, each by id or by name ignoring case, as the picker matches them.
13
+ *
14
+ * @param {Project[]} projects
15
+ * @param {string[]} names
16
+ */
17
+ export function allowedProjectIds(projects, names) {
18
+ /** @type {Set<string>} */
19
+ const ids = new Set();
20
+ for (const name of names) {
21
+ const project =
22
+ projects.find(candidate => candidate.id === name) ??
23
+ projects.find(candidate => candidate.name.toLowerCase() === name.toLowerCase());
24
+ if (project) ids.add(project.id);
25
+ }
26
+ return ids;
27
+ }
28
+
29
+ /**
30
+ * Why the proxy refuses a call, or `undefined` to forward it. The token can do anything in the space, so the proxy
31
+ * forwards only the calls a post makes: listing the projects, uploading its files, creating a task in an allowed
32
+ * project, and attaching the files to, or deleting, a task this proxy created.
33
+ *
34
+ * @param {{ method: string, route: string, query: URLSearchParams, body: string }} call
35
+ * @param {{ allowed?: Set<string>, created: Set<string> }} state `allowed` is needed only to create a task.
36
+ */
37
+ export function refusal({ method, route, query, body }, { allowed, created }) {
38
+ const key = `${method} ${route}`;
39
+ if (key === 'GET api/view' || key === 'PUT api/images') return;
40
+ if (key === 'POST api/tasks') {
41
+ /** @type {{ projectId?: string | null }} */
42
+ let task;
43
+ try {
44
+ task = JSON.parse(body);
45
+ } catch {
46
+ return 'the task is not JSON';
47
+ }
48
+ if (!task.projectId || !allowed?.has(task.projectId))
49
+ return 'Feedback posts only to the projects feedbackProcrastimate({ projects }) lists';
50
+ return;
51
+ }
52
+ if (key === 'PATCH api/tasks' || key === 'DELETE api/tasks') {
53
+ const id = query.get('id');
54
+ if (!id || !created.has(id)) return 'Feedback changes only the tasks it created';
55
+ if (method === 'PATCH') {
56
+ try {
57
+ if (Object.keys(JSON.parse(body)).some(field => field !== 'attachments'))
58
+ return 'Feedback only attaches files to a task it created';
59
+ } catch {
60
+ return 'the change is not JSON';
61
+ }
62
+ }
63
+ return;
64
+ }
65
+ return `Feedback does not forward ${method} /${route}`;
66
+ }
67
+
68
+ /**
69
+ * The view with only the allowed projects and their sections, which is all the picker reads.
70
+ *
71
+ * @param {View} view
72
+ * @param {Set<string>} allowed
73
+ */
74
+ export const allowedView = (view, allowed) => ({
75
+ projects: view.projects.filter(project => allowed.has(project.id)),
76
+ sections: view.sections.filter(section => allowed.has(section.projectId)),
77
+ });
78
+
79
+ /**
80
+ * A Vite plugin that lets the page post to ProcrastiMate. A browser on another origin cannot call ProcrastiMate, and a
81
+ * token in the page would be public, so the dev and preview servers forward `path` to ProcrastiMate and add the
82
+ * token there.
83
+ *
84
+ * The token is the switch. With one, the plugin tells the page where the proxy is, and the Share menu lists
85
+ * ProcrastiMate. Without one the page is told nothing, so the entry is not there. A page that names the path itself
86
+ * then gets a 501 that says why.
87
+ *
88
+ * @param {{ url?: string, token?: string, path?: string, project?: string, projects: string[] }} options
89
+ */
90
+ export function feedbackProcrastimate(options) {
91
+ if (!options?.projects?.length)
92
+ throw new Error(
93
+ 'feedbackProcrastimate({ projects }) needs the ProcrastiMate projects Feedback may post to, by name or id.',
94
+ );
95
+ const { projects } = options;
96
+ const path = options.path ?? '/__feedback/procrastimate';
97
+ const target = (options.url ?? 'https://procrastimate.stf.lol').replace(/\/$/, '');
98
+ /** @type {Set<string>} */
99
+ const created = new Set();
100
+
101
+ /** @param {string} route @param {RequestInit} [init] */
102
+ const upstream = (route, init = {}) =>
103
+ fetch(`${target}/${route}`, {
104
+ ...init,
105
+ headers: { Authorization: `Bearer ${options.token}`, 'User-Agent': 'Feedback', ...init.headers },
106
+ });
107
+
108
+ /** @type {import('vite').Connect.NextHandleFunction} */
109
+ const handler = (request, response, next) => {
110
+ if (!request.url?.startsWith(`${path}/`)) return next();
111
+ const reply = (/** @type {number} */ status, /** @type {string} */ message) => {
112
+ response.statusCode = status;
113
+ response.setHeader('Content-Type', 'application/json');
114
+ response.end(JSON.stringify({ message }));
115
+ };
116
+ if (!options.token)
117
+ return reply(501, 'the dev server has no ProcrastiMate token. Pass one to feedbackProcrastimate().');
118
+ const forward = async () => {
119
+ const chunks = [];
120
+ for await (const chunk of request) chunks.push(chunk);
121
+ const body = Buffer.concat(chunks);
122
+ const method = request.method ?? 'GET';
123
+ const relative = /** @type {string} */ (request.url).slice(path.length + 1);
124
+ const url = new URL(relative, 'http://proxy/');
125
+ const route = url.pathname.slice(1);
126
+ const send = async (/** @type {Response} */ answer, /** @type {Buffer} */ bytes) => {
127
+ response.statusCode = answer.status;
128
+ response.setHeader('Content-Type', answer.headers.get('content-type') ?? 'application/json');
129
+ response.end(bytes);
130
+ };
131
+ const view = async () => {
132
+ const answer = await upstream('api/view');
133
+ if (!answer.ok) return { answer };
134
+ const data = /** @type {View} */ (await answer.json());
135
+ return { answer, data, allowed: allowedProjectIds(data.projects, projects) };
136
+ };
137
+
138
+ if (method === 'GET' && route === 'api/view') {
139
+ const { answer, data, allowed } = await view();
140
+ if (!data) return send(answer, Buffer.from(await answer.arrayBuffer()));
141
+ response.setHeader('Content-Type', 'application/json');
142
+ return response.end(JSON.stringify(allowedView(data, allowed)));
143
+ }
144
+ const creates = method === 'POST' && route === 'api/tasks';
145
+ let allowed;
146
+ if (creates) {
147
+ const listed = await view();
148
+ if (!listed.data) return send(listed.answer, Buffer.from(await listed.answer.arrayBuffer()));
149
+ allowed = listed.allowed;
150
+ }
151
+ const why = refusal({ method, route, query: url.searchParams, body: body.toString() }, { allowed, created });
152
+ if (why) return reply(403, why);
153
+ const answer = await upstream(relative, {
154
+ method,
155
+ headers: request.headers['content-type'] ? { 'Content-Type': request.headers['content-type'] } : {},
156
+ body: body.length ? body : undefined,
157
+ });
158
+ const bytes = Buffer.from(await answer.arrayBuffer());
159
+ if (answer.ok && creates) created.add(/** @type {{ id: string }} */ (JSON.parse(bytes.toString())).id);
160
+ if (answer.ok && method === 'DELETE') created.delete(url.searchParams.get('id') ?? '');
161
+ send(answer, bytes);
162
+ };
163
+ forward().catch(error =>
164
+ reply(502, `the dev server could not reach ${target}: ${/** @type {Error} */ (error).message}`),
165
+ );
166
+ };
167
+ return {
168
+ name: 'feedback-engine-procrastimate',
169
+ config() {
170
+ return {
171
+ define: {
172
+ [pathDefine]: JSON.stringify(options.token ? path : ''),
173
+ [projectDefine]: JSON.stringify(options.project ?? ''),
174
+ [projectsDefine]: JSON.stringify(JSON.stringify(projects)),
175
+ },
176
+ };
177
+ },
178
+ /** @param {import('vite').ViteDevServer} server */
179
+ configureServer(server) {
180
+ server.middlewares.use(handler);
181
+ },
182
+ /** @param {import('vite').PreviewServer} server */
183
+ configurePreviewServer(server) {
184
+ server.middlewares.use(handler);
185
+ },
186
+ };
187
+ }