@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
@@ -0,0 +1,91 @@
1
+ import assert from 'node:assert/strict';
2
+ import { test } from 'node:test';
3
+ import type { Scope } from './model.ts';
4
+ import { keyOf, sweepPrefix } from './store.ts';
5
+
6
+ const A: Scope = { client: 'acme', project: 'rebrand' };
7
+
8
+ test('keys: the studio’s, a client’s and a project’s, each under hub4:', () => {
9
+ assert.equal(keyOf('studio', 'people'), 'hub4:studio:people');
10
+ assert.equal(keyOf('studio', 'settings'), 'hub4:studio:settings');
11
+ assert.equal(keyOf(A, 'people'), 'hub4:c:acme:people');
12
+ assert.equal(keyOf({ client: 'acme' }, 'links'), 'hub4:c:acme:links');
13
+ assert.equal(keyOf(A, 'audiences'), 'hub4:c:acme:p:rebrand:audiences');
14
+ assert.equal(keyOf(A, 'prototypes'), 'hub4:c:acme:p:rebrand:prototypes');
15
+ assert.equal(keyOf(A, 'comments', 'sample-list'), 'hub4:c:acme:p:rebrand:comments:sample-list');
16
+ assert.equal(keyOf(A, 'controls', 'sample-list'), 'hub4:c:acme:p:rebrand:controls:sample-list');
17
+ // A reserved prototype name is read like any other, and finds nothing.
18
+ assert.equal(keyOf(A, 'comments', 'guide'), 'hub4:c:acme:p:rebrand:comments:guide');
19
+ });
20
+
21
+ test('a key is never built from a part that could reach another scope’s keys', () => {
22
+ const bad: [string, () => string][] = [
23
+ ['a client with a colon', () => keyOf({ client: 'acme:p:x' }, 'people')],
24
+ ['an empty client', () => keyOf({ client: '' }, 'people')],
25
+ ['the studio’s host as a client', () => keyOf({ client: 'studio' }, 'people')],
26
+ ['a reserved client', () => keyOf({ client: 'www' }, 'people')],
27
+ ['a project op with no project', () => keyOf({ client: 'acme' }, 'audiences')],
28
+ ['a project with a colon', () => keyOf({ client: 'acme', project: 'a:b' }, 'counters')],
29
+ ['a reserved project', () => keyOf({ client: 'acme', project: 'invite' }, 'counters')],
30
+ ['a prototype with a colon', () => keyOf(A, 'comments', 'x:y')],
31
+ ['no prototype', () => keyOf(A, 'controls', undefined as unknown as string)],
32
+ ['a client that is not text', () => keyOf({ client: 3 as unknown as string }, 'people')],
33
+ ];
34
+ for (const [what, build] of bad) assert.throws(build, /Not a store key/, what);
35
+ });
36
+
37
+ test('a sweep prefix holds every key of its scope and no other scope’s, the studio’s or the local store’s', () => {
38
+ const acme = sweepPrefix({ client: 'acme' });
39
+ const rebrand = sweepPrefix(A);
40
+ assert.equal(acme, 'hub4:c:acme:');
41
+ assert.equal(rebrand, 'hub4:c:acme:p:rebrand:');
42
+ const ofProject = (s: Scope) => [
43
+ keyOf(s, 'audiences'),
44
+ keyOf(s, 'counters'),
45
+ keyOf(s, 'prototypes'),
46
+ keyOf(s, 'comments', 'sample-list'),
47
+ keyOf(s, 'controls', 'sample-list'),
48
+ ];
49
+ const ofClient = (s: Scope) => [
50
+ ...(['people', 'revoked', 'epochs', 'links'] as const).map((n) => keyOf(s, n)),
51
+ keyOf(s, 'projects'),
52
+ keyOf(s, 'proof'),
53
+ ...ofProject(s),
54
+ ];
55
+ const studio = (
56
+ [
57
+ 'people',
58
+ 'revoked',
59
+ 'epochs',
60
+ 'links',
61
+ 'settings',
62
+ 'mark',
63
+ 'clients',
64
+ 'hosts',
65
+ 'claims',
66
+ 'held',
67
+ ] as const
68
+ ).map((n) => keyOf('studio', n));
69
+ for (const key of ofClient(A)) assert.ok(key.startsWith(acme), key);
70
+ for (const key of ofProject(A)) assert.ok(key.startsWith(rebrand), key);
71
+ // acme never reaches acme-two or acm, nor rebrand reaches rebrand-two; no client reaches the studio's keys.
72
+ const notAcme = [
73
+ ...ofClient({ client: 'acme-two', project: 'rebrand' }),
74
+ ...ofClient({ client: 'acm', project: 'rebrand' }),
75
+ ...ofClient({ client: 'site', project: 'site' }),
76
+ ...studio,
77
+ ];
78
+ for (const key of notAcme) assert.ok(!key.startsWith(acme), key);
79
+ for (const key of ofProject({ client: 'acme', project: 'rebrand-two' }))
80
+ assert.ok(!key.startsWith(rebrand), key);
81
+ // The local store's records are this machine's own: no prefix is ever built to sweep them.
82
+ assert.throws(() => sweepPrefix({ client: 'site' }), /local store/);
83
+ assert.throws(() => sweepPrefix({ client: 'site', project: 'site' }), /local store/);
84
+ for (const bad of [
85
+ { client: 'acme:p:x' },
86
+ { client: '' },
87
+ { client: 'studio' },
88
+ { client: 'acme', project: 'a:b' },
89
+ ])
90
+ assert.throws(() => sweepPrefix(bad), /Not a store key/, JSON.stringify(bad));
91
+ });
@@ -2,17 +2,34 @@
2
2
  // and set operations. Production is Upstash Redis over REST
3
3
  // (server/upstash.ts); dev and tests use the in-memory store below, which
4
4
  // the dev server persists to a file (server/file-kv.ts).
5
+ import { SLUG } from '../feature.ts';
6
+ import { isClientSlug, isProjectSlug } from '../prototype.ts';
7
+ import { LOCAL_CLIENT, type Scope } from './model.ts';
8
+
9
+ /** A comment's or a control's prototype: any kebab-case name, so reading one that is reserved finds nothing, as before. */
10
+ const isKebab = (v: unknown): v is string => typeof v === 'string' && SLUG.test(v);
5
11
 
6
12
  export interface KV {
7
13
  hget(key: string, field: string): Promise<string | null>;
8
14
  hset(key: string, field: string, value: string): Promise<void>;
9
15
  /** How many fields it removed: 1, or 0 when the field was not there. Atomic, so it can claim a record. */
10
16
  hdel(key: string, field: string): Promise<number>;
17
+ /** Sets a field only when it is not there: true when this call set it. Atomic, so of two at once one claims it. */
18
+ hsetnx(key: string, field: string, value: string): Promise<boolean>;
11
19
  hgetall(key: string): Promise<Record<string, string>>;
12
20
  /** Adds `by` to a field's integer (absent is 0) and returns the result. Atomic: two calls always add both. */
13
21
  hincrby(key: string, field: string, by: number): Promise<number>;
14
22
  sadd(key: string, member: string): Promise<void>;
15
23
  smembers(key: string): Promise<string[]>;
24
+ /** Removes a whole key, a hash or a set; one that is not there is no error. */
25
+ del(key: string): Promise<void>;
26
+ /**
27
+ * Removes every key, hash or set, whose name starts with `prefix`, taken as
28
+ * plain text (no character in it is a pattern); none is no error. Not one
29
+ * atomic step: a key written while it runs may stay. Redis: SCAN … MATCH,
30
+ * then DEL; Postgres: DELETE … WHERE key LIKE, the prefix escaped.
31
+ */
32
+ delPrefix(prefix: string): Promise<void>;
16
33
  }
17
34
 
18
35
  /**
@@ -20,33 +37,115 @@ export interface KV {
20
37
  * another app's data. Bumped when the stored shapes change without a
21
38
  * migration: records under an older prefix are simply never read.
22
39
  */
23
- const PREFIX = 'hub3:';
40
+ const PREFIX = 'hub4:';
24
41
 
25
- export const KEY = {
26
- /** A person's profile: everything but revocation and epoch, which nothing here can overwrite. */
27
- people: `${PREFIX}people`,
28
- /** When a person was revoked. Written once by revoke, never cleared. */
29
- revoked: `${PREFIX}revoked`,
30
- /** A person's session epoch, only ever raised, by HINCRBY. Absent is 0. */
31
- epochs: `${PREFIX}epochs`,
32
- /** One-time sign-in links: hex(sha256(token)) to a Link. */
33
- links: `${PREFIX}links`,
34
- /** Project settings, one field each: `access` is the default access length. */
35
- settings: `${PREFIX}settings`,
36
- prototypes: `${PREFIX}prototypes`,
37
- /**
38
- * Which prototypes are client-facing: field `<slug>`, value `client`. Only
39
- * client-facing is stored; internal is the field's absence, and any other
40
- * value reads as internal too.
41
- */
42
- audiences: `${PREFIX}audiences`,
43
- /**
44
- * The last thread number given on each prototype, only ever raised by HINCRBY: field
45
- * `<prototype>` counts client-facing threads, `<prototype>:internal` internal ones.
46
- */
47
- counters: `${PREFIX}counters`,
48
- comments: (prototype: string) => `${PREFIX}comments:${prototype}`,
49
- } as const;
42
+ /**
43
+ * The studio's own records: Studio people (profile, revocation, epoch and
44
+ * links, as a client's below) and `settings`, one field each: `access` is the
45
+ * default access length. `mark`, one field, `id`: the id of the one studio
46
+ * this database serves (its studio.json `id`), set once by `studio create`
47
+ * and checked by every command before it acts (server/mark.ts). No other
48
+ * key names a studio, so two studios on one database would be one studio.
49
+ */
50
+ type StudioName = 'people' | 'revoked' | 'epochs' | 'links' | 'settings' | 'mark';
51
+
52
+ /**
53
+ * The studio's clients, outside every scope: `clients`, a client's slug to
54
+ * its Client; `hosts`, a host name to the slug of the client it serves;
55
+ * `claims`, one counter per slug (`client:<slug>`) and per host
56
+ * (`host:<host>`), raised by HINCRBY when a client is added: whoever raised
57
+ * it to 1 holds it, so two adds at once never both get one. Archiving a
58
+ * client deletes its fields, so the slug and the host can be claimed again.
59
+ * `held`, the same fields, each the time a client that had it was archived:
60
+ * neither is added again until every gate's cached answer for the host has
61
+ * surely run out (REUSE_SECONDS in service.ts).
62
+ */
63
+ type DirectoryName = 'clients' | 'hosts' | 'claims' | 'held';
64
+ const DIRECTORY: readonly string[] = ['clients', 'hosts', 'claims', 'held'];
65
+
66
+ /**
67
+ * A client's people, in four records. `people`: a profile, everything but
68
+ * revocation and epoch, which nothing here can overwrite. `revoked`: when a
69
+ * person was revoked, written once by revoke, never cleared. `epochs`: a
70
+ * person's session epoch, only ever raised, by HINCRBY; absent is 0.
71
+ * `links`: one-time sign-in links, hex(sha256(token)) to a Link. And
72
+ * `projects`: the client's projects, a slug to its Project. `proof`: while
73
+ * `client add` waits for the client's host, one field, hex(sha256(ask)) to
74
+ * the answer the gate gives for that ask (PROOF_PATH in prototype.ts).
75
+ */
76
+ type ClientName = 'people' | 'revoked' | 'epochs' | 'links';
77
+ type ClientOnlyName = 'projects' | 'proof';
78
+
79
+ /**
80
+ * A project's records. `audiences`: which prototypes are client-facing,
81
+ * field `<slug>`, value `client`; only client-facing is stored, internal is
82
+ * the field's absence, and any other value reads as internal too.
83
+ * `counters`: the last thread number given on each prototype, only ever
84
+ * raised by HINCRBY: field `<prototype>` counts client-facing threads,
85
+ * `<prototype>:internal` internal ones. `prototypes`: the set of prototypes
86
+ * with comments. `comments`, per prototype: one field per comment.
87
+ * `controls`, per prototype: what Studio marked on its controls
88
+ * (core/controls.ts): field `dial:<id>` is `client` or `internal`, overruling
89
+ * the code either way; field `variant:<name>` is `client`, and internal is
90
+ * its absence. One field per control, so two people marking at once never
91
+ * undo each other. `builds`: every build a share started for the project,
92
+ * field `<build>` to `{ n, live }`: `n` is the order it was started in, from
93
+ * field `next` (HINCRBY), and `live` whether the project ever pointed at it
94
+ * (startBuild and setBuild in service.ts).
95
+ */
96
+ type ProjectName = 'audiences' | 'counters' | 'prototypes' | 'builds';
97
+ type PrototypeName = 'comments' | 'controls';
98
+
99
+ const PROJECT_NAMES: readonly string[] = [
100
+ 'audiences',
101
+ 'counters',
102
+ 'prototypes',
103
+ 'builds',
104
+ 'comments',
105
+ 'controls',
106
+ ];
107
+ const PER_PROTOTYPE: readonly string[] = ['comments', 'controls'];
108
+
109
+ function part(ok: (v: unknown) => v is string, v: unknown, what: string): string {
110
+ // A bad part is a bug in the caller, never input to answer: fail closed before any store call.
111
+ if (!ok(v)) throw new Error(`Not a store key: ${what} is ${JSON.stringify(v)}.`);
112
+ return v;
113
+ }
114
+
115
+ const clientPrefix = (client: unknown) => `${PREFIX}c:${part(isClientSlug, client, 'client')}:`;
116
+ const projectPrefix = (scope: Scope) =>
117
+ `${clientPrefix(scope.client)}p:${part(isProjectSlug, scope.project, 'project')}:`;
118
+
119
+ /**
120
+ * Every store key, and the only place one is built. `'studio'` names the
121
+ * studio's own records; a Scope names its client's, and its project's for a
122
+ * project name. Every part is checked (a client slug, a project slug, a
123
+ * kebab-case prototype), so no value can reach into another client's keys:
124
+ * no part can hold the `:` that joins them.
125
+ */
126
+ export function keyOf(scope: 'studio', name: StudioName | DirectoryName): string;
127
+ export function keyOf(scope: 'studio' | Scope, name: ClientName): string;
128
+ export function keyOf(scope: Scope, name: ClientOnlyName | ProjectName): string;
129
+ export function keyOf(scope: Scope, name: PrototypeName, prototype: string): string;
130
+ export function keyOf(scope: 'studio' | Scope, name: string, prototype?: string): string {
131
+ if (scope === 'studio') return DIRECTORY.includes(name) ? `${PREFIX}${name}` : `${PREFIX}studio:${name}`;
132
+ if (!PROJECT_NAMES.includes(name)) return `${clientPrefix(scope.client)}${name}`;
133
+ const project = `${projectPrefix(scope)}${name}`;
134
+ return PER_PROTOTYPE.includes(name) ? `${project}:${part(isKebab, prototype, 'prototype')}` : project;
135
+ }
136
+
137
+ /**
138
+ * What every key of a client starts with, or of one of its projects when the
139
+ * scope names one: what `delPrefix` takes to sweep that scope clean, whatever
140
+ * index names its keys or not. Built by the parts keyOf builds keys from, and
141
+ * ending in the `:` no part can hold, so `acme` never reaches `acme-two` and
142
+ * no client reaches the studio's keys. Never the local store's client: its
143
+ * records are this machine's own, and nothing archives or reuses it.
144
+ */
145
+ export function sweepPrefix(scope: Scope): string {
146
+ if (scope.client === LOCAL_CLIENT) throw new Error('Not a scope to sweep: the local store’s records stay.');
147
+ return scope.project === undefined ? clientPrefix(scope.client) : projectPrefix(scope);
148
+ }
50
149
 
51
150
  export type Snapshot = { hashes: Record<string, Record<string, string>>; sets: Record<string, string[]> };
52
151
 
@@ -70,6 +169,12 @@ export function memoryKV(initial: Snapshot = { hashes: {}, sets: {} }, onChange?
70
169
  changed();
71
170
  return 1;
72
171
  },
172
+ hsetnx: async (key, field, value) => {
173
+ if (hashes.get(key)?.has(field)) return false;
174
+ hash(key).set(field, value);
175
+ changed();
176
+ return true;
177
+ },
73
178
  hgetall: async (key) => Object.fromEntries(hashes.get(key) ?? []),
74
179
  hincrby: async (key, field, by) => {
75
180
  const n = Number(hash(key).get(field) ?? 0) + by;
@@ -82,5 +187,17 @@ export function memoryKV(initial: Snapshot = { hashes: {}, sets: {} }, onChange?
82
187
  changed();
83
188
  },
84
189
  smembers: async (key) => [...(sets.get(key) ?? [])],
190
+ del: async (key) => {
191
+ const had = hashes.delete(key);
192
+ if (sets.delete(key) || had) changed();
193
+ },
194
+ delPrefix: async (prefix) => {
195
+ const gone = [...hashes.keys(), ...sets.keys()].filter((k) => k.startsWith(prefix));
196
+ for (const key of gone) {
197
+ hashes.delete(key);
198
+ sets.delete(key);
199
+ }
200
+ if (gone.length) changed();
201
+ },
85
202
  };
86
203
  }
@@ -0,0 +1,55 @@
1
+ export type ControlAudience = 'internal' | 'client';
2
+ export declare const CONTROL_KINDS: readonly ['dial', 'variant'];
3
+ export type ControlKind = (typeof CONTROL_KINDS)[number];
4
+ /** What the hub stored for one prototype: a mark per dial Studio switched, and the variants a Client gets. */
5
+ export type Marks = {
6
+ dials: Record<string, ControlAudience>;
7
+ variants: string[];
8
+ };
9
+ export declare const NO_MARKS: Marks;
10
+ /** A dial's or a variant's name as the store keeps it: one line of text, trimmed, at most 200 characters. */
11
+ export declare const isControlId: (v: unknown) => v is string;
12
+ /** 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`. */
13
+ export declare const dialId: (panel: string, path: readonly string[]) => string;
14
+ /** The store's field for one control. */
15
+ export declare const controlField: (kind: ControlKind, id: string) => string;
16
+ /** 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. */
17
+ export declare function readMarks(fields: Record<string, string>): Marks;
18
+ /** The marks after one control is switched. */
19
+ export declare function withMark(marks: Marks, kind: ControlKind, id: string, audience: ControlAudience): Marks;
20
+ /** Who a dial is for: the hub's mark when Studio set one, else what the code says, else internal. */
21
+ export declare const dialAudience: (marks: Marks, id: string, inCode: ControlAudience) => ControlAudience;
22
+ /**
23
+ * The variants a Client gets, in the order the prototype declares them. One
24
+ * is no picker. None marked is still one: the first, so a page is never empty.
25
+ */
26
+ export declare function clientVariants(names: readonly string[], marks: Marks): string[];
27
+ type Config = Record<string, unknown>;
28
+ /**
29
+ * Marks a dial client-facing where it is declared, or a folder and every dial
30
+ * in it. Typed as the dial itself, so the values a prototype reads keep their types.
31
+ */
32
+ export declare const client: <T>(dial: T) => T;
33
+ export type Dial = {
34
+ id: string;
35
+ path: string[];
36
+ inCode: ControlAudience;
37
+ };
38
+ /** A config as DialKit takes it (every `client()` unwrapped) and the dials in it. */
39
+ export declare function readConfig(panel: string, config: Config): {
40
+ config: Config;
41
+ dials: Dial[];
42
+ };
43
+ /** The part of an unwrapped config whose dials `shown` keeps. A folder with none left goes with them. */
44
+ export declare function keepDials(panel: string, config: Config, shown: (id: string) => boolean): Config;
45
+ /**
46
+ * What a dial reads when nobody can move it: the value DialKit would start it
47
+ * at. A test holds this equal to DialKit's own for every kind of dial.
48
+ */
49
+ export declare function defaultOf(dial: unknown): unknown;
50
+ /**
51
+ * The values a prototype reads: DialKit's for the dials it drew, the default
52
+ * for every dial it did not, in the shape of the whole config.
53
+ */
54
+ export declare function withDefaults(config: Config, values: Config): Config;
55
+ export {};
@@ -0,0 +1,174 @@
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
+ export const CONTROL_KINDS = ['dial', 'variant'];
14
+ export const NO_MARKS = { dials: {}, variants: [] };
15
+ const MAX_ID = 200;
16
+ /** A dial's or a variant's name as the store keeps it: one line of text, trimmed, at most 200 characters. */
17
+ export const isControlId = (v) => typeof v === 'string' &&
18
+ v.length > 0 &&
19
+ v.length <= MAX_ID &&
20
+ v.trim() === v &&
21
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what is refused
22
+ !/[\u0000-\u001f\u007f]/.test(v);
23
+ /** 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`. */
24
+ export const dialId = (panel, path) => `${panel}/${path.join('.')}`;
25
+ /** The store's field for one control. */
26
+ export const controlField = (kind, id) => `${kind}:${id}`;
27
+ /** 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. */
28
+ export function readMarks(fields) {
29
+ const dials = {};
30
+ const variants = [];
31
+ for (const [field, value] of Object.entries(fields)) {
32
+ const at = field.indexOf(':');
33
+ const [kind, id] = [field.slice(0, at), field.slice(at + 1)];
34
+ if (!isControlId(id))
35
+ continue;
36
+ if (kind === 'dial' && (value === 'client' || value === 'internal'))
37
+ dials[id] = value;
38
+ if (kind === 'variant' && value === 'client')
39
+ variants.push(id);
40
+ }
41
+ return { dials, variants: variants.sort() };
42
+ }
43
+ /** The marks after one control is switched. */
44
+ export function withMark(marks, kind, id, audience) {
45
+ if (kind === 'dial')
46
+ return { ...marks, dials: { ...marks.dials, [id]: audience } };
47
+ const rest = marks.variants.filter((v) => v !== id);
48
+ return { ...marks, variants: audience === 'client' ? [...rest, id].sort() : rest };
49
+ }
50
+ /** Who a dial is for: the hub's mark when Studio set one, else what the code says, else internal. */
51
+ export const dialAudience = (marks, id, inCode) => marks.dials[id] ?? inCode;
52
+ /**
53
+ * The variants a Client gets, in the order the prototype declares them. One
54
+ * is no picker. None marked is still one: the first, so a page is never empty.
55
+ */
56
+ export function clientVariants(names, marks) {
57
+ const kept = names.filter((n) => marks.variants.includes(n));
58
+ return kept.length ? kept : names.slice(0, 1);
59
+ }
60
+ const isRecord = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
61
+ const isMarked = (v) => isRecord(v) && '__client' in v;
62
+ const isFolder = (v) => isRecord(v) && !('type' in v);
63
+ /** DialKit's own key for a folder that starts closed: not a dial. */
64
+ const SETTING = '_collapsed';
65
+ /**
66
+ * Marks a dial client-facing where it is declared, or a folder and every dial
67
+ * in it. Typed as the dial itself, so the values a prototype reads keep their types.
68
+ */
69
+ export const client = (dial) => ({ __client: dial });
70
+ /** A config as DialKit takes it (every `client()` unwrapped) and the dials in it. */
71
+ export function readConfig(panel, config) {
72
+ const dials = [];
73
+ const walk = (node, path, inherited) => {
74
+ const out = {};
75
+ for (const [key, raw] of Object.entries(node)) {
76
+ if (key === SETTING) {
77
+ out[key] = raw;
78
+ continue;
79
+ }
80
+ const inCode = isMarked(raw) ? 'client' : inherited;
81
+ const value = isMarked(raw) ? raw.__client : raw;
82
+ const at = [...path, key];
83
+ if (isFolder(value))
84
+ out[key] = walk(value, at, inCode);
85
+ else {
86
+ out[key] = value;
87
+ dials.push({ id: dialId(panel, at), path: at, inCode });
88
+ }
89
+ }
90
+ return out;
91
+ };
92
+ return { config: walk(config, [], 'internal'), dials };
93
+ }
94
+ /** The part of an unwrapped config whose dials `shown` keeps. A folder with none left goes with them. */
95
+ export function keepDials(panel, config, shown) {
96
+ const walk = (node, path) => {
97
+ const out = {};
98
+ for (const [key, value] of Object.entries(node)) {
99
+ if (key === SETTING)
100
+ continue;
101
+ const at = [...path, key];
102
+ if (isFolder(value)) {
103
+ const inner = walk(value, at);
104
+ if (Object.keys(inner).length)
105
+ out[key] = SETTING in value ? { ...inner, [SETTING]: value[SETTING] } : inner;
106
+ }
107
+ else if (shown(dialId(panel, at)))
108
+ out[key] = value;
109
+ }
110
+ return out;
111
+ };
112
+ return walk(config, []);
113
+ }
114
+ const finite = (v) => typeof v === 'number' && Number.isFinite(v);
115
+ const clamp = (v, min, max) => Math.max(min, Math.min(max, v));
116
+ /** A slider's starting value: its first number, kept inside a range that is given. */
117
+ function sliderDefault(value) {
118
+ const seed = finite(value[0]) ? value[0] : 0;
119
+ if (!finite(value[1]) || !finite(value[2]))
120
+ return seed;
121
+ const [min, max] = value[1] <= value[2] ? [value[1], value[2]] : [value[2], value[1]];
122
+ return clamp(seed, min, min === max ? min + 1 : max);
123
+ }
124
+ const firstOption = (options) => {
125
+ const first = Array.isArray(options) ? options[0] : undefined;
126
+ if (first === undefined)
127
+ return '';
128
+ return typeof first === 'string' ? first : first.value;
129
+ };
130
+ /** One axis of a pad: `[default, min, max, step?]`, the default snapped to the step as DialKit snaps it. */
131
+ function padAxis(axis) {
132
+ const [initial, min, max, given] = (Array.isArray(axis) ? axis : [0, -1, 1, 0.01]);
133
+ const step = given ?? (max - min) / 200;
134
+ const at = clamp(initial, min, max);
135
+ if (at === min || at === max)
136
+ return at;
137
+ return clamp(Number((min + Math.round((at - min) / step) * step).toPrecision(12)), min, max);
138
+ }
139
+ /** By `type`: what DialKit starts each kind of dial at when its config names no default. */
140
+ const TYPED = {
141
+ select: (v) => v.default ?? firstOption(v.options),
142
+ color: (v) => v.default ?? '#000000',
143
+ image: (v) => v.default ?? firstOption(v.options ?? []),
144
+ text: (v) => v.default ?? '',
145
+ pad: (v) => ({ x: padAxis(v.x), y: padAxis(v.y) }),
146
+ };
147
+ /**
148
+ * What a dial reads when nobody can move it: the value DialKit would start it
149
+ * at. A test holds this equal to DialKit's own for every kind of dial.
150
+ */
151
+ export function defaultOf(dial) {
152
+ if (Array.isArray(dial))
153
+ return sliderDefault(dial);
154
+ if (!isRecord(dial) || typeof dial.type !== 'string')
155
+ return dial;
156
+ const typed = TYPED[dial.type];
157
+ return typed ? typed(dial) : dial;
158
+ }
159
+ /**
160
+ * The values a prototype reads: DialKit's for the dials it drew, the default
161
+ * for every dial it did not, in the shape of the whole config.
162
+ */
163
+ export function withDefaults(config, values) {
164
+ const out = {};
165
+ for (const [key, dial] of Object.entries(config)) {
166
+ if (key === SETTING)
167
+ continue;
168
+ if (isFolder(dial))
169
+ out[key] = withDefaults(dial, isRecord(values[key]) ? values[key] : {});
170
+ else
171
+ out[key] = key in values ? values[key] : defaultOf(dial);
172
+ }
173
+ return out;
174
+ }
@@ -0,0 +1,39 @@
1
+ import type { Scope } from './review/model.ts';
2
+ /** A file's bytes as the store hands them, and the type it was stored with. */
3
+ export type StoredFile = {
4
+ body: ReadableStream<Uint8Array> | Bytes;
5
+ type: string;
6
+ };
7
+ type Bytes = Uint8Array<ArrayBuffer>;
8
+ export interface Files {
9
+ /** Writes a file that is not there yet. A build's paths are never overwritten. */
10
+ put(path: string, body: Bytes, type: string): Promise<void>;
11
+ /** The file and its type, or null when there is none. */
12
+ get(path: string): Promise<StoredFile | null>;
13
+ /** Every path that starts with `prefix`. A scope's prefix ends in `/`, so `c/acme/` never lists `c/acme-co/`. */
14
+ list(prefix: string): Promise<string[]>;
15
+ /** Removes these paths; one that is not there is no error. */
16
+ remove(paths: string[]): Promise<void>;
17
+ }
18
+ export declare const isBuildId: (v: unknown) => v is string;
19
+ /**
20
+ * Removes every file under a prefix, in the store's batches of 1,000, and
21
+ * says how many there were. Takes a prefix one of the functions below built,
22
+ * so it never reaches past its scope.
23
+ */
24
+ export declare function clearPrefix(files: Files, prefix: string): Promise<number>;
25
+ /** Removes these paths, in the store's batches of 1,000. */
26
+ export declare function removeAll(files: Files, paths: string[]): Promise<void>;
27
+ /** Every file of one client, every project and build: what archiving the client removes. Ends in `/`. */
28
+ export declare function clientPrefix(client: string): string;
29
+ /** Every build of one project, ending in `/`, so `c/acme/rebrand/` never lists `c/acme/rebrand-2/`. */
30
+ export declare function projectPrefix(scope: Scope): string;
31
+ /** The folder of one build of a project, ending in `/`. */
32
+ export declare function buildPrefix(scope: Scope, build: string): string;
33
+ /** One file of one build: `c/<client>/<project>/<build>/<file>`, with `file` given as its segments. */
34
+ export declare function filePath(scope: Scope, build: string, file: readonly string[]): string;
35
+ /** The type a built file is stored with, from its extension. */
36
+ export declare function typeOf(path: string): string;
37
+ /** The files port in memory, for tests and for a studio run on one machine. */
38
+ export declare function memoryFiles(): Files;
39
+ export {};