@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
package/README.md CHANGED
@@ -10,9 +10,9 @@ design-hub guide <feature> # its walkthrough, docs/sprints/<feature>/guid
10
10
  design-hub commands # every command, with its flags, as JSON
11
11
  ```
12
12
 
13
- Inside the package, from the inside out: `core/` is the pure kernel (README states, the catalog, fixture sets, checks, the Jev client, the review domain); `kit/` the materials prototypes import; `shell/` the browser hub; `server/` the Node side (the review API, signed sessions, the stores, env and paths); `vite/` the plugin that turns a project into a Vite app; `vercel/` the deployed entries; `scripts/` the CLI; `templates/` what `new` copies; `skills/` what `skills` installs. `AGENTS.md` here holds the layers and their rules.
13
+ Inside the package, from the inside out: `core/` is the pure kernel (README states, the catalog, fixture sets, checks, the Jev client, the review domain); `kit/` the materials prototypes import; `shell/` the browser hub; `server/` the Node side (the review API, signed sessions, the stores, env and paths); `vite/` the plugin that turns a project into a Vite app; `vercel/` the studio site's entries; `scripts/` the CLI; `templates/` what `new` copies; `skills/` what `skills` installs. `AGENTS.md` here holds the layers and their rules.
14
14
 
15
- How a project becomes an app: `design-hub dev` runs Vite with the package's `shell/` as the root and the project as the content. `vite/registry.ts` writes `virtual:design-hub/registry` from the project's `prototypes/` and `docs/sprints/`; `vite/kit.ts` resolves `@kit/<name>` to the project's `kit/<name>` first and the package's second. The sections below describe the hub's own interface and the deployed site; they are the reference for changing the package, not for using it.
15
+ How a project becomes an app: `design-hub dev` runs Vite with the package's `shell/` as the root and the project as the content. `vite/registry.ts` writes `virtual:design-hub/registry` from the project's `prototypes/` and `docs/sprints/`; `vite/kit.ts` resolves `@kit/<name>` to the project's `kit/<name>` first and the package's second. The sections below describe the hub's own interface and the studio site; they are the reference for changing the package, not for using it.
16
16
 
17
17
  ## The index
18
18
 
@@ -70,27 +70,29 @@ A speculation rule in `shell/index.html` prefetches a prototype's page when its
70
70
 
71
71
  `/guide/<feature>/` is `docs/sprints/<feature>/guide.md`, rendered for reviewers who have a sign-in link but not the repo; `/guide/` alone opens the only guide, or lists them. The registry plugin lists the guides, so a new feature's walkthrough appears the moment the file exists (`design-hub guide <feature>` starts one from `templates/guide.md`). The Markdown stays the one source: a Vite plugin (`vite/markdown.ts`, the `?doc` import) compiles it at build time with `marked`, so nothing is parsed in the browser. It turns the first H1 into the title, every H2 and H3 into the contents rail, each image into a figure with its pixel size (no layout shift, lazy below the first), and `> [!NOTE]` quotes into callouts. A paragraph that starts `Controls → …` renders as a click path. Links to other Markdown files lose their href, since nothing serves them. The page reads at 16px on a 680px measure; screenshots and tables take the full 960px column, because a 1440px shot at 680px is unreadable. Two raw values: a screenshot wears a 1px inset outline at 10% (black on light, white on dark) and a callout a 6% ring (8% on dark), alphas rather than tokens because they composite on any surface the page is set on. The slug `guide` is the hub's (`design-hub new guide` refuses it). The page's **Open the prototype** button goes to the feature's sprint prototype, and every prototype of the feature answers with **Open the walkthrough** as the last row of Controls, under every group, in a new tab, so a reviewer reads and clicks side by side. Above it, on every prototype, **All prototypes** goes back to `/` in the same tab. A sheet inside the product was rejected: it would be modal over the thing under review, and testing aids never sit in the product chrome.
72
72
 
73
- ## Deploying, and signing in
73
+ ## The studio site, and signing in
74
74
 
75
- `miles-deploy` owns the steps; this is what they rest on. `design-hub signin` starts `vercel login`'s device sign-in in the background and returns its link, so the user clicks instead of typing. `design-hub bootstrap --vercel <project>` links the project, connects it to the `origin` repo when Vercel can reach it, turns Vercel Authentication off and sets the env. `design-hub share` runs the pre-flight, then deploys: a push of a clean production branch when the project is connected to the repo (following the build for that commit), else `vercel deploy --prod`; then it requests the production URL as a signed-out browser and fails unless the sign-in page answers with `noindex` and a link no store holds answers 404, which proves the review store is wired (503 means there is none, so nobody could sign in). Every path on the deployed site sits behind the gate, enforced on the server by Vercel Routing Middleware (`vercel/proxy.ts`, exported as `createProxy` and default-exported by the project's one-line `proxy.ts`, which `vercel.json` names as `proxy.entrypoint`). A client-side gate was rejected because the bundle and the state behind it would still download.
75
+ `miles-deploy` owns the steps; this is what they rest on. A project has no deployment of its own. A **studio** is one site on one hosting account, with one database (Upstash for Redis), one private file store (Vercel Blob), one `GATE_SECRET` and one apex domain, that serves every client of the studio; two studios share none of these. Its folder, made by `design-hub studio create` from `templates/studio/`, is thin like a project: one-line `proxy.ts`, `api/review.ts` and `api/files.ts` from `./vercel`, a `vercel.json`, a `studio.json` (id, slug, apex, team, DNS; no secret) and a gitignored `.env`. A machine finds its studios by slug in `~/.design-hub/studios.json`. `design-hub signin` starts `vercel login`'s device sign-in in the background and returns its link, so the user clicks instead of typing.
76
76
 
77
- Every person is named, and signs in with a one-time link that Studio makes in the review panel's People tab or with `design-hub people add`.
77
+ A client's address is `<client>.<apex>` (or a codename under the apex, `client add --host`), and a project is `/<project>/` below it. `design-hub project link` writes `.design-hub/studio.json` in the project (studio, its id, client, project; committed). `design-hub share` builds the project with base `/<project>/`, uploads `dist/` under `c/<client>/<project>/<build>/` in the file store with a new random build id, checks every file is there, and only then points the project's record at that build, so a half-finished upload is never served; the live build and the two before it are kept. Every path on every client's host sits behind the gate, enforced on the server by Vercel Routing Middleware (`createStudioProxy` in `vercel/proxy.ts`, which the studio's `vercel.json` names as `proxy.entrypoint`). The host names the client, from one store lookup kept a minute per instance; a host no client has is the plain 404 before anything else is read. The files function and the review function run the gate's checks again themselves, in the order host, session, project, so neither trusts anything the gate set. A client-side gate was rejected because the bundle and the state behind it would still download.
78
+
79
+ Every person is named, and signs in with a one-time link that Studio makes in the review panel's People tab, with `design-hub people add` in a linked project, or, for a client's first person and the owner, with `design-hub client add`. A link signs in on its client's host only.
78
80
 
79
81
  - **A link works once.** `GET /invite/<token>` shows who it is for and a Continue button, and uses nothing up, since mail and chat previews open links too. Continue is a same-origin `POST` that uses the link up, sets the session cookie and goes to `/`. The use is atomic: the store's delete is the claim, so of two requests with one link only the one whose delete removed it signs in. A used, expired or unknown link answers 404, as does a link for someone revoked or past their access end. An unused link lasts 14 days. The store keeps only a hash of each token (32 random bytes), so a read of the store signs nobody in.
80
82
  - **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.
81
83
  - **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.
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>`.
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.
84
+ - **Access lasts the engagement.** Each person has an access end: 3 months, 6 months, or open-ended. A new Client gets their client's default (`client access <client>`), else the studio's (`client access` with no client), else 3 months; a new Studio person is open-ended, and Studio can set one person's length from the People tab or `people access <id>`.
85
+ - **The session** is one cookie, `__Host-hub_person`: `HttpOnly`, `Secure`, `SameSite=Lax`, host-only. Its token is `p5.<id>.<epoch>.<kind>.<client>.<expires>.<checkedAt>.<sig>`, signed with HMAC-SHA256 over all of those and over two things it never carries: the review store's URL, so two studios that share a `GATE_SECRET` never accept each other's cookies, and when the client was added, so a slug archived and added again accepts no token from before. A token verifies only on its own client's host, a Studio person's too. Any other version 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. 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. The hub reads any 401, the gate's plain text or the API's JSON, as signed out.
84
86
  - **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`).
87
+ - **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 (`/<project>/<slug>/`) or anything under `/<project>/_p/<slug>/` gets 404 unless that prototype is client-facing, asked of the store on every such request; `/<project>/_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. Below a project, any first segment that is not the hub's own (`assets`, `api`, `guide`, `_gate`, `index.html`, `favicon.svg`), `_p` or a prototype slug gets the same 404. A path that could mean more than one file (a `.` or `..` segment, a backslash, a control character, an empty segment, a `%` left after decoding, or one that does not decode) goes nowhere for anyone, Studio included. Another client's project, and a project with no build, are the same 404, its review API too. 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 audience read. The client's hub at `/` and a project's `/assets/*`, `/guide/*` and review API pass on the session alone. `invite`, `api`, `_gate`, `_p`, `assets`, `guide`, `index.html` and `favicon.svg` are never a prototype's slug (`RESERVED` in `core/prototype.ts`).
86
88
  - **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.
87
89
 
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.
90
+ The studio site reads its env from the Vercel project, never committed: `GATE_SECRET`, at least 32 random characters that sign the session cookie, and the database's and file store's credentials, which `studio create` sets and copies into the studio folder's `.env` (`templates/studio/.env.example` names them). With the secret or the database missing, every host answers 503 "This site is not set up yet.", which names no command, studio or client, so a misconfigured site never serves anything open. 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 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 signed-out page names no client. 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.
89
91
 
90
92
  ## Comments and people
91
93
 
92
94
  Every signed-in person can comment as themselves. The People tab lists each person with their team, kind and when their access ends, and says how links behave where Studio shares them.
93
95
 
94
- The panel (`shell/review/`) mounts on every prototype page in its own React root, so a prototype that throws never takes it down. A comment carries the prototype, the URL, every dial panel's values (`snapshotDials`), and the element it was pinned to as a selector path with an offset; Show state reopens the URL and sets the dials back. Pins draw over their elements and below the Controls panel. The API is one endpoint, `/api/review` (`server/api.ts`, reached on Vercel through the project's one-line `api/review.ts`, which also bundles the project's `checks.json` so triage runs on its thresholds): queries by GET, commands by POST with a JSON body, same-origin only. The rules (who may delete, what a valid comment is) live once, in `core/review/`, behind a small storage port: Upstash Redis over REST when deployed, a file in `.design-hub/review.json` under `design-hub dev`, where whoever runs the server is a local Studio person.
96
+ The panel (`shell/review/`) mounts on every prototype page in its own React root, so a prototype that throws never takes it down. A comment carries the prototype, the URL, every dial panel's values (`snapshotDials`), and the element it was pinned to as a selector path with an offset; Show state reopens the URL and sets the dials back. Pins draw over their elements and below the Controls panel. The API is one endpoint, `<project>/api/review` (`server/api.ts`, reached on a studio site through its one-line `api/review.ts`, scoped by the host's client and the project the path names): queries by GET, commands by POST with a JSON body, same-origin only. The rules (who may delete, what a valid comment is, which client a person may act in) live once, in `core/review/`, behind a small storage port: the studio's Upstash Redis over REST, or a file in `.design-hub/review.json` under `design-hub dev`, where whoever runs the server is a local Studio person in one fixed scope. Every key is built by one function from a scope, under the prefix `hub4:`: the studio's (`studio:people`, `clients`, `hosts`, …), a client's (`c:<client>:people`, `:links`, `:projects`, …) and a project's (`c:<client>:p:<project>:comments:<prototype>`, …), so no op reaches another client's records.
95
97
 
96
- `design-hub dev` serves the prototypes open, with the review panel on the local store. The gate is covered by `pnpm test` (`vercel/proxy.test.ts`, against an in-memory Upstash); `vercel dev` in a project runs it for real.
98
+ `design-hub dev` serves the prototypes open, with the review panel on the local store. The gate and the studio's functions are covered by `pnpm test` (`vercel/proxy.test.ts`, against an in-memory Upstash and file store).
@@ -0,0 +1,176 @@
1
+ import assert from 'node:assert/strict';
2
+ import { test } from 'node:test';
3
+ import { DialStore } from 'dialkit';
4
+ import {
5
+ client,
6
+ clientVariants,
7
+ controlField,
8
+ defaultOf,
9
+ dialAudience,
10
+ isControlId,
11
+ keepDials,
12
+ type Marks,
13
+ NO_MARKS,
14
+ readConfig,
15
+ readMarks,
16
+ withDefaults,
17
+ withMark,
18
+ } from './controls.ts';
19
+
20
+ const select = { type: 'select', options: ['comfortable', 'compact'], default: 'comfortable' };
21
+
22
+ test('a dial is internal until marked: in code with client(), or in the hub, which overrules the code', () => {
23
+ const { dials } = readConfig('Review', {
24
+ fixtures: select,
25
+ density: client(select),
26
+ avatars: client(true),
27
+ });
28
+ assert.deepEqual(dials, [
29
+ { id: 'Review/fixtures', path: ['fixtures'], inCode: 'internal' },
30
+ { id: 'Review/density', path: ['density'], inCode: 'client' },
31
+ { id: 'Review/avatars', path: ['avatars'], inCode: 'client' },
32
+ ]);
33
+ const marks: Marks = { dials: { 'Review/fixtures': 'client', 'Review/density': 'internal' }, variants: [] };
34
+ const audience = Object.fromEntries(dials.map((d) => [d.id, dialAudience(marks, d.id, d.inCode)]));
35
+ assert.deepEqual(audience, {
36
+ 'Review/fixtures': 'client',
37
+ 'Review/density': 'internal',
38
+ 'Review/avatars': 'client',
39
+ });
40
+ assert.equal(dialAudience(NO_MARKS, 'Review/fixtures', 'internal'), 'internal');
41
+ });
42
+
43
+ test('readConfig unwraps every client() and reads folders, a marked folder marking each dial in it', () => {
44
+ const { config, dials } = readConfig('Card', {
45
+ radius: [8, 0, 24, 1],
46
+ shadow: client({ blur: [12, 0, 40, 1], _collapsed: true, tint: { hue: 200 } }),
47
+ motion: { rise: client([220, 0, 600, 10]), ease: { type: 'easing', ease: [0, 0, 1, 1], duration: 0.2 } },
48
+ });
49
+ assert.deepEqual(config, {
50
+ radius: [8, 0, 24, 1],
51
+ shadow: { blur: [12, 0, 40, 1], _collapsed: true, tint: { hue: 200 } },
52
+ motion: { rise: [220, 0, 600, 10], ease: { type: 'easing', ease: [0, 0, 1, 1], duration: 0.2 } },
53
+ });
54
+ assert.deepEqual(
55
+ dials.map((d) => `${d.id} ${d.inCode}`),
56
+ [
57
+ 'Card/radius internal',
58
+ 'Card/shadow.blur client',
59
+ 'Card/shadow.tint.hue client',
60
+ 'Card/motion.rise client',
61
+ 'Card/motion.ease internal',
62
+ ],
63
+ );
64
+ });
65
+
66
+ test('keepDials leaves out every dial not shown, and a folder with none left', () => {
67
+ const { config } = readConfig('Card', {
68
+ radius: [8, 0, 24, 1],
69
+ shadow: { _collapsed: true, blur: [12, 0, 40, 1], spread: 2 },
70
+ motion: { rise: [220, 0, 600, 10] },
71
+ });
72
+ const kept = keepDials('Card', config, (id) => id === 'Card/shadow.blur');
73
+ assert.deepEqual(kept, { shadow: { blur: [12, 0, 40, 1], _collapsed: true } });
74
+ assert.deepEqual(
75
+ keepDials('Card', config, () => false),
76
+ {},
77
+ );
78
+ assert.deepEqual(
79
+ keepDials('Card', config, () => true),
80
+ config,
81
+ );
82
+ });
83
+
84
+ // Every kind of dial DialKit has, with and without a default of its own.
85
+ const EVERY = {
86
+ bare: 0.4,
87
+ slider: [220, 0, 600, 10],
88
+ outside: [900, 0, 600, 10],
89
+ swapped: [5, 10, 0],
90
+ open: [7],
91
+ toggle: true,
92
+ word: 'hello',
93
+ chosen: { type: 'select', options: ['a', 'b'], default: 'b' },
94
+ first: { type: 'select', options: [{ value: 'x', label: 'X' }, 'y'] },
95
+ none: { type: 'select', options: [] },
96
+ color: { type: 'color', default: '#ff0000' },
97
+ black: { type: 'color' },
98
+ text: { type: 'text', default: 'Title' },
99
+ blank: { type: 'text' },
100
+ image: { type: 'image', options: ['/a.png', '/b.png'] },
101
+ pad: { type: 'pad', x: [0.333, 0, 1, 0.01], y: [5, -10, 10] },
102
+ centre: { type: 'pad' },
103
+ spring: { type: 'spring', visualDuration: 0.3, bounce: 0.2 },
104
+ ease: { type: 'easing', ease: [0.2, 0, 0, 1], duration: 0.3 },
105
+ folder: { depth: [2, 0, 8, 1], inner: { on: false } },
106
+ };
107
+
108
+ test('defaultOf is DialKit’s own starting value, for every kind of dial', () => {
109
+ DialStore.registerPanel('every', 'Every', EVERY as any);
110
+ const flat = DialStore.getValues('every') as Record<string, unknown>;
111
+ DialStore.unregisterPanel('every');
112
+ const ours = withDefaults(EVERY, {});
113
+ const flatten = (node: Record<string, unknown>, prefix = ''): Record<string, unknown> =>
114
+ Object.fromEntries(
115
+ Object.entries(node).flatMap(([k, v]) =>
116
+ prefix === '' && k === 'folder'
117
+ ? Object.entries(flatten(v as Record<string, unknown>, 'folder.'))
118
+ : k === 'inner'
119
+ ? Object.entries(flatten(v as Record<string, unknown>, `${prefix}inner.`))
120
+ : [[prefix + k, v]],
121
+ ),
122
+ );
123
+ assert.deepEqual(flatten(ours), flat);
124
+ });
125
+
126
+ test('withDefaults keeps the values DialKit gave and fills the dials it did not draw', () => {
127
+ const config = { fixtures: select, density: select, shadow: { blur: [12, 0, 40, 1], spread: 2 } };
128
+ assert.deepEqual(withDefaults(config, { density: 'compact', shadow: { blur: 30 } }), {
129
+ fixtures: 'comfortable',
130
+ density: 'compact',
131
+ shadow: { blur: 30, spread: 2 },
132
+ });
133
+ assert.equal(defaultOf([3, 0, 10, 1]), 3);
134
+ });
135
+
136
+ test('a Client gets the variants Studio marked, in the prototype’s order, and the first when none is', () => {
137
+ const names = ['Baseline', 'Lift', 'Sink'];
138
+ assert.deepEqual(clientVariants(names, NO_MARKS), ['Baseline']);
139
+ assert.deepEqual(clientVariants(names, { dials: {}, variants: ['Sink', 'Lift'] }), ['Lift', 'Sink']);
140
+ // A mark for a variant the prototype no longer has counts for nothing.
141
+ assert.deepEqual(clientVariants(names, { dials: {}, variants: ['Gone'] }), ['Baseline']);
142
+ assert.deepEqual(clientVariants([], NO_MARKS), []);
143
+ });
144
+
145
+ test('marks read from the store ignore what is not theirs, and withMark switches one', () => {
146
+ const marks = readMarks({
147
+ [controlField('dial', 'Review/density')]: 'client',
148
+ [controlField('dial', 'Review/fixtures')]: 'internal',
149
+ [controlField('dial', 'Review/odd')]: 'yes',
150
+ [controlField('variant', 'Lift')]: 'client',
151
+ [controlField('variant', 'Sink')]: 'internal',
152
+ 'thing:x': 'client',
153
+ 'dial:': 'client',
154
+ plain: 'client',
155
+ });
156
+ assert.deepEqual(marks, {
157
+ dials: { 'Review/density': 'client', 'Review/fixtures': 'internal' },
158
+ variants: ['Lift'],
159
+ });
160
+ const next = withMark(
161
+ withMark(marks, 'variant', 'Baseline', 'client'),
162
+ 'dial',
163
+ 'Review/density',
164
+ 'internal',
165
+ );
166
+ assert.deepEqual(next.variants, ['Baseline', 'Lift']);
167
+ assert.equal(next.dials['Review/density'], 'internal');
168
+ assert.deepEqual(withMark(next, 'variant', 'Lift', 'internal').variants, ['Baseline']);
169
+ });
170
+
171
+ test('a control id is one trimmed line of at most 200 characters', () => {
172
+ for (const ok of ['Review/density', 'Outline, as legal asked', 'a', 'x'.repeat(200)])
173
+ assert.ok(isControlId(ok), ok);
174
+ for (const bad of ['', ' a', 'a ', 'a\nb', 'a\u0000', 'x'.repeat(201), 3, null, undefined])
175
+ assert.ok(!isControlId(bad), String(bad));
176
+ });
@@ -0,0 +1,195 @@
1
+ // Which of a prototype's controls a Client gets: its dials and its variants.
2
+ // Pure, so the server, the kit and the tests read one set of rules.
3
+ //
4
+ // A dial is internal until marked client-facing. It is marked in two places:
5
+ // in code, with `client(...)` around the dial where it is declared, which is
6
+ // where it starts; and in the hub, by Studio, which is stored per deployed
7
+ // site and overrules the code either way. A variant is marked only in the
8
+ // hub. The View tools are never asked about: they are always a Client's.
9
+ //
10
+ // The mark decides what a Client's panel draws and nothing else. A prototype's
11
+ // code is one file a Client's browser loads, so an internal dial's name, range
12
+ // and default are still in it; its value stays at the default.
13
+
14
+ export type ControlAudience = 'internal' | 'client';
15
+
16
+ export const CONTROL_KINDS = ['dial', 'variant'] as const;
17
+ export type ControlKind = (typeof CONTROL_KINDS)[number];
18
+
19
+ /** What the hub stored for one prototype: a mark per dial Studio switched, and the variants a Client gets. */
20
+ export type Marks = { dials: Record<string, ControlAudience>; variants: string[] };
21
+
22
+ export const NO_MARKS: Marks = { dials: {}, variants: [] };
23
+
24
+ const MAX_ID = 200;
25
+
26
+ /** A dial's or a variant's name as the store keeps it: one line of text, trimmed, at most 200 characters. */
27
+ export const isControlId = (v: unknown): v is string =>
28
+ typeof v === 'string' &&
29
+ v.length > 0 &&
30
+ v.length <= MAX_ID &&
31
+ v.trim() === v &&
32
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what is refused
33
+ !/[\u0000-\u001f\u007f]/.test(v);
34
+
35
+ /** A dial is named by its panel and its key, a folder's dial by the keys down to it: `Review/density`, `Card/shadow.blur`. */
36
+ export const dialId = (panel: string, path: readonly string[]) => `${panel}/${path.join('.')}`;
37
+
38
+ /** The store's field for one control. */
39
+ export const controlField = (kind: ControlKind, id: string) => `${kind}:${id}`;
40
+
41
+ /** The marks in a prototype's stored fields. A field or a value that is not one of ours is left out, so it reads as unmarked. */
42
+ export function readMarks(fields: Record<string, string>): Marks {
43
+ const dials: Record<string, ControlAudience> = {};
44
+ const variants: string[] = [];
45
+ for (const [field, value] of Object.entries(fields)) {
46
+ const at = field.indexOf(':');
47
+ const [kind, id] = [field.slice(0, at), field.slice(at + 1)];
48
+ if (!isControlId(id)) continue;
49
+ if (kind === 'dial' && (value === 'client' || value === 'internal')) dials[id] = value;
50
+ if (kind === 'variant' && value === 'client') variants.push(id);
51
+ }
52
+ return { dials, variants: variants.sort() };
53
+ }
54
+
55
+ /** The marks after one control is switched. */
56
+ export function withMark(marks: Marks, kind: ControlKind, id: string, audience: ControlAudience): Marks {
57
+ if (kind === 'dial') return { ...marks, dials: { ...marks.dials, [id]: audience } };
58
+ const rest = marks.variants.filter((v) => v !== id);
59
+ return { ...marks, variants: audience === 'client' ? [...rest, id].sort() : rest };
60
+ }
61
+
62
+ /** Who a dial is for: the hub's mark when Studio set one, else what the code says, else internal. */
63
+ export const dialAudience = (marks: Marks, id: string, inCode: ControlAudience): ControlAudience =>
64
+ marks.dials[id] ?? inCode;
65
+
66
+ /**
67
+ * The variants a Client gets, in the order the prototype declares them. One
68
+ * is no picker. None marked is still one: the first, so a page is never empty.
69
+ */
70
+ export function clientVariants(names: readonly string[], marks: Marks): string[] {
71
+ const kept = names.filter((n) => marks.variants.includes(n));
72
+ return kept.length ? kept : names.slice(0, 1);
73
+ }
74
+
75
+ // The config a prototype hands to useDials, read without DialKit's types: a
76
+ // leaf is a dial, an object without a `type` is a folder of them.
77
+
78
+ type Config = Record<string, unknown>;
79
+ type Marked = { __client: unknown };
80
+
81
+ const isRecord = (v: unknown): v is Config => typeof v === 'object' && v !== null && !Array.isArray(v);
82
+ const isMarked = (v: unknown): v is Marked => isRecord(v) && '__client' in v;
83
+ const isFolder = (v: unknown): v is Config => isRecord(v) && !('type' in v);
84
+ /** DialKit's own key for a folder that starts closed: not a dial. */
85
+ const SETTING = '_collapsed';
86
+
87
+ /**
88
+ * Marks a dial client-facing where it is declared, or a folder and every dial
89
+ * in it. Typed as the dial itself, so the values a prototype reads keep their types.
90
+ */
91
+ export const client = <T>(dial: T): T => ({ __client: dial }) as T;
92
+
93
+ export type Dial = { id: string; path: string[]; inCode: ControlAudience };
94
+
95
+ /** A config as DialKit takes it (every `client()` unwrapped) and the dials in it. */
96
+ export function readConfig(panel: string, config: Config): { config: Config; dials: Dial[] } {
97
+ const dials: Dial[] = [];
98
+ const walk = (node: Config, path: string[], inherited: ControlAudience): Config => {
99
+ const out: Config = {};
100
+ for (const [key, raw] of Object.entries(node)) {
101
+ if (key === SETTING) {
102
+ out[key] = raw;
103
+ continue;
104
+ }
105
+ const inCode: ControlAudience = isMarked(raw) ? 'client' : inherited;
106
+ const value = isMarked(raw) ? raw.__client : raw;
107
+ const at = [...path, key];
108
+ if (isFolder(value)) out[key] = walk(value, at, inCode);
109
+ else {
110
+ out[key] = value;
111
+ dials.push({ id: dialId(panel, at), path: at, inCode });
112
+ }
113
+ }
114
+ return out;
115
+ };
116
+ return { config: walk(config, [], 'internal'), dials };
117
+ }
118
+
119
+ /** The part of an unwrapped config whose dials `shown` keeps. A folder with none left goes with them. */
120
+ export function keepDials(panel: string, config: Config, shown: (id: string) => boolean): Config {
121
+ const walk = (node: Config, path: string[]): Config => {
122
+ const out: Config = {};
123
+ for (const [key, value] of Object.entries(node)) {
124
+ if (key === SETTING) continue;
125
+ const at = [...path, key];
126
+ if (isFolder(value)) {
127
+ const inner = walk(value, at);
128
+ if (Object.keys(inner).length)
129
+ out[key] = SETTING in value ? { ...inner, [SETTING]: value[SETTING] } : inner;
130
+ } else if (shown(dialId(panel, at))) out[key] = value;
131
+ }
132
+ return out;
133
+ };
134
+ return walk(config, []);
135
+ }
136
+
137
+ const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
138
+ const clamp = (v: number, min: number, max: number) => Math.max(min, Math.min(max, v));
139
+
140
+ /** A slider's starting value: its first number, kept inside a range that is given. */
141
+ function sliderDefault(value: readonly unknown[]): number {
142
+ const seed = finite(value[0]) ? value[0] : 0;
143
+ if (!finite(value[1]) || !finite(value[2])) return seed;
144
+ const [min, max] = value[1] <= value[2] ? [value[1], value[2]] : [value[2], value[1]];
145
+ return clamp(seed, min, min === max ? min + 1 : max);
146
+ }
147
+
148
+ const firstOption = (options: unknown): unknown => {
149
+ const first = Array.isArray(options) ? options[0] : undefined;
150
+ if (first === undefined) return '';
151
+ return typeof first === 'string' ? first : (first as { value: unknown }).value;
152
+ };
153
+
154
+ /** One axis of a pad: `[default, min, max, step?]`, the default snapped to the step as DialKit snaps it. */
155
+ function padAxis(axis: unknown): number {
156
+ const [initial, min, max, given] = (Array.isArray(axis) ? axis : [0, -1, 1, 0.01]) as number[];
157
+ const step = given ?? (max - min) / 200;
158
+ const at = clamp(initial, min, max);
159
+ if (at === min || at === max) return at;
160
+ return clamp(Number((min + Math.round((at - min) / step) * step).toPrecision(12)), min, max);
161
+ }
162
+
163
+ /** By `type`: what DialKit starts each kind of dial at when its config names no default. */
164
+ const TYPED: Record<string, (v: Config) => unknown> = {
165
+ select: (v) => v.default ?? firstOption(v.options),
166
+ color: (v) => v.default ?? '#000000',
167
+ image: (v) => v.default ?? firstOption(v.options ?? []),
168
+ text: (v) => v.default ?? '',
169
+ pad: (v) => ({ x: padAxis(v.x), y: padAxis(v.y) }),
170
+ };
171
+
172
+ /**
173
+ * What a dial reads when nobody can move it: the value DialKit would start it
174
+ * at. A test holds this equal to DialKit's own for every kind of dial.
175
+ */
176
+ export function defaultOf(dial: unknown): unknown {
177
+ if (Array.isArray(dial)) return sliderDefault(dial);
178
+ if (!isRecord(dial) || typeof dial.type !== 'string') return dial;
179
+ const typed = TYPED[dial.type];
180
+ return typed ? typed(dial) : dial;
181
+ }
182
+
183
+ /**
184
+ * The values a prototype reads: DialKit's for the dials it drew, the default
185
+ * for every dial it did not, in the shape of the whole config.
186
+ */
187
+ export function withDefaults(config: Config, values: Config): Config {
188
+ const out: Config = {};
189
+ for (const [key, dial] of Object.entries(config)) {
190
+ if (key === SETTING) continue;
191
+ if (isFolder(dial)) out[key] = withDefaults(dial, isRecord(values[key]) ? values[key] : {});
192
+ else out[key] = key in values ? values[key] : defaultOf(dial);
193
+ }
194
+ return out;
195
+ }
@@ -0,0 +1,76 @@
1
+ import assert from 'node:assert/strict';
2
+ import { test } from 'node:test';
3
+ import { buildPrefix, clientPrefix, filePath, isBuildId, memoryFiles, typeOf } from './files.ts';
4
+
5
+ const A = { client: 'acme', project: 'rebrand' };
6
+ const BUILD = 'k3f9q2x7m1z8c4v6';
7
+
8
+ test('a file’s path is its client’s, its project’s and its build’s, from checked parts only', () => {
9
+ assert.equal(buildPrefix(A, BUILD), `c/acme/rebrand/${BUILD}/`);
10
+ // A client's own folder ends in a slash, so it never takes in acme-co's.
11
+ assert.equal(clientPrefix('acme'), 'c/acme/');
12
+ assert.ok(buildPrefix(A, BUILD).startsWith(clientPrefix('acme')));
13
+ assert.equal(filePath(A, BUILD, ['_p', 'plan', 'entry.js']), `c/acme/rebrand/${BUILD}/_p/plan/entry.js`);
14
+ assert.equal(filePath(A, BUILD, ['caf é.png']), `c/acme/rebrand/${BUILD}/caf é.png`);
15
+ // The names a build emits: hashed, dotted, dashed and underscored, and what a person names an image.
16
+ for (const name of [
17
+ 'Notice-B7Z_eR-a.css',
18
+ 'sample-social-BhnQuwv-.js',
19
+ 'geist-latin-wght-normal-BgDaEnEv.woff2',
20
+ 'logo@2x.png',
21
+ 'Q&A (v2), final+1.png',
22
+ ])
23
+ assert.equal(filePath(A, BUILD, ['assets', name]), `c/acme/rebrand/${BUILD}/assets/${name}`);
24
+ const bad: [string, () => string][] = [
25
+ ['a client that is reserved', () => buildPrefix({ client: 'studio', project: 'rebrand' }, BUILD)],
26
+ ['a client folder for a reserved name', () => clientPrefix('www')],
27
+ ['a client folder for no slug', () => clientPrefix('')],
28
+ ['a client folder with a slash', () => clientPrefix('acme/../bravo')],
29
+ ['no project', () => buildPrefix({ client: 'acme' }, BUILD)],
30
+ ['a project with a slash', () => buildPrefix({ client: 'acme', project: 'a/b' }, BUILD)],
31
+ ['a short build', () => buildPrefix(A, 'b1')],
32
+ ['a build with a slash', () => buildPrefix(A, `${BUILD}/x`)],
33
+ ['no file', () => filePath(A, BUILD, [])],
34
+ ['a .. segment', () => filePath(A, BUILD, ['..', 'other', 'x.js'])],
35
+ ['an empty segment', () => filePath(A, BUILD, ['assets', '', 'x.js'])],
36
+ ['a slash in a segment', () => filePath(A, BUILD, ['a/../../b'])],
37
+ ['a backslash', () => filePath(A, BUILD, ['a\\\\b'])],
38
+ ['a tab a URL parser drops', () => filePath(A, BUILD, ['.\t.', 'other', 'x.js'])],
39
+ ['a newline', () => filePath(A, BUILD, ['.\n.', 'x.js'])],
40
+ ['a carriage return', () => filePath(A, BUILD, ['.\r.', 'x.js'])],
41
+ ['a ? that cuts the URL', () => filePath(A, BUILD, ['x.js?y'])],
42
+ ['a # that cuts the URL', () => filePath(A, BUILD, ['x.js#y'])],
43
+ ['a % left in a name', () => filePath(A, BUILD, ['%2e%2e', 'x.js'])],
44
+ ['a space at an end', () => filePath(A, BUILD, ['x.js '])],
45
+ ];
46
+ for (const [what, build] of bad) assert.throws(build, /Not a file path/, what);
47
+ assert.equal(isBuildId(BUILD), true);
48
+ for (const id of ['', 'b1', 'A'.repeat(16), 'a'.repeat(65), 7])
49
+ assert.equal(isBuildId(id), false, String(id));
50
+ });
51
+
52
+ test('a file is stored with the type its name says', () => {
53
+ assert.equal(typeOf('index.html'), 'text/html; charset=utf-8');
54
+ assert.equal(typeOf('_p/x/entry.js'), 'text/javascript; charset=utf-8');
55
+ assert.equal(typeOf('_gate/geist.WOFF2'), 'font/woff2');
56
+ assert.equal(typeOf('assets/brand.ttf'), 'font/ttf');
57
+ assert.equal(typeOf('assets/brand.otf'), 'font/otf');
58
+ assert.equal(typeOf('assets/brief.pdf'), 'application/pdf');
59
+ assert.equal(typeOf('sitemap.xml'), 'application/xml');
60
+ assert.equal(typeOf('site.webmanifest'), 'application/manifest+json');
61
+ assert.equal(typeOf('LICENSE'), 'application/octet-stream');
62
+ assert.equal(typeOf('x.constructor'), 'application/octet-stream');
63
+ });
64
+
65
+ test('the in-memory store keeps what is put, never overwrites, and lists by prefix', async () => {
66
+ const files = memoryFiles();
67
+ const bytes = new TextEncoder().encode('hello');
68
+ await files.put('c/acme/a/1', bytes, 'text/plain');
69
+ await files.put('c/acme-co/a/1', bytes, 'text/plain');
70
+ await assert.rejects(files.put('c/acme/a/1', bytes, 'text/plain'), /never overwritten/);
71
+ assert.deepEqual(await files.get('c/acme/a/1'), { body: bytes, type: 'text/plain' });
72
+ assert.equal(await files.get('c/acme/a/2'), null);
73
+ assert.deepEqual(await files.list('c/acme/'), ['c/acme/a/1']);
74
+ await files.remove(['c/acme/a/1', 'c/acme/none']);
75
+ assert.deepEqual(await files.list('c/'), ['c/acme-co/a/1']);
76
+ });