@milesroxas/design-hub 0.9.0 → 0.11.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 (150) hide show
  1. package/README.md +13 -11
  2. package/core/controls.test.ts +176 -0
  3. package/core/controls.ts +195 -0
  4. package/core/files.test.ts +76 -0
  5. package/core/files.ts +131 -0
  6. package/core/prototype.test.ts +124 -7
  7. package/core/prototype.ts +133 -24
  8. package/core/review/model.ts +144 -2
  9. package/core/review/policy.test.ts +79 -22
  10. package/core/review/policy.ts +36 -8
  11. package/core/review/service.test.ts +1525 -322
  12. package/core/review/service.ts +810 -183
  13. package/core/review/store.test.ts +91 -0
  14. package/core/review/store.ts +143 -26
  15. package/dist/core/controls.d.ts +55 -0
  16. package/dist/core/controls.js +174 -0
  17. package/dist/core/files.d.ts +39 -0
  18. package/dist/core/files.js +107 -0
  19. package/dist/core/prototype.d.ts +61 -12
  20. package/dist/core/prototype.js +105 -26
  21. package/dist/core/review/model.d.ts +87 -2
  22. package/dist/core/review/model.js +97 -1
  23. package/dist/core/review/policy.d.ts +11 -4
  24. package/dist/core/review/policy.js +14 -2
  25. package/dist/core/review/service.d.ts +222 -43
  26. package/dist/core/review/service.js +727 -182
  27. package/dist/core/review/store.d.ts +84 -24
  28. package/dist/core/review/store.js +66 -26
  29. package/dist/scripts/bootstrap.d.ts +4 -34
  30. package/dist/scripts/bootstrap.js +9 -244
  31. package/dist/scripts/cli.js +6 -0
  32. package/dist/scripts/client.d.ts +45 -0
  33. package/dist/scripts/client.js +320 -0
  34. package/dist/scripts/commands.js +6 -0
  35. package/dist/scripts/comments.d.ts +8 -26
  36. package/dist/scripts/comments.js +27 -14
  37. package/dist/scripts/guard.d.ts +11 -0
  38. package/dist/scripts/guard.js +44 -0
  39. package/dist/scripts/lib/builds.d.ts +40 -0
  40. package/dist/scripts/lib/builds.js +198 -0
  41. package/dist/scripts/lib/cli.js +3 -1
  42. package/dist/scripts/lib/deploy.d.ts +6 -90
  43. package/dist/scripts/lib/deploy.js +24 -137
  44. package/dist/scripts/lib/dns.d.ts +49 -0
  45. package/dist/scripts/lib/dns.js +141 -0
  46. package/dist/scripts/lib/fake-host.d.ts +168 -0
  47. package/dist/scripts/lib/fake-host.js +244 -0
  48. package/dist/scripts/lib/host.d.ts +87 -0
  49. package/dist/scripts/lib/host.js +362 -0
  50. package/dist/scripts/lib/linked.d.ts +51 -0
  51. package/dist/scripts/lib/linked.js +124 -0
  52. package/dist/scripts/lib/names.d.ts +35 -0
  53. package/dist/scripts/lib/names.js +77 -0
  54. package/dist/scripts/lib/review.d.ts +23 -2
  55. package/dist/scripts/lib/review.js +32 -15
  56. package/dist/scripts/lib/rules.d.ts +1 -0
  57. package/dist/scripts/lib/rules.js +1 -0
  58. package/dist/scripts/lib/studio-deps.d.ts +35 -0
  59. package/dist/scripts/lib/studio-deps.js +79 -0
  60. package/dist/scripts/lib/studios.d.ts +70 -0
  61. package/dist/scripts/lib/studios.js +187 -0
  62. package/dist/scripts/lib/update.d.ts +33 -0
  63. package/dist/scripts/lib/update.js +40 -0
  64. package/dist/scripts/lib/vercel.d.ts +1 -23
  65. package/dist/scripts/lib/vercel.js +6 -81
  66. package/dist/scripts/people.d.ts +7 -11
  67. package/dist/scripts/people.js +51 -46
  68. package/dist/scripts/preflight.d.ts +8 -1
  69. package/dist/scripts/preflight.js +36 -19
  70. package/dist/scripts/project.d.ts +86 -0
  71. package/dist/scripts/project.js +141 -0
  72. package/dist/scripts/share.d.ts +105 -30
  73. package/dist/scripts/share.js +82 -154
  74. package/dist/scripts/skills.d.ts +18 -2
  75. package/dist/scripts/skills.js +22 -3
  76. package/dist/scripts/studio.d.ts +75 -0
  77. package/dist/scripts/studio.js +401 -0
  78. package/dist/scripts/upgrade.d.ts +10 -2
  79. package/dist/scripts/upgrade.js +44 -14
  80. package/dist/server/api.d.ts +22 -11
  81. package/dist/server/api.js +125 -44
  82. package/dist/server/blob.d.ts +10 -0
  83. package/dist/server/blob.js +53 -0
  84. package/dist/server/checks.js +2 -2
  85. package/dist/server/dev.js +4 -4
  86. package/dist/server/env.d.ts +2 -0
  87. package/dist/server/env.js +9 -0
  88. package/dist/server/fake-upstash.js +52 -3
  89. package/dist/server/hosts.d.ts +11 -0
  90. package/dist/server/hosts.js +31 -0
  91. package/dist/server/local.d.ts +7 -1
  92. package/dist/server/local.js +10 -1
  93. package/dist/server/mark.d.ts +41 -0
  94. package/dist/server/mark.js +111 -0
  95. package/dist/server/session.d.ts +17 -9
  96. package/dist/server/session.js +22 -45
  97. package/dist/server/upstash.js +20 -0
  98. package/dist/vercel/files.d.ts +11 -0
  99. package/dist/vercel/files.js +68 -0
  100. package/dist/vercel/index.d.ts +4 -3
  101. package/dist/vercel/index.js +12 -8
  102. package/dist/vercel/proxy.d.ts +69 -4
  103. package/dist/vercel/proxy.js +171 -107
  104. package/dist/vite/plugin.d.ts +24 -1
  105. package/dist/vite/plugin.js +46 -2
  106. package/kit/Artboard.tsx +21 -8
  107. package/kit/Space.tsx +4 -3
  108. package/kit/Variants.tsx +193 -65
  109. package/kit/ViewTools.tsx +77 -11
  110. package/kit/audience.ts +85 -0
  111. package/kit/dials.css +59 -0
  112. package/kit/dials.tsx +272 -35
  113. package/kit/harness.css +34 -0
  114. package/kit/prefs.ts +23 -1
  115. package/package.json +3 -2
  116. package/shell/ClientViewNote.tsx +31 -3
  117. package/shell/Guide.tsx +11 -5
  118. package/shell/Index.tsx +32 -10
  119. package/shell/Notice.tsx +1 -1
  120. package/shell/controls.ts +26 -0
  121. package/shell/hub.ts +5 -1
  122. package/shell/main.tsx +33 -6
  123. package/shell/review/Review.tsx +2 -2
  124. package/shell/review/ThreadCard.tsx +5 -5
  125. package/shell/review/client.ts +28 -11
  126. package/shell/review/view.test.ts +19 -0
  127. package/shell/review/view.ts +25 -0
  128. package/shell/shell.css +8 -0
  129. package/shell/studio/ClientHub.tsx +98 -0
  130. package/shell/studio/hub.css +48 -0
  131. package/shell/studio/index.html +14 -0
  132. package/shell/studio/main.tsx +17 -0
  133. package/skills/miles-brand/SKILL.md +11 -1
  134. package/skills/miles-deploy/SKILL.md +121 -64
  135. package/skills/miles-design-hub/SKILL.md +11 -9
  136. package/skills/miles-prototype/SKILL.md +34 -1
  137. package/skills/miles-review/SKILL.md +5 -7
  138. package/skills/miles-worktrees/SKILL.md +3 -3
  139. package/templates/conductor/settings.toml +1 -1
  140. package/templates/studio/.env.example +9 -0
  141. package/templates/studio/.vercelignore +5 -0
  142. package/templates/studio/README.md +84 -0
  143. package/templates/studio/_gitignore +7 -0
  144. package/templates/studio/api/files.ts +4 -0
  145. package/templates/studio/api/review.ts +4 -0
  146. package/templates/studio/build.mjs +4 -0
  147. package/templates/studio/package.json +16 -0
  148. package/templates/studio/proxy.ts +4 -0
  149. package/templates/studio/studio.json +9 -0
  150. package/templates/studio/vercel.json +27 -0
@@ -1,7 +1,9 @@
1
1
  import { SLUG } from '../core/feature.js';
2
- import { createReview, ReviewError } from '../core/review/service.js';
2
+ import { hostName, isProjectSlug } from '../core/prototype.js';
3
+ import { createReview, NO_PROJECT, ReviewError } from '../core/review/service.js';
3
4
  import { jevTriager } from '../core/review/triage.js';
4
- import { PERSON_COOKIE, readCookie, readGate, readPersonToken, sameOrigin } from './session.js';
5
+ import { hostOf } from './hosts.js';
6
+ import { clearedCookie, PERSON_COOKIE, readCookie, readGate, readPersonToken, sameOrigin, } from './session.js';
5
7
  import { storeConfig, upstashKV } from './upstash.js';
6
8
  export const API_PATH = '/api/review';
7
9
  const MAX_BODY_BYTES = 64 * 1024;
@@ -25,22 +27,36 @@ function prototypeOf(v) {
25
27
  throw new ReviewError('invalid', 'Name the prototype.', ['prototype: a prototype slug']);
26
28
  return s;
27
29
  }
28
- async function query(op, params, { review, actor }) {
30
+ /** The scope of an op about prototypes and comments, which needs a project: without one, there is none to find. */
31
+ function projectScope(scope) {
32
+ if (!scope.project)
33
+ throw new ReviewError('not_found', NO_PROJECT);
34
+ return scope;
35
+ }
36
+ /** What a client's hub shows of a project: its slug, for the link, and its name. */
37
+ const listed = ({ slug, name }) => ({ slug, name });
38
+ async function query(op, params, { review, actor, scope }) {
29
39
  switch (op) {
30
40
  case 'me':
31
41
  return { person: actor ? visible(actor) : null };
32
42
  case 'comments':
33
43
  // viewAs=client is Studio's Client view; the service checks the value and never widens a Client's view.
34
44
  return {
35
- comments: await review.listComments(actor, prototypeOf(params.get('prototype')), params.get('viewAs') ?? undefined),
45
+ comments: await review.listComments(projectScope(scope), actor, prototypeOf(params.get('prototype')), params.get('viewAs') ?? undefined),
36
46
  };
37
47
  case 'prototypes':
38
48
  // The index's read: the view the caller gets and the client-facing slugs. viewAs is checked as comments checks it.
39
- return await review.visiblePrototypes(actor, params.get('viewAs') ?? undefined);
49
+ return await review.visiblePrototypes(projectScope(scope), actor, params.get('viewAs') ?? undefined);
50
+ case 'controls':
51
+ // A prototype page's read: the caller's view, and what Studio marked on its dials and variants.
52
+ return await review.controlsOf(projectScope(scope), actor, params.get('prototype'));
53
+ case 'projects':
54
+ // A client's hub: every project of the scope's client with a build to open.
55
+ return { projects: (await review.listProjects(scope, actor)).map(listed) };
40
56
  case 'people':
41
- return { people: (await review.listPeople(actor)).map(visible) };
57
+ return { people: (await review.listPeople(scope, actor)).map(visible) };
42
58
  case 'access':
43
- return { access: await review.defaultAccess(actor) };
59
+ return { access: await review.defaultAccess(scope, actor) };
44
60
  default:
45
61
  return undefined;
46
62
  }
@@ -50,31 +66,45 @@ const link = (r) => ({
50
66
  link: `/invite/${r.token}`,
51
67
  });
52
68
  /** Studio's commands over people, their links and how long they keep access. */
53
- async function peopleCommand(op, b, { review, actor }) {
69
+ async function peopleCommand(op, b, { review, actor, scope }) {
54
70
  switch (op) {
55
71
  case 'people.add':
56
- return link(await review.addPerson(actor, { name: b.name, team: b.team, kind: b.kind, access: b.access }));
72
+ return link(await review.addPerson(scope, actor, { name: b.name, team: b.team, kind: b.kind, access: b.access }));
57
73
  case 'people.link':
58
- return link(await review.newLink(actor, str(b.id)));
74
+ return link(await review.newLink(scope, actor, str(b.id)));
59
75
  case 'people.signOut':
60
- return link(await review.signOutEverywhere(actor, str(b.id)));
76
+ return link(await review.signOutEverywhere(scope, actor, str(b.id)));
61
77
  case 'people.revoke':
62
- return { person: visible(await review.revoke(actor, str(b.id))) };
78
+ return { person: visible(await review.revoke(scope, actor, str(b.id))) };
63
79
  case 'people.access':
64
- return { person: visible(await review.setAccess(actor, str(b.id), b.access)) };
80
+ return { person: visible(await review.setAccess(scope, actor, str(b.id), b.access)) };
65
81
  case 'access.set':
66
- return { access: await review.setDefaultAccess(actor, b.access) };
82
+ return { access: await review.setDefaultAccess(scope, actor, b.access) };
67
83
  default:
68
84
  return undefined;
69
85
  }
70
86
  }
87
+ /** The commands about a project's prototypes and comments; the rest are the client's people. */
88
+ const PROJECT_COMMANDS = [
89
+ 'comment.add',
90
+ 'comment.reply',
91
+ 'comment.edit',
92
+ 'comment.remove',
93
+ 'comment.resolve',
94
+ 'comment.triage',
95
+ 'prototype.audience',
96
+ 'control.audience',
97
+ ];
71
98
  async function command(op, b, ctx) {
99
+ if (!PROJECT_COMMANDS.includes(op))
100
+ return peopleCommand(op, b, ctx);
72
101
  const { review, actor } = ctx;
102
+ const scope = projectScope(ctx.scope);
73
103
  const at = () => ({ prototype: prototypeOf(b.prototype), id: str(b.id) });
74
104
  switch (op) {
75
105
  case 'comment.add':
76
106
  return {
77
- comment: await review.add(actor, {
107
+ comment: await review.add(scope, actor, {
78
108
  body: b.body,
79
109
  anchor: b.anchor,
80
110
  states: b.states,
@@ -83,27 +113,37 @@ async function command(op, b, ctx) {
83
113
  };
84
114
  case 'comment.reply':
85
115
  return {
86
- comment: await review.reply(actor, {
116
+ comment: await review.reply(scope, actor, {
87
117
  prototype: prototypeOf(b.prototype),
88
118
  thread: str(b.thread),
89
119
  body: b.body,
90
120
  }),
91
121
  };
92
122
  case 'comment.edit':
93
- return { comment: await review.edit(actor, { ...at(), body: b.body }) };
123
+ return { comment: await review.edit(scope, actor, { ...at(), body: b.body }) };
94
124
  case 'comment.remove':
95
- return { removed: await review.remove(actor, at()) };
125
+ return { removed: await review.remove(scope, actor, at()) };
96
126
  case 'comment.resolve':
97
- return { comment: await review.resolve(actor, { ...at(), resolved: b.resolved === true }) };
127
+ return { comment: await review.resolve(scope, actor, { ...at(), resolved: b.resolved === true }) };
98
128
  case 'comment.triage':
99
- return { comment: await review.retriage(actor, { ...at(), triage: b.triage, states: b.states }) };
129
+ return {
130
+ comment: await review.retriage(scope, actor, { ...at(), triage: b.triage, states: b.states }),
131
+ };
100
132
  case 'prototype.audience':
101
133
  return {
102
134
  prototype: b.prototype,
103
- audience: await review.setAudience(actor, b.prototype, b.audience),
135
+ audience: await review.setAudience(scope, actor, b.prototype, b.audience),
136
+ };
137
+ case 'control.audience':
138
+ return {
139
+ prototype: b.prototype,
140
+ ...(await review.setControl(scope, actor, {
141
+ prototype: b.prototype,
142
+ kind: b.kind,
143
+ id: b.id,
144
+ audience: b.audience,
145
+ })),
104
146
  };
105
- default:
106
- return peopleCommand(op, b, ctx);
107
147
  }
108
148
  }
109
149
  async function readJson(request) {
@@ -148,45 +188,86 @@ export async function handleReview(request, ctx) {
148
188
  return json(503, { error: STORE_DOWN }, { 'retry-after': '30' });
149
189
  }
150
190
  }
151
- /** The person a request's signed cookie names, while they may still sign in. */
152
- export async function actorFrom(request, review, gate) {
191
+ /** The person a request's signed cookie names, while they may still sign in, in `scope`. */
192
+ export async function actorFrom(request, review, gate, scope) {
153
193
  const claim = await readPersonToken(gate, readCookie(request, PERSON_COOKIE));
154
- return claim ? review.sessionPerson(claim.id, claim.epoch) : null;
194
+ return claim ? review.sessionPerson(scope, claim.id, claim.epoch) : null;
155
195
  }
196
+ /** What a studio site says when it is not set up: every client host sees it, so it names no command, studio or client. */
197
+ const SITE_NOT_SET_UP = 'This site is not set up yet.';
156
198
  /**
157
- * The review service as deployed: Upstash for the store, Jev for triage when
158
- * its key is set and `checks` is given. `now` is the clock, so the gate and
159
- * the service it asks run on one (the gate's tests move it).
199
+ * A studio site's review service: Upstash for the store, Jev for triage
200
+ * when its key is set and `checks` is given. `now` is the clock, so the gate
201
+ * and the service it asks run on one (the gate's tests move it). Without the
202
+ * gate's secret or the store, the cause goes to the site's log and a visitor
203
+ * gets SITE_NOT_SET_UP.
160
204
  */
161
- export function deployedReview(env, checks = null, now) {
162
- const gate = readGate(env);
163
- if (!gate)
164
- return { error: 'The prototype gate is not configured.' };
205
+ export function studioReview(env, checks = null, now) {
206
+ const keys = readGate(env);
165
207
  const store = storeConfig(env);
166
- if (!store)
167
- return { error: 'Review is not set up on this site: pnpm bootstrap --vercel <project> --review.' };
208
+ if (!keys || !store) {
209
+ console.error('[studio]', keys ? 'The review store is not configured.' : 'GATE_SECRET is missing or short.');
210
+ return { error: SITE_NOT_SET_UP };
211
+ }
168
212
  return {
169
- gate,
213
+ keys,
170
214
  review: createReview(upstashKV(store), {
171
215
  triage: jevTriager(env.TYPESAFE_API_KEY ?? '', checks),
172
216
  ...(now ? { now } : {}),
173
217
  }),
174
218
  };
175
219
  }
176
- /** The Vercel function's whole body; `checks` is the project's checks.json, bundled by its api/review.ts. */
177
- export async function deployedHandler(request, checks) {
178
- const setup = deployedReview(process.env, checks);
220
+ /** The client a studio request's host names, from one host lookup; null for a host no client has. */
221
+ async function hostClient(request, review, hosts) {
222
+ const host = hostName(hostOf(request));
223
+ return host ? await hosts(host, (h) => review.clientOfHost(h)) : null;
224
+ }
225
+ /**
226
+ * The scope a signed-in studio request runs in: the host's client, and the
227
+ * `project` parameter only when it is one of that client's projects with a
228
+ * build. Null for a project the client does not have or has not built yet (a
229
+ * malformed slug among them, refused before any key is built), so an
230
+ * unshared project reads as none.
231
+ */
232
+ async function studioScope(request, review, client) {
233
+ const project = new URL(request.url).searchParams.get('project');
234
+ if (project === null)
235
+ return { client };
236
+ if (!isProjectSlug(project))
237
+ return null;
238
+ const found = await review.projectOf({ client, project });
239
+ return found?.build ? { client, project } : null;
240
+ }
241
+ /** The gate's answer to no session, in JSON: it names no client (S10), and clears a cookie that does not hold. */
242
+ const signedOut = (request) => json(401, { error: 'Sign in with the link the studio sent you.' }, readCookie(request, PERSON_COOKIE) === undefined ? {} : { 'set-cookie': clearedCookie(PERSON_COOKIE) });
243
+ /**
244
+ * A studio site's review function: the host's client is the scope, and the
245
+ * gate's client, of every op. The session is read before any project is
246
+ * looked up (S5), so a caller signed out, or signed in for another client,
247
+ * gets one answer whatever project the request names.
248
+ */
249
+ export async function studioHandler(request, checks, hosts) {
250
+ const setup = studioReview(process.env, checks);
179
251
  if ('error' in setup)
180
252
  return json(503, { error: setup.error });
181
- let actor;
253
+ let ctx;
182
254
  try {
183
- actor = await actorFrom(request, setup.review, setup.gate);
255
+ const found = await hostClient(request, setup.review, hosts);
256
+ if (!found)
257
+ return json(404, { error: 'Not found.' });
258
+ const client = found.slug;
259
+ const gate = { ...setup.keys, client, since: found.createdAt };
260
+ const actor = await actorFrom(request, setup.review, gate, { client });
261
+ if (!actor)
262
+ return signedOut(request);
263
+ const scope = await studioScope(request, setup.review, client);
264
+ if (!scope)
265
+ return json(404, { error: 'Not found.' });
266
+ ctx = { review: setup.review, actor, scope };
184
267
  }
185
268
  catch (error) {
186
- // The store is down: say so in JSON, as every other answer here is, so the panel can retry.
187
269
  console.error('[review]', error);
188
- // Retry-After tells the panel this passes, unlike a 503 for a site with no store.
189
270
  return json(503, { error: STORE_DOWN }, { 'retry-after': '30' });
190
271
  }
191
- return handleReview(request, { review: setup.review, actor });
272
+ return handleReview(request, ctx);
192
273
  }
@@ -0,0 +1,10 @@
1
+ import { del, get, list, put } from '@vercel/blob';
2
+ import type { Files } from '../core/files.ts';
3
+ /** The four SDK calls the port makes, so a test can stand in for the store. */
4
+ export type BlobSdk = {
5
+ put: typeof put;
6
+ get: typeof get;
7
+ list: typeof list;
8
+ del: typeof del;
9
+ };
10
+ export declare function blobFiles(token?: string, sdk?: BlobSdk): Files;
@@ -0,0 +1,53 @@
1
+ // The files port on a private Vercel Blob store (`studios-findings.md`,
2
+ // section 1). Nothing is ever public: a blob's own URL is 403 without the
3
+ // store's credential. With no `token`, the SDK finds its credential itself
4
+ // (OIDC with a store id, else BLOB_READ_WRITE_TOKEN), so the studio site's
5
+ // functions work either way; a script on a person's machine passes the
6
+ // read-write token. That token reads and deletes every client's files: it
7
+ // lives in the studio folder's ignored env file and the site's env, nowhere else.
8
+ import { del, get, list, put } from '@vercel/blob';
9
+ /**
10
+ * Whether the store's URL for `path` names `path` and nothing else. The SDK
11
+ * puts a path into a URL as it is, and a URL parser drops a tab or a newline,
12
+ * resolves `..` and `%2e%2e`, and cuts at `?` and `#`: a path it would rewrite
13
+ * is never sent, so no read leaves the folder it names.
14
+ */
15
+ function unchanged(path) {
16
+ try {
17
+ return decodeURIComponent(new URL(path, 'https://store.invalid/').pathname) === `/${path}`;
18
+ }
19
+ catch {
20
+ return false;
21
+ }
22
+ }
23
+ export function blobFiles(token, sdk = { put, get, list, del }) {
24
+ const auth = token ? { token } : {};
25
+ return {
26
+ async put(path, body, type) {
27
+ if (!unchanged(path))
28
+ throw new Error(`Not a file path: ${JSON.stringify(path)}.`);
29
+ // A build's paths are new: without allowOverwrite the store refuses one that exists, and that is a bug.
30
+ await sdk.put(path, new Blob([body]), { access: 'private', contentType: type, ...auth });
31
+ },
32
+ async get(path) {
33
+ if (!unchanged(path))
34
+ return null;
35
+ const found = await sdk.get(path, { access: 'private', ...auth });
36
+ return found?.statusCode === 200 ? { body: found.stream, type: found.blob.contentType } : null;
37
+ },
38
+ async list(prefix) {
39
+ const paths = [];
40
+ let cursor;
41
+ do {
42
+ const page = await sdk.list({ prefix, limit: 1000, cursor, ...auth });
43
+ paths.push(...page.blobs.map((b) => b.pathname));
44
+ cursor = page.hasMore ? page.cursor : undefined;
45
+ } while (cursor);
46
+ return paths;
47
+ },
48
+ async remove(paths) {
49
+ if (paths.length)
50
+ await sdk.del(paths, auth);
51
+ },
52
+ };
53
+ }
@@ -1,8 +1,8 @@
1
1
  /// <reference types="node" />
2
2
  // The project's checks, read once: .design-hub/checks.json when the project
3
3
  // has one, the package defaults when it does not. The scripts and the dev
4
- // server import `checks` from here; the Vercel function gets its copy bundled
5
- // by the project's api/review.ts.
4
+ // server import `checks` from here; a studio site's review function runs on
5
+ // the package defaults.
6
6
  import { existsSync, readFileSync } from 'node:fs';
7
7
  import { DEFAULT_CHECKS, loadChecks } from '../core/checks.js';
8
8
  import { CHECKS_FILE } from './paths.js';
@@ -1,11 +1,11 @@
1
1
  import { createReview } from '../core/review/service.js';
2
- import { KEY } from '../core/review/store.js';
2
+ import { keyOf } from '../core/review/store.js';
3
3
  import { jevTriager } from '../core/review/triage.js';
4
4
  import { API_PATH, handleReview } from './api.js';
5
5
  import { checks } from './checks.js';
6
6
  import { readEnv } from './env.js';
7
7
  import { fileKV } from './file-kv.js';
8
- import { LOCAL_STORE, localStudio } from './local.js';
8
+ import { LOCAL_SCOPE, LOCAL_STORE, localStudio } from './local.js';
9
9
  import { ROOT } from './paths.js';
10
10
  // Connect strips the mount path from req.url; originalUrl keeps the query the handler reads.
11
11
  async function toRequest(req) {
@@ -42,10 +42,10 @@ export function devReview() {
42
42
  });
43
43
  const actor = localStudio();
44
44
  // The local Studio person is in the people list like anyone else, so the people panel shows them.
45
- void kv.hset(KEY.people, actor.id, JSON.stringify(actor));
45
+ void kv.hset(keyOf('studio', 'people'), actor.id, JSON.stringify(actor));
46
46
  server.middlewares.use(API_PATH, (req, res, nextMiddleware) => {
47
47
  toRequest(req)
48
- .then((request) => handleReview(request, { review, actor }))
48
+ .then((request) => handleReview(request, { review, actor, scope: LOCAL_SCOPE }))
49
49
  .then((response) => send(res, response))
50
50
  .catch(nextMiddleware);
51
51
  });
@@ -1,5 +1,7 @@
1
1
  export declare function readEnv(dir: string): Record<string, string>;
2
2
  export declare function writeEnv(dir: string, updates: Record<string, string>): void;
3
+ /** Takes these keys out of .env, keeping every other line. */
4
+ export declare function removeEnv(dir: string, names: readonly string[]): void;
3
5
  /** The variables a harness (Conductor, T3 Code, a script) may hand a worktree its port in, first wins. */
4
6
  declare const HARNESS_PORT_VARS: readonly ['DESIGN_HUB_PORT', 'CONDUCTOR_PORT'];
5
7
  /**
@@ -46,6 +46,15 @@ export function writeEnv(dir, updates) {
46
46
  const text = next.join('\n').replace(/\n*$/, '\n');
47
47
  writeFileSync(file, text, { mode: 0o600 });
48
48
  }
49
+ /** Takes these keys out of .env, keeping every other line. */
50
+ export function removeEnv(dir, names) {
51
+ const file = join(dir, ENV_FILE);
52
+ if (!existsSync(file))
53
+ return;
54
+ const lines = readFileSync(file, 'utf8').split('\n');
55
+ const kept = lines.filter((line) => !names.includes(line.match(/^\s*([A-Z0-9_]+)\s*=/)?.[1] ?? ''));
56
+ writeFileSync(file, kept.join('\n'), { mode: 0o600 });
57
+ }
49
58
  /** The variables a harness (Conductor, T3 Code, a script) may hand a worktree its port in, first wins. */
50
59
  const HARNESS_PORT_VARS = ['DESIGN_HUB_PORT', 'CONDUCTOR_PORT'];
51
60
  function asPort(value) {
@@ -1,10 +1,51 @@
1
1
  /// <reference types="node" />
2
2
  // A fetch that answers like Upstash's REST API from memory, for tests that
3
- // exercise the deployed code path (proxy.ts, api/review.ts) without an account.
3
+ // exercise a studio site's code path (its gate and functions) without an account.
4
4
  import { memoryKV } from '../core/review/store.js';
5
+ /** How many keys one SCAN call looks at: few, so a walk takes many calls, some of them finding nothing. */
6
+ const SCAN_PAGE = 2;
7
+ /** A Redis glob as a RegExp: `*`, `?`, `[…]`, and `\` before a character that stands for itself. */
8
+ function globToRegExp(glob) {
9
+ const plain = (c) => c.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
10
+ let out = '';
11
+ for (let i = 0; i < glob.length; i++) {
12
+ const c = glob[i];
13
+ const end = c === '[' ? glob.indexOf(']', i + 1) : -1;
14
+ if (c === '\\' && i + 1 < glob.length)
15
+ out += plain(glob[++i]);
16
+ else if (c === '*')
17
+ out += '[\\s\\S]*';
18
+ else if (c === '?')
19
+ out += '[\\s\\S]';
20
+ else if (end > i) {
21
+ out += `[${glob.slice(i + 1, end)}]`;
22
+ i = end;
23
+ }
24
+ else
25
+ out += plain(c);
26
+ }
27
+ return new RegExp(`^${out}$`);
28
+ }
5
29
  export function fakeUpstash() {
6
- const kv = memoryKV();
7
- async function run(cmd, [key, a, b]) {
30
+ // Every key Redis would have: a hash with no fields, or an empty set, is no key at all.
31
+ let live = [];
32
+ const kv = memoryKV(undefined, (s) => {
33
+ live = [
34
+ ...Object.entries(s.hashes).filter(([, v]) => Object.keys(v).length),
35
+ ...Object.entries(s.sets).filter(([, v]) => v.length),
36
+ ]
37
+ .map(([k]) => k)
38
+ .sort();
39
+ });
40
+ function scan(cursor, args) {
41
+ const at = Number(cursor);
42
+ const m = args.indexOf('MATCH');
43
+ const match = m < 0 ? '*' : args[m + 1];
44
+ const page = live.slice(at, at + SCAN_PAGE).filter((k) => globToRegExp(match).test(k));
45
+ return [at + SCAN_PAGE >= live.length ? '0' : String(at + SCAN_PAGE), page];
46
+ }
47
+ async function run(cmd, args) {
48
+ const [key, a, b] = args;
8
49
  switch (cmd) {
9
50
  case 'HGET':
10
51
  return kv.hget(key, a);
@@ -13,6 +54,8 @@ export function fakeUpstash() {
13
54
  return 1;
14
55
  case 'HDEL':
15
56
  return kv.hdel(key, a);
57
+ case 'HSETNX':
58
+ return (await kv.hsetnx(key, a, b)) ? 1 : 0;
16
59
  case 'HINCRBY':
17
60
  return kv.hincrby(key, a, Number(b));
18
61
  case 'HGETALL':
@@ -22,6 +65,12 @@ export function fakeUpstash() {
22
65
  return 1;
23
66
  case 'SMEMBERS':
24
67
  return kv.smembers(key);
68
+ case 'DEL':
69
+ for (const k of args)
70
+ await kv.del(k);
71
+ return args.length;
72
+ case 'SCAN':
73
+ return scan(key, args.slice(1));
25
74
  default:
26
75
  throw new Error(`unknown command ${cmd}`);
27
76
  }
@@ -0,0 +1,11 @@
1
+ import { type Client } from '../core/review/model.ts';
2
+ export type HostLookup = (host: string, load: (host: string) => Promise<Client | null>) => Promise<Client | null>;
3
+ /** One instance's cache of host answers, the unknown ones included. `now` is its clock, so tests need not wait. */
4
+ export declare function hostCache(now?: () => Date): HostLookup;
5
+ /**
6
+ * The host a request was sent to, as the platform hands it on: the forwarded
7
+ * host, else Host, else the URL's (a function's URL can carry the deployment's
8
+ * own host). A client may send any of these; the cookie it holds is signed to
9
+ * one client, so naming another host opens nothing.
10
+ */
11
+ export declare const hostOf: (request: Request) => string;
@@ -0,0 +1,31 @@
1
+ // Which client a studio site's host serves. The gate and every studio
2
+ // function ask on each request, so the answer is kept in memory for a minute
3
+ // per instance: archiving a client, or adding one, takes effect within
4
+ // HOST_SECONDS. A store that does not answer is never kept, so an outage ends
5
+ // when the store is back.
6
+ import { HOST_SECONDS } from '../core/review/model.js';
7
+ /** Hosts kept at once: a wildcard domain sends any made-up name to the gate, so the map is bounded. */
8
+ const MAX_HOSTS = 500;
9
+ /** One instance's cache of host answers, the unknown ones included. `now` is its clock, so tests need not wait. */
10
+ export function hostCache(now = () => new Date()) {
11
+ const seen = new Map();
12
+ return async (host, load) => {
13
+ const at = now().getTime();
14
+ const hit = seen.get(host);
15
+ if (hit && at - hit.at < HOST_SECONDS * 1000)
16
+ return hit.client;
17
+ const client = await load(host);
18
+ seen.delete(host);
19
+ if (seen.size >= MAX_HOSTS)
20
+ seen.delete(seen.keys().next().value);
21
+ seen.set(host, { client, at });
22
+ return client;
23
+ };
24
+ }
25
+ /**
26
+ * The host a request was sent to, as the platform hands it on: the forwarded
27
+ * host, else Host, else the URL's (a function's URL can carry the deployment's
28
+ * own host). A client may send any of these; the cookie it holds is signed to
29
+ * one client, so naming another host opens nothing.
30
+ */
31
+ export const hostOf = (request) => request.headers.get('x-forwarded-host') ?? request.headers.get('host') ?? new URL(request.url).host;
@@ -1,4 +1,10 @@
1
- import type { Person } from '../core/review/model.ts';
1
+ import { type Person, type Scope } from '../core/review/model.ts';
2
2
  export declare const LOCAL_STORE: string;
3
+ /**
4
+ * The one scope of the local store: `design-hub dev` has no host to name a
5
+ * client, so every op there runs in this fixed client and project, and the
6
+ * CLI's --local commands read and write the same records.
7
+ */
8
+ export declare const LOCAL_SCOPE: Scope;
3
9
  /** Whoever runs this machine's dev server or CLI: Studio, because they hold the store itself. */
4
10
  export declare const localStudio: (id?: string, team?: string) => Person;
@@ -1,10 +1,18 @@
1
1
  /// <reference types="node" />
2
2
  // The review store and identity on this machine, shared by the dev server
3
- // and the CLI: .design-hub/review.json, and a local Studio person named from git.
3
+ // and the CLI's --local commands: .design-hub/review.json, one fixed scope
4
+ // in it, and a local Studio person named from git.
4
5
  import { execFileSync } from 'node:child_process';
5
6
  import { join } from 'node:path';
7
+ import { LOCAL_CLIENT } from '../core/review/model.js';
6
8
  import { STATE_DIR } from './paths.js';
7
9
  export const LOCAL_STORE = join(STATE_DIR, 'review.json');
10
+ /**
11
+ * The one scope of the local store: `design-hub dev` has no host to name a
12
+ * client, so every op there runs in this fixed client and project, and the
13
+ * CLI's --local commands read and write the same records.
14
+ */
15
+ export const LOCAL_SCOPE = { client: LOCAL_CLIENT, project: 'site' };
8
16
  function gitName() {
9
17
  try {
10
18
  return execFileSync('git', ['config', 'user.name'], { encoding: 'utf8' }).trim();
@@ -19,6 +27,7 @@ export const localStudio = (id = 'local', team = 'Local') => ({
19
27
  name: gitName() || 'You',
20
28
  team,
21
29
  kind: 'studio',
30
+ client: null,
22
31
  email: null,
23
32
  accessEndsAt: null,
24
33
  createdAt: new Date(0).toISOString(),
@@ -0,0 +1,41 @@
1
+ import { type KV } from '../core/review/store.ts';
2
+ /** What the mark is checked against: a studio folder and the settings its studio.json holds. */
3
+ export type MarkedStudio = {
4
+ dir: string;
5
+ config: {
6
+ id?: string;
7
+ slug: string;
8
+ owner: string | null;
9
+ vercel: {
10
+ team: string;
11
+ project: string;
12
+ };
13
+ };
14
+ };
15
+ /**
16
+ * A refusal: why, and its detail (`code`, `studio`, `fix`), which the CLI
17
+ * prints as it prints a CliError's (scripts/lib/cli.ts, which this layer
18
+ * cannot import).
19
+ */
20
+ export declare class MarkError extends Error {
21
+ detail: {
22
+ code: string;
23
+ studio: string;
24
+ fix: string;
25
+ };
26
+ constructor(message: string, detail: MarkError['detail']);
27
+ }
28
+ /**
29
+ * Marks the database as this studio's, for `studio create`, before anything
30
+ * else is written to it: 'claimed' the first time, 'kept' when it is already
31
+ * this studio's. One marked for another studio, or holding data it is not
32
+ * free for, is refused with nothing written. The mark is set by HSETNX, so of
33
+ * two creates at once on one empty database only one wins.
34
+ */
35
+ export declare function claimDatabase(kv: KV, studio: MarkedStudio): Promise<'claimed' | 'kept'>;
36
+ /**
37
+ * Stops a command before it acts on a database that is not marked as this
38
+ * studio's, so no command of one studio ever reads or changes another's
39
+ * clients, people or links.
40
+ */
41
+ export declare function mustBeOwnDatabase(kv: KV, studio: MarkedStudio): Promise<void>;