@milesroxas/design-hub 0.8.0 → 0.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.
Files changed (64) hide show
  1. package/README.md +7 -2
  2. package/core/prototype.test.ts +83 -0
  3. package/core/prototype.ts +84 -0
  4. package/core/review/model.ts +20 -2
  5. package/core/review/policy.test.ts +4 -2
  6. package/core/review/policy.ts +4 -2
  7. package/core/review/service.test.ts +200 -16
  8. package/core/review/service.ts +91 -5
  9. package/core/review/store.ts +10 -1
  10. package/dist/core/prototype.d.ts +35 -0
  11. package/dist/core/prototype.js +84 -0
  12. package/dist/core/review/model.d.ts +13 -2
  13. package/dist/core/review/model.js +13 -0
  14. package/dist/core/review/policy.d.ts +1 -1
  15. package/dist/core/review/policy.js +1 -0
  16. package/dist/core/review/service.d.ts +24 -2
  17. package/dist/core/review/service.js +81 -6
  18. package/dist/core/review/store.d.ts +10 -1
  19. package/dist/core/review/store.js +10 -1
  20. package/dist/scripts/comments.js +4 -3
  21. package/dist/scripts/lib/cdp.js +6 -1
  22. package/dist/scripts/lib/export-smoke.d.ts +18 -0
  23. package/dist/scripts/lib/export-smoke.js +73 -0
  24. package/dist/scripts/new.js +5 -2
  25. package/dist/scripts/release-check.d.ts +5 -3
  26. package/dist/scripts/release-check.js +17 -4
  27. package/dist/scripts/share.d.ts +2 -2
  28. package/dist/server/api.js +8 -0
  29. package/dist/server/session.d.ts +5 -1
  30. package/dist/server/session.js +39 -21
  31. package/dist/vercel/proxy.js +44 -8
  32. package/dist/vite/boundary.d.ts +93 -0
  33. package/dist/vite/boundary.js +218 -0
  34. package/dist/vite/css-boundary.d.ts +39 -0
  35. package/dist/vite/css-boundary.js +167 -0
  36. package/dist/vite/kit.js +15 -6
  37. package/dist/vite/leaks.d.ts +37 -0
  38. package/dist/vite/leaks.js +331 -0
  39. package/dist/vite/plugin.js +2 -1
  40. package/dist/vite/registry.d.ts +15 -4
  41. package/dist/vite/registry.js +531 -27
  42. package/dist/vite/settle.d.ts +27 -0
  43. package/dist/vite/settle.js +185 -0
  44. package/package.json +4 -3
  45. package/shell/ClientViewNote.tsx +18 -0
  46. package/shell/Guide.tsx +17 -2
  47. package/shell/Index.tsx +257 -25
  48. package/shell/audience.test.ts +63 -0
  49. package/shell/audience.ts +47 -0
  50. package/shell/hub.ts +36 -0
  51. package/shell/main.tsx +39 -5
  52. package/shell/registry.ts +28 -7
  53. package/shell/registry.virtual.d.ts +12 -4
  54. package/shell/review/Pins.tsx +8 -6
  55. package/shell/review/Review.tsx +8 -4
  56. package/shell/review/ThreadCard.tsx +6 -14
  57. package/shell/review/client.ts +16 -4
  58. package/shell/review/review.css +37 -24
  59. package/shell/shell.css +50 -3
  60. package/shell/system.css +5 -0
  61. package/skills/miles-deploy/SKILL.md +17 -0
  62. package/skills/miles-new-feature/SKILL.md +1 -1
  63. package/skills/miles-prototype/SKILL.md +14 -1
  64. package/skills/miles-review/SKILL.md +1 -1
package/README.md CHANGED
@@ -35,7 +35,7 @@ A feature group, top to bottom:
35
35
  1. **Heading.** The feature's name. `Walkthrough →` ends the line when `docs/sprints/<feature>/guide.md` exists.
36
36
  2. **Primary.** The one `sprint` row, its title 16px against 14px for every other row. Size alone marks it; no badge, no new shape.
37
37
  3. **Alternates.** Under an `Alternates` caption (12px, 500, quaternary text), indented 20px and joined to the primary by a 1px rail in `--border-secondary` on the primary's text edge. The rail makes them children of that one row; a heading of their own would make them peers of the feature. A stray second `sprint` renders here too.
38
- 4. **Internal explorations.** A toggle (`Internal explorations`, the count, a chevron), collapsed by default because explorations are working material, not the feature. The open state persists per group in `localStorage` (`index-explorations-open`). Typing in the filter opens every fold, so a match is never hidden. Open, the explorations are cards on a grid (`minmax(208px, 1fr)`, 8px gap). Every exploration lives here, never in the row list.
38
+ 4. **Explorations.** A toggle (`Explorations`, the count, a chevron), collapsed by default because explorations are working material, not the feature. The open state persists per group in `localStorage` (`index-explorations-open`). Typing in the filter opens every fold, so a match is never hidden. Open, the explorations are cards on a grid (`minmax(208px, 1fr)`, 8px gap). Every exploration lives here, never in the row list.
39
39
 
40
40
  Within any list: exploring above decided, then newest first.
41
41
 
@@ -49,6 +49,10 @@ Surfaces:
49
49
  - **Foot.** The count alone, in body type over a hairline (the Ledger Foot Rule).
50
50
  - **Lede.** 18px/28px Geist at 400, secondary text. `--font-voice` resolves to Geist inside the hub's `.sys` scope (`shell/system.css`), so the index never borrows the project's faces.
51
51
 
52
+ ### Audience
53
+
54
+ Every prototype is Internal until Studio marks it Client-facing; a Client's index lists only the client-facing ones, and the gate refuses an internal prototype's page and files to a Client. Studio, outside Client view, sees each prototype's audience in a fifth column beside its row (under a card), never inside the link: `Internal` on the internal comments' amber (`--sys-internal`), `Client-facing` in quaternary text, then a switch (`role="switch"`, a 28px track, its hit area grown to 40px). A switch shows at once and is undone, with a toast, when the save fails. **Client view** in the head shows the index as a client gets it, with the comment layer's note at the bottom and **Leave**; in it no switch and no audience word shows. A Client with nothing shared sees `Nothing shared yet`.
55
+
52
56
  ### Motion
53
57
 
54
58
  Nothing animates on a keyboard action.
@@ -76,8 +80,9 @@ Every person is named, and signs in with a one-time link that Studio makes in th
76
80
  - **A second device gets a second link** (`design-hub people link <id>`), and the first stays signed in. **Sign out everywhere** (`people sign-out <id>`) bumps the person's epoch, drops their unused links and returns one new link. **Revoke** ends their access everywhere.
77
81
  - **What a stale write cannot undo.** A person is a profile (name, team, kind, access end), written read-modify-write, plus two records only revoke and sign out everywhere touch: the revocation, written once and never cleared, and the epoch, raised only by `HINCRBY`. So a profile change that started before a revoke or a sign out everywhere and lands after it never clears the revocation or lowers the epoch, and two sign outs everywhere at once raise it twice.
78
82
  - **Access lasts the engagement.** Each person has an access end: 3 months, 6 months, or open-ended. The project default (`people access --access <length>`, or `bootstrap --review --access`) applies to a new Client and is 3 months when unset; a new Studio person is open-ended, and Studio can set one person's length from the People tab or `people access <id>`.
79
- - **The session** is one cookie, `__Host-hub_person`: `HttpOnly`, `Secure`, `SameSite=Lax`, signed with HMAC-SHA256 over the person, their epoch, an expiry, `checkedAt` (when the store last said yes) and the review store's URL, which is signed but never written into the token, so two projects that share a `GATE_SECRET` never accept each other's cookies, and versioned (`p3`), so a cookie from an older release never verifies. It lasts to the access end, at most 400 days, the longest a browser keeps one. For `CHECK_SECONDS` (5 minutes) after `checkedAt` any request passes on the signature. After that the next request, of any kind, asks the store: a current person passes with a fresh cookie whose expiry follows their current access end; a revoked, signed-out-everywhere or ended person gets 401 and the cookie cleared. The request's own headers never decide whether the store is asked, since the client chooses them. A store that fails answers 503 with `Retry-After`, and leaves the cookie, so an outage signs nobody out; the review panel reads `Retry-After` as try again, and a 503 without it as a site with no store. The API function answers the same way in JSON. The sign-in POST also refuses a store failure with 503, and a link is checked before it is used up, so a failure never burns one.
83
+ - **The session** is one cookie, `__Host-hub_person`: `HttpOnly`, `Secure`, `SameSite=Lax`, signed with HMAC-SHA256 over the person, their epoch, their kind (Studio or Client), an expiry, `checkedAt` (when the store last said yes) and the review store's URL, which is signed but never written into the token, so two projects that share a `GATE_SECRET` never accept each other's cookies, and versioned (`p4`), so a cookie from an older release never verifies. The one exception is `p3`, the version before the kind: a valid one still passes, read as stale, so the next request asks the store and re-issues it as `p4`, and nobody is signed out by the upgrade. It lasts to the access end, at most 400 days, the longest a browser keeps one. For `CHECK_SECONDS` (5 minutes) after `checkedAt` any request passes on the signature. After that the next request, of any kind, asks the store: a current person passes with a fresh cookie whose expiry follows their current access end; a revoked, signed-out-everywhere or ended person gets 401 and the cookie cleared. The request's own headers never decide whether the store is asked, since the client chooses them. A store that fails answers 503 with `Retry-After`, and leaves the cookie, so an outage signs nobody out; the review panel reads `Retry-After` as try again, and a 503 without it as a site with no store. The API function answers the same way in JSON. The sign-in POST also refuses a store failure with 503, and a link is checked before it is used up, so a failure never burns one.
80
84
  - **The link page** sends `Referrer-Policy: same-origin`, so Continue's POST carries a real `Origin` (with `no-referrer` a browser sends `Origin: null`, trusted only beside `Sec-Fetch-Site`, which older Safari does not send). Every other gate response sends `no-referrer`.
85
+ - **Internal prototypes.** Everything built from `prototypes/<slug>/` (its README, code, CSS, fixtures, lazy chunks and images) lands under `/_p/<slug>/`, its entry at `/_p/<slug>/entry.js`, and Studio's list of every slug at `/_p/all.js`; the shared bundle in `/assets/` names no prototype's folder (`vite/registry.ts`, `vite/boundary.ts`, `vite/settle.ts`; the build fails if a file breaks that). The exception is the walkthroughs: their compiled text and every feature's name sit in `/assets/` and reach every signed-in person, so a walkthrough must not name or describe internal work until that is built. A built file is owned by where its content comes from, never by who reads it, and each source is recorded as the file is written (`vite/settle.ts`): a stylesheet's CSS modules, an asset's original files, a worker's output; a file with no record and no fixed name fails the build. Nothing a prototype owns is inlined by the size limit, and nothing under `prototypes/` is ever the hub's: a file directly there, or in a folder without a README, is refused (shared code belongs in `kit/`). Any import or `new URL` (`?inline` included) into a prototype its importer does not own is refused in dev and in a build. Every stylesheet is read for reaches inside Vite's postcss run (`vite/css-boundary.ts`), each reference followed as a path and through Vite's own resolvers (aliases and package paths included); Sass, Less and Stylus are refused in prototypes and the project's `kit/`, since their imports resolve inside the preprocessor; and every worker bundle refuses a module under `prototypes/` and resolves `@kit/*`. After the bundle is settled the build reads what it wrote (`vite/leaks.ts`): a file outside `/_p/<slug>/` that holds a whole file of `prototypes/<slug>/` (its bytes, a base64 or SVG data URI of it anywhere in the file, or, for a file the build read, its whole text as a string in a script; 40 bytes or more) fails the build, unless the reader's owner has a source with the same content. It is a backstop for whole-file inlining: no part of a file (a line, a rule) is looked for. Vite is pinned to 8.3 (`~8.3.5`) because the boundary leans on its internals; `vite/build.test.ts` is what to run on a Vite upgrade. A file a prototype owns lives in its folder; the hub's and the kit's live in `/assets/` and are never copied into a prototype's folder; the same bytes from several owners become one copy per owner, each named from its owner's source. A file that reads what another prototype owns, or a hub or kit file that reads what a prototype owns, fails the build, naming both. A prototype that reaches into another (an import, a CSS `@import` or `url()`, a `new URL`) or starts a web worker fails the build. A Client asking for a prototype's page (`/<slug>/`) or anything under `/_p/<slug>/` gets 404 unless that prototype is client-facing, asked of the store on every such request; `/_p/all.js` is always 404 to a Client, and an internal prototype and one that does not exist answer byte for byte the same. A path that could mean more than one file (a `.` or `..` segment, a backslash, an empty segment, a `%` left after decoding, or one that does not decode) gets the same 404, as does any first segment that is not `/`, the hub's own (`assets`, `api`, `guide`, `_gate`, `index.html`, `favicon.svg`), `_p` or a prototype slug. A Client's comments on a prototype that is not client-facing answer as if it had none. Studio passes on the cookie's kind with no store read. `/`, `/assets/*`, `/guide/*` and `/api/*` pass as before. `guide`, `api` and `assets` are never a prototype's slug (`core/prototype.ts`).
81
86
  - **Signed out**, a page gets the sign-in page (401). It has no form: it says to open the link the studio sent, that each link signs in one device and then stops working, and to ask the studio for a new one for another device. Anything else gets a plain-text 401, an anonymous `POST` included.
82
87
 
83
88
  The middleware reads one environment variable, set in the Vercel project for Production and Preview and never committed (`.env.example` names it): `GATE_SECRET`, at least 32 random characters that sign the session cookie. With it missing the gate answers 503 on every path, so a misconfigured deploy never serves the prototypes open. People and links live in the review store, so a site without it has a gate nobody can pass. The gate pages ship a hash-based Content Security Policy with no `unsafe-inline` and no script, plus `font-src 'self'` and `img-src 'self'`, and send no referrer. They wear the hub's neutral look in Geist, so two files pass the gate without a session: `/_gate/geist.woff2` (the latin subset, emitted by `vite/plugin.ts` at that fixed path) and `/favicon.svg`. Nothing else does. Every response carries `X-Robots-Tag: noindex`, so no search engine lists the site. The pages' title is the `siteName` the project's `proxy.ts` passes to `createProxy`. Under `design-hub dev` there is no gate; `/_gate/` previews the sign-in page, `?page=link` a link's page and `?page=used` a used one.
@@ -0,0 +1,83 @@
1
+ import assert from 'node:assert/strict';
2
+ import { test } from 'node:test';
3
+ import { ALL_FILE, entryFile, isPrototypeSlug, probeEntry, prototypeOfPath, RESERVED } from './prototype.ts';
4
+
5
+ test('a prototype slug is kebab-case and never one of the hub’s own paths', () => {
6
+ assert.deepEqual([...RESERVED], ['guide', 'api', 'assets']);
7
+ for (const reserved of RESERVED) assert.equal(isPrototypeSlug(reserved), false);
8
+ assert.equal(isPrototypeSlug('sample-list'), true);
9
+ for (const bad of ['_p', 'Sample', 'a_b', '', 'a.js', 'a/b', null, 3])
10
+ assert.equal(isPrototypeSlug(bad), false);
11
+ assert.equal(entryFile('sample-list'), '_p/sample-list/entry.js');
12
+ assert.equal(ALL_FILE, '_p/all.js');
13
+ });
14
+
15
+ test('a path names its prototype, or none for the hub’s own', () => {
16
+ const cases: [string, string | null][] = [
17
+ ['/', null],
18
+ ['/assets/index-abc.js', null],
19
+ ['/guide/sample/', null],
20
+ ['/api/review', null],
21
+ ['/favicon.svg', null],
22
+ ['/_gate/geist.woff2', null],
23
+ ['/index.html', null],
24
+ ['/robots.txt', ''],
25
+ ['/invite/short', 'invite'],
26
+ ['/Sample-List/', ''],
27
+ ['/_p;x/secret/entry.js', ''],
28
+ ['/_p./secret/entry.js', ''],
29
+ ['/_p%20/secret/entry.js', ''],
30
+ ['/_p%00/secret/entry.js', ''],
31
+ ['/%EF%BC%BFp/secret/entry.js', ''],
32
+ ['/_p/secret/entry.js', ''],
33
+ ['/assets;x/y.js', ''],
34
+ ['/sample-list/', 'sample-list'],
35
+ ['/sample-list', 'sample-list'],
36
+ ['/sample-list/deep/path', 'sample-list'],
37
+ ['/_p/sample-list/entry.js', 'sample-list'],
38
+ ['/_p/sample-list', 'sample-list'],
39
+ ['/_p/all.js', 'all.js'],
40
+ ['/_p/', ''],
41
+ ['/_p', ''],
42
+ ['//_p//sample-list/x.js', ''],
43
+ ['/assets/..%2f_p/secret/entry.js', ''],
44
+ ['/api/..%2f_p/secret/entry.js', ''],
45
+ ['/_p/open/..%2fsecret/entry.js', ''],
46
+ ['/_p/open/.%2fentry.js', ''],
47
+ ['/assets//x.js', ''],
48
+ ['/_P/secret/entry.js', ''],
49
+ ['/_P/all.js', ''],
50
+ ['/%255Fp/secret/entry.js', ''],
51
+ ['/_p%5csecret%5centry.js', ''],
52
+ ['/assets%5cx.js', ''],
53
+ ['/assets/a%20b.png', null],
54
+ ['/assets/caf%C3%A9.png', null],
55
+ ['/_p/secret/caf%C3%A9%20x.png', 'secret'],
56
+ ['/guide/', null],
57
+ ['/%5Fp/sample-list/entry.js', 'sample-list'],
58
+ ['/_p/sample%2Dlist/entry.js', 'sample-list'],
59
+ ['/_p%2Fsample-list%2Fentry.js', 'sample-list'],
60
+ ['/%73ample-list/', 'sample-list'],
61
+ ['/%E0%A4%A/', ''],
62
+ ];
63
+ for (const [path, owner] of cases) assert.equal(prototypeOfPath(path), owner, path);
64
+ });
65
+
66
+ test('an entry is there on a JavaScript 200, not there on a 404 or the host’s page, and an error otherwise', async () => {
67
+ const asked: [string, RequestInit | undefined][] = [];
68
+ const answer = (status: number, type = 'text/javascript') =>
69
+ (async (url: string, init?: RequestInit) => {
70
+ asked.push([url, init]);
71
+ return new Response(null, { status, headers: { 'content-type': type } });
72
+ }) as unknown as typeof fetch;
73
+ assert.equal(await probeEntry('/_p/a/entry.js', answer(200)), true);
74
+ assert.equal(
75
+ await probeEntry('/_p/a/entry.js', answer(200, 'application/javascript; charset=utf-8')),
76
+ true,
77
+ );
78
+ assert.equal(await probeEntry('/_p/a/entry.js', answer(404)), false);
79
+ assert.equal(await probeEntry('/_p/a/entry.js', answer(200, 'text/html; charset=utf-8')), false);
80
+ for (const status of [401, 403, 500, 503])
81
+ await assert.rejects(probeEntry('/_p/a/entry.js', answer(status)), new RegExp(`answered ${status}`));
82
+ assert.deepEqual(asked[0], ['/_p/a/entry.js', { method: 'HEAD', credentials: 'same-origin' }]);
83
+ });
@@ -0,0 +1,84 @@
1
+ // What a prototype's slug may be, and where the files built from it live.
2
+ // One rule for the registry's scan, `design-hub new` and the gate, so a
3
+ // folder the hub lists is always a path the gate knows how to refuse.
4
+ import { SLUG } from './feature.ts';
5
+
6
+ /**
7
+ * First path segments the hub owns, never a prototype: the walkthroughs,
8
+ * the review API, and the shared bundle.
9
+ */
10
+ export const RESERVED = ['guide', 'api', 'assets'] as const;
11
+
12
+ /**
13
+ * Everything built from `prototypes/<slug>/` lands under `/_p/<slug>/`, and
14
+ * Studio's list of every slug at `/_p/all.js`. `_p` can never be a slug: SLUG
15
+ * has no underscore.
16
+ */
17
+ export const PROTOTYPE_DIR = '_p';
18
+ export const ALL_FILE = `${PROTOTYPE_DIR}/all.js`;
19
+ export const entryFile = (slug: string) => `${PROTOTYPE_DIR}/${slug}/entry.js`;
20
+
21
+ /** Whether `name` can be a prototype's folder: kebab-case and not one of the hub's own paths. */
22
+ export const isPrototypeSlug = (name: unknown): name is string =>
23
+ typeof name === 'string' && SLUG.test(name) && !(RESERVED as readonly string[]).includes(name);
24
+
25
+ /**
26
+ * A path's segments as a file server might read them, or null when the path
27
+ * could mean more than one file: it does not decode, still holds a `%` after
28
+ * decoding (`%255F`), holds a backslash, a `.` or `..` segment, or an empty
29
+ * segment other than the last. The gate refuses those to a Client rather than
30
+ * guess how the server resolves them. An encoded space or letter decodes and passes.
31
+ */
32
+ function segments(pathname: string): string[] | null {
33
+ let decoded: string;
34
+ try {
35
+ decoded = decodeURIComponent(pathname);
36
+ } catch {
37
+ return null;
38
+ }
39
+ if (/[%\\]/.test(decoded)) return null;
40
+ const parts = decoded.split('/').slice(1);
41
+ if (parts.at(-1) === '') parts.pop();
42
+ return parts.some((p) => p === '' || p === '.' || p === '..') ? null : parts;
43
+ }
44
+
45
+ /**
46
+ * The first path segments that are the hub's own, for anyone signed in: the
47
+ * reserved routes, the gate's font folder, and the files the hub serves at
48
+ * the top (shell/index.html, shell/public/favicon.svg).
49
+ */
50
+ const HUB_ROOT: readonly string[] = [...RESERVED, '_gate', 'index.html', 'favicon.svg'];
51
+
52
+ /**
53
+ * Which prototype a request path belongs to, for the gate: the name a
54
+ * prototype path carries, or null for a hub path (`/`, or a first segment in
55
+ * HUB_ROOT). The first segment, decoded, must be one of those, `_p`, or a
56
+ * prototype slug; anything else (`_P`, `_p;x`, `_p.`, a full-width `_p`)
57
+ * belongs to `''`, refused like an internal prototype. A path under `/_p/`
58
+ * always belongs to one, so its name may be no slug at all (`all.js`), which
59
+ * no audience makes client-facing. A path that could mean more than one file
60
+ * belongs to `''` too.
61
+ */
62
+ export function prototypeOfPath(pathname: string): string | null {
63
+ const parts = segments(pathname);
64
+ if (!parts) return '';
65
+ const [first, second] = parts;
66
+ if (first === undefined || HUB_ROOT.includes(first)) return null;
67
+ if (first === PROTOTYPE_DIR) return second ?? '';
68
+ return isPrototypeSlug(first) ? first : '';
69
+ }
70
+
71
+ /**
72
+ * Whether a built prototype's entry is there for this person, asked with a
73
+ * HEAD before it is imported. Not there: a 404 (the gate's answer for a
74
+ * prototype this person may not open, or none at all), or a 200 that is not
75
+ * JavaScript (the host's page for an entry that was never built). Any other
76
+ * answer (401, 500, 503) is an error, never "not there", so an outage never
77
+ * reads as nothing shared.
78
+ */
79
+ export async function probeEntry(path: string, fetcher: typeof fetch): Promise<boolean> {
80
+ const head = await fetcher(path, { method: 'HEAD', credentials: 'same-origin' });
81
+ if (head.status === 404) return false;
82
+ if (head.status !== 200) throw new Error(`${path} answered ${head.status}.`);
83
+ return /javascript/.test(head.headers.get('content-type') ?? '');
84
+ }
@@ -119,12 +119,23 @@ export type Comment = {
119
119
  /** The thread's audience. Set on the root when it is made and copied onto every reply; never changed. */
120
120
  audience: Audience;
121
121
  /**
122
- * The thread's number on its prototype, from 1, copied onto every reply. Never reused, so a
123
- * deleted or hidden thread moves no other number. 0 for a thread stored before numbers existed.
122
+ * The thread's number on its prototype and audience, from 1, copied onto every reply.
123
+ * Internal and client-facing threads count apart, so a Client's numbers run 1, 2, 3 with no
124
+ * gap where an internal thread sits; `threadLabel` tells the two apart. Never reused, so a
125
+ * deleted thread moves no other number. 0 for a thread stored before numbers existed.
124
126
  */
125
127
  number: number;
126
128
  };
127
129
 
130
+ /**
131
+ * How a thread is named in words, for a screen reader and an agent: `I2` for internal thread 2,
132
+ * `2` for client-facing thread 2, '' for a thread stored before numbers. The pin, the card
133
+ * and `comments pull` use it, so "fix I2" names one thread. The pin and the card's badge show
134
+ * the bare number; their amber says internal.
135
+ */
136
+ export const threadLabel = (c: Pick<Comment, 'audience' | 'number'>): string =>
137
+ !c.number ? '' : c.audience === 'internal' ? `I${c.number}` : String(c.number);
138
+
128
139
  /**
129
140
  * A stored comment as the rules read it. A record with no audience, or one
130
141
  * that is not a known value, is internal: a missing field never shows a
@@ -223,6 +234,13 @@ export function checkAudience(input: unknown): Checked<Audience | null> {
223
234
  : { ok: false, problems: [`audience: one of ${AUDIENCES.join(', ')}`] };
224
235
  }
225
236
 
237
+ /** A prototype's audience as Studio sets it: one of AUDIENCES, required. */
238
+ export function checkPrototypeAudience(input: unknown): Checked<Audience> {
239
+ return AUDIENCES.includes(input as Audience)
240
+ ? { ok: true, value: input as Audience }
241
+ : { ok: false, problems: [`audience: one of ${AUDIENCES.join(', ')}`] };
242
+ }
243
+
226
244
  /** Whose view of the comments is asked for: a person kind, or null for the caller's own. */
227
245
  export function checkViewAs(input: unknown): Checked<PersonKind | null> {
228
246
  if (input === undefined || input === null) return { ok: true, value: null };
@@ -48,6 +48,8 @@ const TABLE: [Action, Audience, boolean, boolean, boolean, boolean][] = [
48
48
  ['triage', 'internal', true, true, false, false],
49
49
  ['people', 'client', true, true, false, false],
50
50
  ['people', 'internal', true, true, false, false],
51
+ ['audience', 'client', true, true, false, false],
52
+ ['audience', 'internal', true, true, false, false],
51
53
  ];
52
54
 
53
55
  const studio = person('s', 'studio');
@@ -72,12 +74,12 @@ for (const [action, audience, studioOwn, studioOther, clientOwn, clientOther] of
72
74
  });
73
75
  }
74
76
 
75
- test('with no thread, both kinds read and start one; only Studio triages and manages people', () => {
77
+ test('with no thread, both kinds read and start one; only Studio triages, manages people and sets a prototype’s audience', () => {
76
78
  for (const action of ['read', 'comment'] as const) {
77
79
  assert.equal(can(studio, action), true);
78
80
  assert.equal(can(client, action), true);
79
81
  }
80
- for (const action of ['triage', 'people'] as const) {
82
+ for (const action of ['triage', 'people', 'audience'] as const) {
81
83
  assert.equal(can(studio, action), true);
82
84
  assert.equal(can(client, action), false);
83
85
  }
@@ -1,5 +1,6 @@
1
1
  // Who may do what. Studio runs the review: it adds and revokes people,
2
- // deletes any comment and corrects triage. A Client comments, replies, edits
2
+ // deletes any comment, corrects triage and sets which prototypes are
3
+ // client-facing. A Client comments, replies, edits
3
4
  // and deletes what they wrote, and resolves or reopens any client-facing
4
5
  // thread, because clients work alongside others in their own organisation.
5
6
  // An internal thread does not exist for a Client: every action on one is
@@ -7,7 +8,7 @@
7
8
  // nothing here.
8
9
  import type { Audience, Comment, Person, PersonKind } from './model.ts';
9
10
 
10
- export type Action = 'read' | 'comment' | 'edit' | 'delete' | 'resolve' | 'triage' | 'people';
11
+ export type Action = 'read' | 'comment' | 'edit' | 'delete' | 'resolve' | 'triage' | 'people' | 'audience';
11
12
 
12
13
  /** Only what the rules read, so the browser's signed-in person (no epoch) is checked by the same rules. */
13
14
  type Actor = Pick<Person, 'id' | 'kind' | 'revokedAt'>;
@@ -36,6 +37,7 @@ export function can(actor: Actor | null, action: Action, root?: Comment, subject
36
37
  return own || studio;
37
38
  case 'triage':
38
39
  case 'people':
40
+ case 'audience':
39
41
  return studio;
40
42
  }
41
43
  }
@@ -1,6 +1,6 @@
1
1
  import assert from 'node:assert/strict';
2
2
  import { beforeEach, test } from 'node:test';
3
- import { type Anchor, accessEnd, type Person } from './model.ts';
3
+ import { type Anchor, accessEnd, type Comment, type Person, threadLabel } from './model.ts';
4
4
  import { createReview, type Review, ReviewError } from './service.ts';
5
5
  import { KEY, type KV, memoryKV, type Snapshot } from './store.ts';
6
6
 
@@ -47,6 +47,8 @@ beforeEach(async () => {
47
47
  const r = await review.addPerson(studio, { name: 'Rae', team: 'Acme' });
48
48
  client = r.person;
49
49
  clientToken = r.token;
50
+ // The prototype these tests comment on is client-facing, so a Client reaches its comments.
51
+ await review.setAudience(studio, anchor.prototype, 'client');
50
52
  });
51
53
 
52
54
  test('a link works once, and looking at it uses nothing up', async () => {
@@ -60,10 +62,8 @@ test('a link works once, and looking at it uses nothing up', async () => {
60
62
 
61
63
  test('two requests with one link at once sign in one device', async () => {
62
64
  const both = await Promise.all([review.useLink(clientToken), review.useLink(clientToken)]);
63
- assert.deepEqual(
64
- both.map((p) => p?.id ?? null),
65
- [client.id, null],
66
- );
65
+ // Either request may win the claim; exactly one does.
66
+ assert.deepEqual(both.map((p) => p?.id ?? null).sort(), [client.id, null].sort());
67
67
  });
68
68
 
69
69
  test('a new link is for another device: sessions and other links stay', async () => {
@@ -555,6 +555,7 @@ test('triage runs on add, and a failing triager never loses the comment', async
555
555
  return { kind: 'bug', state: states[0] ?? null, by: 'jev', confidence: 0.9 };
556
556
  },
557
557
  });
558
+ await triaged.setAudience(studio, anchor.prototype, 'client');
558
559
  const c = await triaged.add(client, {
559
560
  body: 'Broken',
560
561
  anchor,
@@ -563,6 +564,7 @@ test('triage runs on add, and a failing triager never loses the comment', async
563
564
  assert.deepEqual(seen, [['Empty', 'Real list']]);
564
565
  assert.equal(c.triage?.kind, 'bug');
565
566
  const failing = createReview(memoryKV(), { triage: async () => Promise.reject(new Error('down')) });
567
+ await failing.setAudience(studio, anchor.prototype, 'client');
566
568
  assert.equal((await failing.add(client, { body: 'Still saved', anchor })).triage, null);
567
569
  });
568
570
 
@@ -678,29 +680,74 @@ test('a Client still works on client-facing threads, Studio’s replies included
678
680
  assert.deepEqual(await review.remove(client, { ...at, id: t.clientReply.id }), [t.clientReply.id]);
679
681
  });
680
682
 
681
- test('numbers are fixed: a delete or a hidden thread moves no other number, and none is reused', async () => {
683
+ test('numbers are fixed: internal and client-facing threads count apart, and none moves or is reused', async () => {
682
684
  const t = await twoThreads();
683
685
  const third = await review.add(client, { body: 'Third', anchor });
684
- assert.deepEqual([t.internal.number, t.shared.number, third.number], [1, 2, 3]);
686
+ const ours = await review.add(studio, { body: 'Ours too', anchor });
687
+ assert.deepEqual(
688
+ [t.internal, t.shared, third, ours].map((c) => [c.audience, c.number]),
689
+ [
690
+ ['internal', 1],
691
+ ['client', 1],
692
+ ['client', 2],
693
+ ['internal', 2],
694
+ ],
695
+ );
696
+ assert.deepEqual([t.internal, t.shared, third, ours].map(threadLabel), ['I1', '1', '2', 'I2']);
685
697
  // Replies carry their thread's number.
686
- assert.deepEqual([t.internalReply.number, t.studioReply.number], [1, 2]);
687
- // A Client sees 2 and 3: the internal thread is hidden and leaves a gap.
688
- const roots = (cs: { id: string; thread: string; number: number }[]) =>
689
- cs.filter((c) => c.id === c.thread).map((c) => c.number);
690
- assert.deepEqual(roots(await review.listComments(client, 'sample-list')), [2, 3]);
698
+ assert.deepEqual([t.internalReply.number, t.studioReply.number], [1, 1]);
699
+ // A Client sees 1 and 2: no gap where an internal thread sits.
700
+ const roots = (cs: Comment[]) => cs.filter((c) => c.id === c.thread).map(threadLabel);
701
+ assert.deepEqual(roots(await review.listComments(client, 'sample-list')), ['1', '2']);
691
702
  await review.remove(studio, { prototype: 'sample-list', id: t.shared.id });
692
- assert.deepEqual(roots(await review.listComments(studio, 'sample-list')), [1, 3]);
693
- assert.deepEqual(roots(await review.listComments(client, 'sample-list')), [3]);
694
- assert.equal((await review.add(client, { body: 'Fourth', anchor })).number, 4);
703
+ assert.deepEqual(roots(await review.listComments(studio, 'sample-list')), ['I1', '2', 'I2']);
704
+ assert.deepEqual(roots(await review.listComments(client, 'sample-list')), ['2']);
705
+ assert.equal((await review.add(client, { body: 'Fourth', anchor })).number, 3);
695
706
  });
696
707
 
697
708
  test('numbers count per prototype', async () => {
709
+ await review.setAudience(studio, 'other', 'client');
698
710
  const a = await review.add(client, { body: 'A1', anchor });
699
711
  const b = await review.add(client, { body: 'B1', anchor: { ...anchor, prototype: 'other' } });
700
- const a2 = await review.add(studio, { body: 'A2', anchor });
712
+ const a2 = await review.add(studio, { body: 'A2', anchor, audience: 'client' });
701
713
  assert.deepEqual([a.number, b.number, a2.number], [1, 1, 2]);
702
714
  });
703
715
 
716
+ test('the internal count starts past internal threads numbered while the two shared one count', async () => {
717
+ const kv = memoryKV();
718
+ const r = createReview(kv);
719
+ const root = { ...studio, id: 'cli' };
720
+ // Under one shared count: internal 1, client-facing 2, internal 3.
721
+ const shared = [
722
+ { id: 'a', audience: 'internal', number: 1 },
723
+ { id: 'b', audience: 'client', number: 2 },
724
+ { id: 'c', audience: 'internal', number: 3 },
725
+ ];
726
+ await kv.sadd(KEY.prototypes, 'sample-list');
727
+ await kv.hset(KEY.counters, 'sample-list', '3');
728
+ for (const c of shared)
729
+ await kv.hset(
730
+ KEY.comments('sample-list'),
731
+ c.id,
732
+ JSON.stringify({
733
+ ...c,
734
+ thread: c.id,
735
+ author: { id: 'cli', name: 'Ed', team: 'Studio' },
736
+ body: 'Before',
737
+ createdAt: '2030-01-01T00:00:00Z',
738
+ editedAt: null,
739
+ anchor,
740
+ status: 'open',
741
+ resolvedBy: null,
742
+ triage: null,
743
+ }),
744
+ );
745
+ const next = await r.add(root, { body: 'After', anchor });
746
+ assert.deepEqual([next.audience, next.number], ['internal', 4]);
747
+ assert.equal((await r.add(root, { body: 'Again', anchor })).number, 5);
748
+ assert.equal((await r.add(root, { body: 'For them', anchor, audience: 'client' })).number, 4);
749
+ });
750
+
704
751
  test('a stored comment without an audience is internal, and one without a number has none', async () => {
705
752
  const kv = memoryKV();
706
753
  const r = createReview(kv);
@@ -737,3 +784,140 @@ test('a stored comment without an audience is internal, and one without a number
737
784
  assert.equal(await r.locate(rae, 'old'), null);
738
785
  await rejects(r.edit(rae, { prototype: 'sample-list', id: 'old', body: 'x' }), 'not_found');
739
786
  });
787
+
788
+ test('a prototype is internal until Studio marks it client-facing, and internal again when unmarked', async () => {
789
+ assert.equal(await review.audienceOf('secret-plan'), 'internal');
790
+ assert.equal(await review.setAudience(studio, 'secret-plan', 'client'), 'client');
791
+ assert.equal(await review.audienceOf('secret-plan'), 'client');
792
+ assert.equal(await review.audienceOf('sample-page'), 'internal');
793
+ assert.equal(await review.setAudience(studio, 'secret-plan', 'internal'), 'internal');
794
+ assert.equal(await review.audienceOf('secret-plan'), 'internal');
795
+ // Marking internal twice, or one never marked, is no error.
796
+ assert.equal(await review.setAudience(studio, 'sample-page', 'internal'), 'internal');
797
+ });
798
+
799
+ test('only client-facing is stored: internal deletes the field, and absent or garbage reads as internal', async () => {
800
+ const kv = memoryKV();
801
+ const own = createReview(kv);
802
+ await own.setAudience(studio, 'secret-plan', 'client');
803
+ assert.deepEqual(await kv.hgetall(KEY.audiences), { 'secret-plan': 'client' });
804
+ await own.setAudience(studio, 'secret-plan', 'internal');
805
+ assert.deepEqual(await kv.hgetall(KEY.audiences), {});
806
+ for (const garbage of ['Client', 'internal', '', '"client"', 'true', ' client']) {
807
+ await kv.hset(KEY.audiences, 'secret-plan', garbage);
808
+ assert.equal(await own.audienceOf('secret-plan'), 'internal', garbage);
809
+ }
810
+ await kv.hset(KEY.audiences, 'sample-page', 'yes');
811
+ await kv.hset(KEY.audiences, 'guide', 'client');
812
+ await kv.hset(KEY.audiences, 'Not_A_Slug', 'client');
813
+ await kv.hset(KEY.audiences, 'sample-social', 'client');
814
+ assert.deepEqual(await own.visiblePrototypes(studio), { view: 'studio', clientFacing: ['sample-social'] });
815
+ // A name that can never be a prototype is internal without a store read.
816
+ assert.equal(await own.audienceOf('guide'), 'internal');
817
+ assert.equal(await own.audienceOf('all.js'), 'internal');
818
+ });
819
+
820
+ test('only Studio sets an audience: a Client is forbidden, a signed-out caller unauthorized, whatever the input', async () => {
821
+ await rejects(review.setAudience(client, 'secret-plan', 'client'), 'forbidden');
822
+ await rejects(review.setAudience(client, 'nope!', 'garbage'), 'forbidden');
823
+ await rejects(review.setAudience(null, 'secret-plan', 'client'), 'unauthorized');
824
+ const revoked = await review.revoke(studio, client.id);
825
+ await rejects(review.setAudience({ ...revoked, kind: 'studio' }, 'secret-plan', 'client'), 'forbidden');
826
+ assert.equal(await review.audienceOf('secret-plan'), 'internal');
827
+ });
828
+
829
+ test('a prototype’s audience is checked: the slug and the value, every problem named', async () => {
830
+ await assert.rejects(
831
+ review.setAudience(studio, 'Bad Slug', 'everyone'),
832
+ (e: unknown) =>
833
+ e instanceof ReviewError &&
834
+ e.code === 'invalid' &&
835
+ e.problems.join('|') === 'prototype: a prototype slug|audience: one of internal, client',
836
+ );
837
+ for (const reserved of ['guide', 'api', 'assets'])
838
+ await rejects(review.setAudience(studio, reserved, 'client'), 'invalid');
839
+ await rejects(review.setAudience(studio, 'sample-list', null), 'invalid');
840
+ await rejects(review.setAudience(studio, 'sample-list', undefined), 'invalid');
841
+ });
842
+
843
+ test('the index read: Studio’s view, Client view, and a Client’s, each with the client-facing slugs', async () => {
844
+ await review.setAudience(studio, 'sample-page', 'client');
845
+ await review.setAudience(studio, 'sample-list', 'client');
846
+ const facing = ['sample-list', 'sample-page'];
847
+ assert.deepEqual(await review.visiblePrototypes(studio), { view: 'studio', clientFacing: facing });
848
+ assert.deepEqual(await review.visiblePrototypes(studio, 'studio'), {
849
+ view: 'studio',
850
+ clientFacing: facing,
851
+ });
852
+ assert.deepEqual(await review.visiblePrototypes(studio, 'client'), {
853
+ view: 'client',
854
+ clientFacing: facing,
855
+ });
856
+ // A Client asking for Studio's view still gets a Client's.
857
+ assert.deepEqual(await review.visiblePrototypes(client), { view: 'client', clientFacing: facing });
858
+ assert.deepEqual(await review.visiblePrototypes(client, 'studio'), {
859
+ view: 'client',
860
+ clientFacing: facing,
861
+ });
862
+ await rejects(review.visiblePrototypes(studio, 'everyone'), 'invalid');
863
+ await rejects(review.visiblePrototypes(null), 'unauthorized');
864
+ await rejects(review.visiblePrototypes(null, 'client'), 'unauthorized');
865
+ });
866
+
867
+ /** A client-facing thread with a Client's reply on it, then the prototype switched back to internal. */
868
+ async function onInternalPrototype() {
869
+ const root = await review.add(studio, { body: 'For the client', anchor, audience: 'client' });
870
+ const reply = await review.reply(client, { prototype: anchor.prototype, thread: root.id, body: 'Seen' });
871
+ await review.setAudience(studio, anchor.prototype, 'internal');
872
+ return { root, reply };
873
+ }
874
+
875
+ test('a Client’s list of an internal prototype is empty, as if it had no comments, and so is Studio’s Client view', async () => {
876
+ await onInternalPrototype();
877
+ assert.deepEqual(await review.listComments(client, anchor.prototype), []);
878
+ assert.deepEqual(await review.listComments(client, anchor.prototype, 'studio'), []);
879
+ assert.deepEqual(await review.listComments(studio, anchor.prototype, 'client'), []);
880
+ // The same answer as a prototype nobody made.
881
+ assert.deepEqual(await review.listComments(client, 'no-such-thing'), []);
882
+ assert.equal((await review.listComments(studio, anchor.prototype)).length, 2);
883
+ assert.deepEqual(await review.allComments(client), []);
884
+ assert.equal((await review.allComments(studio)).length, 2);
885
+ // Client-facing again: the thread is back for them, with its reply.
886
+ await review.setAudience(studio, anchor.prototype, 'client');
887
+ assert.equal((await review.listComments(client, anchor.prototype)).length, 2);
888
+ });
889
+
890
+ test('a Client acting on a client-facing thread of an internal prototype is told it does not exist, by every op', async () => {
891
+ const { root, reply } = await onInternalPrototype();
892
+ const at = { prototype: anchor.prototype };
893
+ for (const id of [root.id, reply.id]) {
894
+ await rejects(review.reply(client, { ...at, thread: id, body: 'x' }), 'not_found');
895
+ await rejects(review.edit(client, { ...at, id, body: 'x' }), 'not_found');
896
+ await rejects(review.remove(client, { ...at, id }), 'not_found');
897
+ await rejects(review.resolve(client, { ...at, id, resolved: true }), 'not_found');
898
+ await rejects(review.resolve(client, { ...at, id, resolved: false }), 'not_found');
899
+ await rejects(review.retriage(client, { ...at, id, triage: { kind: 'bug' } }), 'forbidden');
900
+ assert.equal(await review.locate(client, id), null);
901
+ assert.ok(await review.locate(studio, id));
902
+ }
903
+ // The same answers as an id, and a prototype, that are not there at all.
904
+ await rejects(review.edit(client, { ...at, id: 'nope', body: 'x' }), 'not_found');
905
+ await rejects(review.edit(client, { prototype: 'no-such-thing', id: 'nope', body: 'x' }), 'not_found');
906
+ // A new thread there is refused the same way, and nothing is written or counted.
907
+ await rejects(review.add(client, { body: 'Hello?', anchor }), 'not_found');
908
+ await rejects(
909
+ review.add(client, { body: 'Hello?', anchor: { ...anchor, prototype: 'no-such-thing' } }),
910
+ 'not_found',
911
+ );
912
+ const after = await review.listComments(studio, anchor.prototype);
913
+ assert.deepEqual(
914
+ after.map((c) => [c.body, c.status]),
915
+ [
916
+ ['For the client', 'open'],
917
+ ['Seen', 'open'],
918
+ ],
919
+ );
920
+ // Studio, writing as Studio from Client view, still works there.
921
+ assert.ok(await review.add(studio, { body: 'Internal note', anchor }));
922
+ assert.ok(await review.reply(studio, { ...at, thread: root.id, body: 'Studio reply' }));
923
+ });