@milesroxas/design-hub 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +7 -2
  2. package/core/prototype.test.ts +83 -0
  3. package/core/prototype.ts +84 -0
  4. package/core/review/model.ts +20 -2
  5. package/core/review/policy.test.ts +4 -2
  6. package/core/review/policy.ts +4 -2
  7. package/core/review/service.test.ts +200 -16
  8. package/core/review/service.ts +91 -5
  9. package/core/review/store.ts +10 -1
  10. package/dist/core/prototype.d.ts +35 -0
  11. package/dist/core/prototype.js +84 -0
  12. package/dist/core/review/model.d.ts +13 -2
  13. package/dist/core/review/model.js +13 -0
  14. package/dist/core/review/policy.d.ts +1 -1
  15. package/dist/core/review/policy.js +1 -0
  16. package/dist/core/review/service.d.ts +24 -2
  17. package/dist/core/review/service.js +81 -6
  18. package/dist/core/review/store.d.ts +10 -1
  19. package/dist/core/review/store.js +10 -1
  20. package/dist/scripts/comments.js +4 -3
  21. package/dist/scripts/lib/cdp.js +6 -1
  22. package/dist/scripts/lib/export-smoke.d.ts +18 -0
  23. package/dist/scripts/lib/export-smoke.js +73 -0
  24. package/dist/scripts/new.js +5 -2
  25. package/dist/scripts/release-check.d.ts +5 -3
  26. package/dist/scripts/release-check.js +17 -4
  27. package/dist/scripts/share.d.ts +2 -2
  28. package/dist/server/api.js +8 -0
  29. package/dist/server/session.d.ts +5 -1
  30. package/dist/server/session.js +39 -21
  31. package/dist/vercel/proxy.js +44 -8
  32. package/dist/vite/boundary.d.ts +93 -0
  33. package/dist/vite/boundary.js +218 -0
  34. package/dist/vite/css-boundary.d.ts +39 -0
  35. package/dist/vite/css-boundary.js +167 -0
  36. package/dist/vite/kit.js +15 -6
  37. package/dist/vite/leaks.d.ts +37 -0
  38. package/dist/vite/leaks.js +331 -0
  39. package/dist/vite/plugin.js +2 -1
  40. package/dist/vite/registry.d.ts +15 -4
  41. package/dist/vite/registry.js +531 -27
  42. package/dist/vite/settle.d.ts +27 -0
  43. package/dist/vite/settle.js +185 -0
  44. package/package.json +4 -3
  45. package/shell/ClientViewNote.tsx +18 -0
  46. package/shell/Guide.tsx +17 -2
  47. package/shell/Index.tsx +257 -25
  48. package/shell/audience.test.ts +63 -0
  49. package/shell/audience.ts +47 -0
  50. package/shell/hub.ts +36 -0
  51. package/shell/main.tsx +39 -5
  52. package/shell/registry.ts +28 -7
  53. package/shell/registry.virtual.d.ts +12 -4
  54. package/shell/review/Pins.tsx +8 -6
  55. package/shell/review/Review.tsx +8 -4
  56. package/shell/review/ThreadCard.tsx +6 -14
  57. package/shell/review/client.ts +16 -4
  58. package/shell/review/review.css +37 -24
  59. package/shell/shell.css +50 -3
  60. package/shell/system.css +5 -0
  61. package/skills/miles-deploy/SKILL.md +17 -0
  62. package/skills/miles-new-feature/SKILL.md +1 -1
  63. package/skills/miles-prototype/SKILL.md +14 -1
  64. package/skills/miles-review/SKILL.md +1 -1
@@ -1,13 +1,31 @@
1
1
  /// <reference types="node" />
2
2
  // `virtual:design-hub/registry`: the project's prototypes and walkthroughs as
3
3
  // a module the hub imports. The hub's own code lives in this package, so it
4
- // cannot glob the project; this plugin scans the project's folders instead
5
- // and writes the imports the browser index and the loader need, each on an
6
- // absolute path. A folder that appears or disappears invalidates the module
7
- // and reloads the page, so a new prototype shows without a restart.
4
+ // cannot glob the project; this plugin scans the project's folders instead.
5
+ //
6
+ // Each prototype is reached through its own entry module
7
+ // (`virtual:design-hub/entry/<slug>`): its README and a loader for its code.
8
+ // In a build each entry is its own file, `_p/<slug>/entry.js`, and every file
9
+ // built from the prototype lands beside it (vite/boundary.ts), so the gate
10
+ // refuses an internal prototype by path. The registry module then holds no
11
+ // slug at all: Studio's list of every slug is `_p/all.js`, which the gate
12
+ // never gives a Client, and an entry is fetched by its path. In dev there is
13
+ // no gate and the module keeps a map. A folder that appears or disappears
14
+ // invalidates the modules and reloads the page, so a new prototype shows
15
+ // without a restart.
16
+ import { createHash } from 'node:crypto';
8
17
  import { existsSync, readdirSync } from 'node:fs';
9
- import { join } from 'node:path';
18
+ import { basename, dirname, extname, join, resolve } from 'node:path';
19
+ import postcss, {} from 'postcss';
20
+ import { createIdResolver } from 'vite';
10
21
  import { SLUG } from '../core/feature.js';
22
+ import { ALL_FILE, entryFile, isPrototypeSlug, PROTOTYPE_DIR } from '../core/prototype.js';
23
+ import { PACKAGE, PACKAGE_KIT, SHELL } from '../server/paths.js';
24
+ import { crossImport, ENTRY_ID, fromRoot, looseFile, newUrlTargets, ownerOf, ownersOf, PREPROCESSED, placed, preprocessed, real, unreadable, workerRefused, } from './boundary.js';
25
+ import { cssBoundary, importRef, moduleRef } from './css-boundary.js';
26
+ import { kitResolver } from './kit.js';
27
+ import { leaks } from './leaks.js';
28
+ import { settle } from './settle.js';
11
29
  const REGISTRY_ID = 'virtual:design-hub/registry';
12
30
  const RESOLVED = `\0${REGISTRY_ID}`;
13
31
  const dirs = (parent) => existsSync(parent)
@@ -16,48 +34,532 @@ const dirs = (parent) => existsSync(parent)
16
34
  .map((d) => d.name)
17
35
  .sort()
18
36
  : [];
19
- /** The prototype folders: kebab-case, with a README. `guide` is the walkthrough route, never a prototype. */
20
- export const prototypeSlugs = (prototypes) => dirs(prototypes).filter((slug) => slug !== 'guide' && existsSync(join(prototypes, slug, 'README.md')));
37
+ /** The prototype folders: kebab-case, with a README, and never one of the hub's own paths (core/prototype.ts). */
38
+ export const prototypeSlugs = (prototypes) => dirs(prototypes).filter((slug) => isPrototypeSlug(slug) && existsSync(join(prototypes, slug, 'README.md')));
21
39
  /** The features with a walkthrough at docs/sprints/<feature>/guide.md. */
22
40
  export const guideFeatures = (sprints) => dirs(sprints).filter((feature) => existsSync(join(sprints, feature, 'guide.md')));
23
- const entry = (key, path, query = '') => ` ${JSON.stringify(key)}: () => import(${JSON.stringify(path + query)}),`;
24
- export function registrySource(root) {
25
- const prototypes = join(root, 'prototypes');
41
+ const lazy = (key, id) => ` ${JSON.stringify(key)}: () => import(${JSON.stringify(id)}),`;
42
+ /** One prototype's entry: its README text, and a loader for its code when it has an index.tsx. */
43
+ export function entrySource(root, slug) {
44
+ const dir = join(root, 'prototypes', slug);
45
+ const code = existsSync(join(dir, 'index.tsx'))
46
+ ? [`export const load = () => import(${JSON.stringify(join(dir, 'index.tsx'))});`]
47
+ : [];
48
+ return [
49
+ `export { default as readme } from ${JSON.stringify(`${join(dir, 'README.md')}?raw`)};`,
50
+ ...code,
51
+ '',
52
+ ].join('\n');
53
+ }
54
+ /** The package's own probe (core/prototype.ts), imported by the built registry. */
55
+ const PROBE = join(PACKAGE, 'core', 'prototype.ts');
56
+ /**
57
+ * The registry module: `allSlugs()` and `entryOf(slug)`, both async, and
58
+ * `guideDocs`. Served, a map of every entry. Built, no slug: `_p/all.js` and
59
+ * `_p/<slug>/entry.js` are fetched by path from `base`, so the gate decides
60
+ * who gets each.
61
+ */
62
+ export function registrySource(root, mode = 'serve', base = '/') {
26
63
  const sprints = join(root, 'docs', 'sprints');
27
- const slugs = prototypeSlugs(prototypes);
28
- const readmes = slugs.map((slug, i) => `import readme${i} from ${JSON.stringify(`${join(prototypes, slug, 'README.md')}?raw`)};`);
29
- const modules = slugs
30
- .filter((slug) => existsSync(join(prototypes, slug, 'index.tsx')))
31
- .map((slug) => entry(slug, join(prototypes, slug, 'index.tsx')));
32
- const guides = guideFeatures(sprints).map((feature) => entry(feature, join(sprints, feature, 'guide.md'), '?doc'));
64
+ const guides = guideFeatures(sprints).map((feature) => lazy(feature, `${join(sprints, feature, 'guide.md')}?doc`));
65
+ const guideDocs = `export const guideDocs = {\n${guides.join('\n')}\n};`;
66
+ if (mode === 'build')
67
+ return [
68
+ // A path in a variable, so Rolldown leaves the import to the browser.
69
+ 'const at = (path) => import(/* @vite-ignore */ path);',
70
+ `export const allSlugs = () => at(${JSON.stringify(base + ALL_FILE)}).then((m) => m.slugs);`,
71
+ // The gate answers 404 for a prototype this person may not open, and the host its page for one not built: neither is there.
72
+ `import { probeEntry } from ${JSON.stringify(PROBE)};`,
73
+ `const dir = ${JSON.stringify(`${base}${PROTOTYPE_DIR}/`)};`,
74
+ 'export const entryOf = async (slug) => {',
75
+ ' const path = dir + slug + "/entry.js";',
76
+ ' return (await probeEntry(path, fetch)) ? at(path) : null;',
77
+ '};',
78
+ guideDocs,
79
+ '',
80
+ ].join('\n');
81
+ const slugs = prototypeSlugs(join(root, 'prototypes'));
33
82
  return [
34
- ...readmes,
35
- `export const readmes = {\n${slugs.map((slug, i) => ` ${JSON.stringify(slug)}: readme${i},`).join('\n')}\n};`,
36
- `export const modules = {\n${modules.join('\n')}\n};`,
37
- `export const guideDocs = {\n${guides.join('\n')}\n};`,
83
+ `const entries = {\n${slugs.map((slug) => lazy(slug, ENTRY_ID + slug)).join('\n')}\n};`,
84
+ 'export const allSlugs = async () => Object.keys(entries);',
85
+ 'export const entryOf = async (slug) => (Object.hasOwn(entries, slug) ? entries[slug]() : null);',
86
+ guideDocs,
38
87
  '',
39
88
  ].join('\n');
40
89
  }
41
- const REGISTRY_FILE = /\/(README\.md|index\.tsx|guide\.md)$/;
90
+ /** The source of Studio's list of every slug, `_p/all.js`. */
91
+ export const allSource = (slugs) => `export const slugs = ${JSON.stringify(slugs)};\n`;
92
+ /** The hub's page: Vite's importer for every URL a browser asks for in dev, and for each entry. */
93
+ const HUB_HTML = join(SHELL, 'index.html');
94
+ /** A prototype's import of a sheet the hub itself loads, answered once the hub's graph is known. */
95
+ const HUB_SHEET = '\0design-hub-hub-sheet:';
96
+ /** Every module the hub's entry loads statically: on every page, before any prototype. */
97
+ async function hubGraph(ctx) {
98
+ const seen = new Set();
99
+ const stack = [join(SHELL, 'main.tsx')];
100
+ while (stack.length) {
101
+ const id = stack.pop();
102
+ if (seen.has(id))
103
+ continue;
104
+ seen.add(id);
105
+ const info = await ctx.load({ id, resolveDependencies: true });
106
+ stack.push(...info.importedIds);
107
+ }
108
+ return seen;
109
+ }
110
+ /**
111
+ * What is wrong with `importer` reaching `file`, or null: a file in
112
+ * prototypes/ outside any prototype's folder, or another owner's prototype
113
+ * file (for the kit and the hub, any prototype's). The registry's own virtual
114
+ * modules load prototypes by design.
115
+ */
116
+ function reachProblem(j, importer, file) {
117
+ const to = j.owner(file);
118
+ if (to === null)
119
+ return null;
120
+ if (!j.isPrototype(to))
121
+ return looseFile(j.root, importer, file);
122
+ const from = j.owner(importer);
123
+ if (from === to || (from === null && importer.startsWith('\0virtual:design-hub/')))
124
+ return null;
125
+ return crossImport(j.root, importer, file, from !== null);
126
+ }
127
+ const SCRIPT = /\.(m?[jt]sx?|vue|svelte)$/;
128
+ /** Vite's own test for a `?raw` import (`rawRE`): the file's text, never compiled. */
129
+ const RAW = /(\?|&)raw(?:&|$)/;
130
+ /** Plain CSS the build parses itself: what postcss reads before any preprocessor. */
131
+ const PLAIN_CSS = /\.(css|pcss|postcss)$/;
132
+ const inNodeModules = (id) => id.includes('/node_modules/');
133
+ /** Where a `new URL` path points on disk: relative to the module, else through the resolver; null for the public folder. */
134
+ async function urlTarget(ctx, url, id) {
135
+ const path = url.split(/[?#]/)[0];
136
+ if (path.startsWith('.'))
137
+ return resolve(dirname(id.replace(/\?.*$/, '')), path);
138
+ return (await ctx.resolve(path, id, { skipSelf: true }))?.id ?? null;
139
+ }
140
+ /**
141
+ * The boundary in dev and in a build, on real paths: any import (whoever
142
+ * imports) into a prototype it does not own, or into prototypes/ outside any
143
+ * prototype; any `new URL(…, import.meta.url)` that does (Vite answers those,
144
+ * `?inline` included, without asking the plugins); and a stylesheet the
145
+ * build cannot parse. Reaches inside a stylesheet are the postcss plugin's
146
+ * (vite/css-boundary.ts); every built file read across owners is
147
+ * vite/settle.ts's.
148
+ */
149
+ function prototypeBoundary(j, loaded) {
150
+ let hub = null;
151
+ return {
152
+ name: 'design-hub-prototype-boundary',
153
+ enforce: 'pre',
154
+ buildStart() {
155
+ hub = null;
156
+ loaded.clear();
157
+ },
158
+ async resolveId(source, importer, options) {
159
+ // Not a reach: no importer; the hub's index.html, which Vite names as the importer of every URL a
160
+ // browser asks for in dev and of every entry; or the dependency scan, which resolves each
161
+ // prototype's index.tsx from that page.
162
+ if (!importer || importer === HUB_HTML || options.scan)
163
+ return null;
164
+ if (inNodeModules(importer) && j.owner(importer) === null)
165
+ return null;
166
+ const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });
167
+ if (!resolved || resolved.external)
168
+ return resolved;
169
+ const problem = reachProblem(j, importer, resolved.id);
170
+ if (problem)
171
+ this.error(problem);
172
+ const file = resolved.id.replace(/\?.*$/, '');
173
+ // Read as text (`?raw`), a preprocessor file is never compiled, so nothing it imports is resolved.
174
+ if (PREPROCESSED.test(file) && !RAW.test(resolved.id) && j.authored(importer))
175
+ this.error(preprocessed(j.root, importer, file));
176
+ // In a build, a prototype's import of a kit or hub sheet goes through a stand-in, so a sheet the
177
+ // hub already loads on every page is not pulled out of the hub's own sheet into a shared chunk.
178
+ if (j.isBuild() &&
179
+ j.owner(importer) !== null &&
180
+ j.owner(resolved.id) === null &&
181
+ isSheetModule(resolved.id))
182
+ return `${HUB_SHEET}${resolved.id}.js`;
183
+ return resolved;
184
+ },
185
+ async load(id) {
186
+ // Every prototype file the build loads, `?raw` included: a pre plugin's load runs before Vite's own
187
+ // loaders (vite:asset answers `?raw`), and this one never answers for a file.
188
+ if (j.isBuild() && !id.startsWith('\0') && j.owner(id) !== null)
189
+ loaded.add(id);
190
+ if (!id.startsWith(HUB_SHEET))
191
+ return null;
192
+ const sheet = id.slice(HUB_SHEET.length, -'.js'.length);
193
+ hub ??= hubGraph(this);
194
+ const from = JSON.stringify(sheet);
195
+ // A CSS module's class names are what the prototype imports it for: always passed on.
196
+ if (/\.module\.\w+$/.test(sheet))
197
+ return `export * from ${from};\nexport { default } from ${from};\n`;
198
+ return (await hub).has(sheet) ? 'export {};' : `import ${from};`;
199
+ },
200
+ async transform(code, id) {
201
+ const file = id.replace(/\?.*$/, '');
202
+ if (id.startsWith('\0') || inNodeModules(file))
203
+ return null;
204
+ // The file without its query (`./q.css?theme=dark` is q.css); the query decides whether it is a sheet.
205
+ if (PLAIN_CSS.test(file) && !/[?&](?:raw|url|inline)\b/.test(id)) {
206
+ let sheet;
207
+ try {
208
+ sheet = postcss.parse(code, { from: file });
209
+ }
210
+ catch (error) {
211
+ const e = error;
212
+ this.error(unreadable(j.root, file, e.line ?? 0, e.column ?? 0, e.reason ?? e.message));
213
+ }
214
+ if (j.authored(file))
215
+ await refusePreprocessed(this, j, sheet, file);
216
+ }
217
+ return null;
218
+ },
219
+ };
220
+ }
221
+ /**
222
+ * A Sass, Less or Stylus file a stylesheet names by `@import`, `composes`,
223
+ * `@value` or `:import`, refused before Vite hands it to the preprocessor.
224
+ * Each is resolved as Vite resolves it; one that does not resolve is named as written.
225
+ */
226
+ async function refusePreprocessed(ctx, j, sheet, file) {
227
+ const refs = [];
228
+ sheet.walk((node) => {
229
+ const ref = node.type === 'atrule' && node.name === 'import' ? importRef(node.params) : moduleRef(node);
230
+ if (ref)
231
+ refs.push(ref);
232
+ });
233
+ for (const ref of refs) {
234
+ const target = ((await ctx.resolve(ref, file, { skipSelf: true }))?.id ?? ref).replace(/\?.*$/, '');
235
+ if (PREPROCESSED.test(target))
236
+ ctx.error(preprocessed(j.root, file, target));
237
+ }
238
+ }
239
+ /** The targets of a module's `new URL(…, import.meta.url)`, on disk. */
240
+ async function urlTargets(ctx, code, id) {
241
+ const file = id.replace(/\?.*$/, '');
242
+ if (id.startsWith('\0') || !SCRIPT.test(file))
243
+ return [];
244
+ const targets = [];
245
+ for (const url of newUrlTargets(code, file) ?? []) {
246
+ const target = await urlTarget(ctx, url, id);
247
+ if (target)
248
+ targets.push(real(target));
249
+ }
250
+ return targets;
251
+ }
252
+ /**
253
+ * `new URL(…, import.meta.url)` into a file another owner holds, `?inline`
254
+ * included, refused in dev and in a build. A normal-order plugin, so it reads
255
+ * the code Vite's own `new URL` plugin reads: TypeScript and JSX already
256
+ * compiled, and Vite not yet answered.
257
+ */
258
+ function urlBoundary(j) {
259
+ return {
260
+ name: 'design-hub-url-boundary',
261
+ async transform(code, id) {
262
+ // A package is skipped only when nobody owns it: one inside a prototype's folder is that prototype's.
263
+ if (inNodeModules(id) && j.owner(id) === null)
264
+ return null;
265
+ for (const target of await urlTargets(this, code, id)) {
266
+ const problem = reachProblem(j, id, target);
267
+ if (problem)
268
+ this.error(problem);
269
+ }
270
+ return null;
271
+ },
272
+ };
273
+ }
274
+ /**
275
+ * The guard in every worker bundle, which Vite builds without the hub's
276
+ * plugins: a module under prototypes/, reached any way (an import with any
277
+ * query, a glob, a `new URL`), is refused before Vite's own plugins answer
278
+ * it. What the bundle writes is recorded as the kit's only when every source
279
+ * it has is outside prototypes/.
280
+ */
281
+ function workerGuard(j, written) {
282
+ const refuse = (ctx, id) => {
283
+ if (j.owner(real(id.replace(/^\0/, '').replace(/\?.*$/, ''))) !== null)
284
+ ctx.error(workerRefused(j.root, id));
285
+ };
286
+ const guard = {
287
+ name: 'design-hub-worker-guard',
288
+ enforce: 'pre',
289
+ async resolveId(source, importer, options) {
290
+ const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });
291
+ refuse(this, resolved?.id ?? source);
292
+ return resolved;
293
+ },
294
+ load(id) {
295
+ refuse(this, id);
296
+ return null;
297
+ },
298
+ generateBundle(_, bundle) {
299
+ for (const file of Object.values(bundle)) {
300
+ // An asset's original files are relative to Vite's root, not the project's.
301
+ const sources = file.type === 'chunk' ? file.moduleIds : file.originalFileNames.map(j.inRoot);
302
+ if (sources.length && sources.every((id) => j.owner(id) === null))
303
+ written.add(file.fileName);
304
+ }
305
+ },
306
+ };
307
+ // Normal order, so it reads the worker's code as Vite's own `new URL` plugin does.
308
+ const urls = {
309
+ name: 'design-hub-worker-url-guard',
310
+ async transform(code, id) {
311
+ for (const target of await urlTargets(this, code, id))
312
+ refuse(this, target);
313
+ return null;
314
+ },
315
+ };
316
+ return [guard, urls];
317
+ }
318
+ // Vite's own tests (vite:css) for a stylesheet module that goes into a chunk's sheet: not one
319
+ // imported as ?inline, ?raw, ?url, a worker, transform-only or a CommonJS proxy.
320
+ const CSS_LANGS = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
321
+ const SPECIAL_QUERY = /[?&](?:worker|sharedworker|raw|url)\b/;
322
+ const NOT_A_SHEET = [SPECIAL_QUERY, /[?&]inline\b/, /[?&]transform-only\b/, /[?&]commonjs-proxy/];
323
+ const isSheetModule = (id) => !id.startsWith('\0') && CSS_LANGS.test(id) && !NOT_A_SHEET.some((re) => re.test(id));
324
+ const shortHash = (text) => createHash('sha256').update(text).digest('hex').slice(0, 6);
325
+ /**
326
+ * The chunk group a kit or hub sheet goes into: one of its own, per file,
327
+ * when only prototypes import it, so its sheet is the kit's alone and lives
328
+ * once in assets/. A sheet the hub or the kit itself imports stays where it
329
+ * is, so the hub's own sheet and its order never change.
330
+ */
331
+ function kitSheetGroup(id, importers, owner) {
332
+ if (!isSheetModule(id) || owner(id) !== null)
333
+ return null;
334
+ const byPrototype = (i) => i.startsWith(HUB_SHEET) || owner(i) !== null;
335
+ if (!importers.length || !importers.every(byPrototype))
336
+ return null;
337
+ const file = id.replace(/^\0/, '').replace(/\?.*$/, '');
338
+ return `kit-${basename(file, extname(file))}-${shortHash(file)}`;
339
+ }
340
+ /**
341
+ * The order modules run in from `roots`: each module's static imports first,
342
+ * in import order, then the module itself, as ES modules evaluate. A
343
+ * stylesheet module's place in it is where dev applies its CSS.
344
+ */
345
+ function runOrder(roots, info) {
346
+ const order = new Map();
347
+ const seen = new Set();
348
+ const visit = (id) => {
349
+ if (seen.has(id))
350
+ return;
351
+ seen.add(id);
352
+ for (const dep of info(id)?.importedIds ?? [])
353
+ visit(dep);
354
+ order.set(id, order.size);
355
+ };
356
+ for (const id of roots)
357
+ visit(id);
358
+ return order;
359
+ }
360
+ /**
361
+ * A chunk's sheets in the order the source imports them, as dev applies
362
+ * them, for kit and own sheets alike. Vite puts a chunk's own sheet before
363
+ * the ones it moves onto it from CSS-only chunks, whatever the source said:
364
+ * a kit sheet a prototype imports first, or a prototype's own sheet it shares
365
+ * with a lazy module, would otherwise come after. Runs after Vite moves those
366
+ * sheets and before it writes the preload lists (enforce 'post'). Only a
367
+ * prototype's chunks: the hub's and the kit's keep the order Vite gives them,
368
+ * so the hub's pages load what they loaded before.
369
+ */
370
+ function sheetOrder(css, owner) {
371
+ return {
372
+ name: 'design-hub-sheet-order',
373
+ enforce: 'post',
374
+ apply: 'build',
375
+ generateBundle(_, bundle) {
376
+ for (const file of Object.values(bundle)) {
377
+ if (file.type !== 'chunk' || !ownersOf(owner, file.moduleIds).length)
378
+ continue;
379
+ const sheets = file.viteMetadata
380
+ ?.importedCss;
381
+ if (!sheets || sheets.size < 2)
382
+ continue;
383
+ const roots = file.facadeModuleId ? [file.facadeModuleId] : file.moduleIds;
384
+ const order = runOrder(roots, (id) => this.getModuleInfo(id));
385
+ const place = (sheet) => Math.min(Infinity, ...(css.get(sheet) ?? []).flatMap((w) => w.modules.map((id) => order.get(id) ?? Infinity)));
386
+ const ordered = [...sheets]
387
+ .map((s, i) => ({ s, i, at: place(s) }))
388
+ .sort((a, b) => a.at - b.at || a.i - b.i);
389
+ sheets.clear();
390
+ for (const { s } of ordered)
391
+ sheets.add(s);
392
+ }
393
+ },
394
+ };
395
+ }
42
396
  export function registry(root) {
43
397
  const prototypes = join(root, 'prototypes');
44
398
  const sprints = join(root, 'docs', 'sprints');
45
- return {
399
+ const owner = ownerOf(prototypes);
400
+ const isPrototype = (o) => isPrototypeSlug(o) && existsSync(join(prototypes, o, 'README.md'));
401
+ const projectKit = `${real(join(root, 'kit'))}/`;
402
+ const judge = {
403
+ root,
404
+ owner,
405
+ isPrototype,
406
+ authored: (file) => owner(file) !== null || real(file.replace(/\?.*$/, '')).startsWith(projectKit),
407
+ isBuild: () => config.command === 'build',
408
+ inRoot: (file) => inRoot(file),
409
+ };
410
+ // Recorded as the build writes them, never inferred later from who reads a file.
411
+ const css = new Map();
412
+ const workers = new Set();
413
+ const loaded = new Set();
414
+ let config = { command: 'serve', base: '/', root };
415
+ const inRoot = (file) => fromRoot(config.root)(file);
416
+ // Vite's own CSS resolvers, with the options its CSS plugin gives them, on the client environment.
417
+ let cssResolvers = null;
418
+ let client = null;
419
+ const onClient = (resolve) => (id, importer) => client ? resolve(client, id, importer) : Promise.resolve(undefined);
420
+ const main = {
46
421
  name: 'design-hub-registry',
422
+ // Named by what they hold: one prototype's chunks and assets under _p/<slug>/, everything shared in assets/.
423
+ config: () => ({
424
+ // Every stylesheet, whoever owns it, is read for reaches in Vite's own postcss run.
425
+ css: {
426
+ postcss: { plugins: [cssBoundary(root, owner, isPrototype, () => (client ? cssResolvers : null))()] },
427
+ },
428
+ // Vite builds a worker without the hub's plugins: the guard, and the kit resolver so a kit worker's
429
+ // `@kit/*` imports are bundled, not left external.
430
+ worker: {
431
+ plugins: () => [...workerGuard(judge, workers), kitResolver(join(root, 'kit'), PACKAGE_KIT)],
432
+ },
433
+ build: {
434
+ // Nothing a prototype owns is inlined: every reach leaves a file with a source the end-of-build check can see.
435
+ assetsInlineLimit: (file) => (owner(file) !== null ? false : undefined),
436
+ rolldownOptions: {
437
+ output: {
438
+ // A kit or hub sheet a prototype imports is a chunk of its own, so its sheet is the kit's alone
439
+ // and lives once in assets/, never folded into the prototype's sheet.
440
+ codeSplitting: {
441
+ groups: [
442
+ {
443
+ debugName: 'kit-sheet',
444
+ name: (id, ctx) => kitSheetGroup(id, ctx.getModuleInfo(id)?.importers ?? [], owner),
445
+ },
446
+ ],
447
+ },
448
+ chunkFileNames: (chunk) => placed(ownersOf(owner, chunk.moduleIds), '[name]-[hash].js'),
449
+ assetFileNames: (asset) => {
450
+ const sources = asset.originalFileNames.map(inRoot);
451
+ const shared = sources.some((f) => owner(f) === null);
452
+ return placed(ownersOf(owner, sources), '[name]-[hash][extname]', shared);
453
+ },
454
+ },
455
+ },
456
+ },
457
+ }),
458
+ configResolved(resolved) {
459
+ config = resolved;
460
+ cssResolvers = {
461
+ // vite:css's resolver for url() and image-set().
462
+ url: onClient(createIdResolver(resolved, { preferRelative: true, tryIndex: false, extensions: [] })),
463
+ // Its resolver for @import, which postcss-modules also asks for composes, @value and :import.
464
+ css: onClient(createIdResolver(resolved, {
465
+ extensions: ['.css'],
466
+ mainFields: ['style'],
467
+ conditions: ['style', 'development|production'],
468
+ tryIndex: false,
469
+ preferRelative: true,
470
+ })),
471
+ };
472
+ },
47
473
  resolveId(id) {
48
- return id === REGISTRY_ID ? RESOLVED : null;
474
+ if (id === REGISTRY_ID)
475
+ return RESOLVED;
476
+ return id.startsWith(ENTRY_ID) && isPrototypeSlug(id.slice(ENTRY_ID.length)) ? `\0${id}` : null;
49
477
  },
50
478
  load(id) {
51
- return id === RESOLVED ? registrySource(root) : null;
479
+ if (id === RESOLVED)
480
+ return registrySource(root, config.command, config.base);
481
+ return id.startsWith(`\0${ENTRY_ID}`) ? entrySource(root, id.slice(ENTRY_ID.length + 1)) : null;
482
+ },
483
+ buildStart() {
484
+ if (this.environment.name === 'client')
485
+ client = this.environment;
486
+ if (config.command !== 'build')
487
+ return;
488
+ css.clear();
489
+ workers.clear();
490
+ const slugs = prototypeSlugs(prototypes);
491
+ // preserveSignature: 'strict', or Rolldown empties an entry nothing else imports.
492
+ for (const slug of slugs)
493
+ this.emitFile({
494
+ type: 'chunk',
495
+ id: ENTRY_ID + slug,
496
+ fileName: entryFile(slug),
497
+ preserveSignature: 'strict',
498
+ });
499
+ this.emitFile({ type: 'asset', fileName: ALL_FILE, source: allSource(slugs) });
500
+ },
501
+ // After Vite's own renderChunk, while each chunk's importedCss still holds only its own sheet:
502
+ // the sheet's CSS modules are its sources. Vite later moves a CSS-only chunk's sheet onto its importers.
503
+ renderChunk: {
504
+ order: 'post',
505
+ handler(_, chunk) {
506
+ const sheets = chunk.viteMetadata
507
+ ?.importedCss;
508
+ if (!sheets?.size)
509
+ return null;
510
+ const write = {
511
+ modules: chunk.moduleIds.filter(isSheetModule),
512
+ writer: ownersOf(owner, chunk.moduleIds)[0] ?? null,
513
+ };
514
+ for (const sheet of sheets)
515
+ css.set(sheet, [...(css.get(sheet) ?? []), write]);
516
+ return null;
517
+ },
518
+ },
519
+ // After Vite's own generateBundle work, so its preload lists are final:
520
+ // every asset goes where its readers can reach it, then the build proves
521
+ // its own boundary, and a file that breaks it fails the build.
522
+ generateBundle: {
523
+ order: 'post',
524
+ handler(_, bundle) {
525
+ const o = { owner, inRoot, slugs: prototypeSlugs(prototypes), root, css, workers };
526
+ // Every file the bundle read, before settle moves or splits anything: a CSS-only chunk is gone by
527
+ // now, so its stylesheet modules come from the sheet records, and a module no chunk holds (one a
528
+ // plugin loaded with `this.load`) from the loads.
529
+ const inputs = [
530
+ ...loaded,
531
+ ...Object.values(bundle).flatMap((f) => f.type === 'chunk' ? f.moduleIds : f.originalFileNames.map(inRoot)),
532
+ ...[...css.values()].flatMap((writes) => writes.flatMap((w) => w.modules)),
533
+ ];
534
+ const copies = new Map();
535
+ const problems = settle(bundle, o, (fileName, source) => {
536
+ copies.set(fileName, { fileName, source });
537
+ this.emitFile({ type: 'asset', fileName, source });
538
+ });
539
+ // Then what was written, whatever wrote it: no prototype's content outside its folder.
540
+ if (!problems.length) {
541
+ const written = new Map(Object.values(bundle).map((f) => [
542
+ f.fileName,
543
+ { fileName: f.fileName, source: f.type === 'chunk' ? f.code : f.source },
544
+ ]));
545
+ for (const [name, copy] of copies)
546
+ written.set(name, copy);
547
+ problems.push(...leaks(root, prototypes, owner, inputs, [...written.values()]));
548
+ }
549
+ if (problems.length)
550
+ this.error(`The prototype boundary does not hold:\n${problems.join('\n')}`);
551
+ },
52
552
  },
53
553
  configureServer(server) {
54
554
  server.watcher.add([prototypes, sprints]);
55
555
  const refresh = (path) => {
56
556
  if (!path.startsWith(prototypes) && !path.startsWith(sprints))
57
557
  return;
58
- const mod = server.moduleGraph.getModuleById(RESOLVED);
59
- if (mod)
60
- server.moduleGraph.invalidateModule(mod);
558
+ for (const id of [RESOLVED, ...prototypeSlugs(prototypes).map((slug) => `\0${ENTRY_ID}${slug}`)]) {
559
+ const mod = server.moduleGraph.getModuleById(id);
560
+ if (mod)
561
+ server.moduleGraph.invalidateModule(mod);
562
+ }
61
563
  server.ws.send({ type: 'full-reload' });
62
564
  };
63
565
  // A folder coming or going, or one of the three files the registry lists, changes what the index shows.
@@ -67,4 +569,6 @@ export function registry(root) {
67
569
  server.watcher.on('unlink', (path) => REGISTRY_FILE.test(path) && refresh(path));
68
570
  },
69
571
  };
572
+ return [prototypeBoundary(judge, loaded), urlBoundary(judge), main, sheetOrder(css, owner)];
70
573
  }
574
+ const REGISTRY_FILE = /\/(README\.md|index\.tsx|guide\.md)$/;
@@ -0,0 +1,27 @@
1
+ import type { Rolldown } from 'vite';
2
+ import { type Owner } from './boundary.ts';
3
+ type Bundle = Rolldown.OutputBundle;
4
+ /** One chunk writing a stylesheet: the CSS modules it holds, and the owner of the chunk, whose name Vite gave the sheet. */
5
+ export type SheetWrite = {
6
+ modules: readonly string[];
7
+ writer: Owner;
8
+ };
9
+ export type Owners = {
10
+ owner: (id: string) => string | null;
11
+ inRoot: (file: string) => string;
12
+ slugs: readonly string[];
13
+ root: string;
14
+ /** Each written stylesheet's CSS modules and writer, one record per chunk that wrote it, recorded when the chunk was rendered. */
15
+ css: ReadonlyMap<string, readonly SheetWrite[]>;
16
+ /** The files worker bundles wrote: built from no prototype's file (the worker guard refuses one). */
17
+ workers: ReadonlySet<string>;
18
+ };
19
+ /**
20
+ * Places every asset by the owners of its content, points each real read at
21
+ * the reader's own copy, and returns every problem: a chunk with two
22
+ * prototypes' modules or outside its folder, a read across owners, and a
23
+ * file with no record of its source and no fixed name.
24
+ * Writes nothing when there is a problem.
25
+ */
26
+ export declare function settle(bundle: Bundle, o: Owners, emit: (fileName: string, source: string | Uint8Array) => void): string[];
27
+ export {};