forked from nexu-io/open-design
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
4400 lines (4078 loc) · 163 KB
/
Copy pathindex.ts
File metadata and controls
4400 lines (4078 loc) · 163 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Design-system registry. Scans <projectRoot>/design-systems/* for design
// system projects. Project folders may opt into manifest.json; legacy folders
// with only DESIGN.md remain valid. Without a manifest, title comes from the
// first H1, category from a `> Category: <name>` blockquote line beneath the
// H1, and summary from the first paragraph between the H1 and next heading.
//
// YAML frontmatter (Google spec, issue #1857): frontmatter `colors` wins
// over Markdown swatches only when its row fills every semantic slot;
// otherwise Markdown wins. Other fields (`name`/`description`/`category`/
// `surface`) fall back to frontmatter when the body has none.
import { createHash, randomUUID } from 'node:crypto';
import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
import path from 'node:path';
import JSZip from 'jszip';
import type Database from 'better-sqlite3';
import {
type ComponentsManifest,
DesignSystemRuntimePathsSchema,
extractComponentsManifest,
summarizeComponentsManifestForPrompt,
type DesignSystemRuntimePaths,
} from '@open-design/contracts';
import { parseFrontmatter } from './frontmatter.js';
import type { FrontmatterObject, FrontmatterValue } from './frontmatter.js';
import { extractSwiftColors } from './swift-colors.js';
import {
loadDesignSystemRuntimePackage,
summarizeDesignSystemIntentMapForPrompt,
type DesignSystemRuntimeLoadResult,
} from './runtime.js';
import { workspaceTeamDesignSystemBindingResourceId } from './workspace-team-binding.js';
import {
ensureWorkspaceResource,
getWorkspaceResourceByResourceId,
updateWorkspaceResource,
} from '../db.js';
import { teamResourceWorkspaceRoot } from '../collab/team-resource-materialization.js';
type SqliteDb = Database.Database;
export type DesignSystemSurface = 'web' | 'image' | 'video' | 'audio';
export type DesignSystemSource = 'built-in' | 'installed' | 'user';
export type DesignSystemStatus = 'draft' | 'published';
export type DesignSystemRevisionStatus = 'pending' | 'accepted' | 'rejected';
export type DesignSystemArtifactMode = 'generated' | 'agent-managed';
export type DesignSystemSummary = {
id: string;
title: string;
category: string;
summary: string;
swatches: string[];
surface: DesignSystemSurface;
body: string;
source: DesignSystemSource;
status: DesignSystemStatus;
isEditable: boolean;
createdAt?: string;
updatedAt?: string;
provenance?: DesignSystemProvenance;
projectId?: string;
teamSynced?: boolean;
/**
* The workspace this user design system belongs to, when one claimed it.
*
* Absent means UNCLAIMED, not "belongs to no workspace" — see
* `DesignSystemListOptions.workspaceId`.
*/
workspaceId?: string;
};
export type DesignSystemFileKind =
| 'folder'
| 'page'
| 'stylesheet'
| 'document'
| 'image'
| 'data'
| 'asset';
export type DesignSystemFileSummary = {
path: string;
name: string;
kind: DesignSystemFileKind;
size?: number;
updatedAt?: string;
};
export type DesignSystemFileDetail = DesignSystemFileSummary & {
content: string;
};
export type DesignSystemPullFileDetail = {
path: string;
name: string;
kind: DesignSystemFileKind;
size: number;
updatedAt: string;
encoding: 'utf8' | 'base64';
content: string;
};
export type DesignSystemStaticFileDetail = {
path: string;
name: string;
kind: DesignSystemFileKind;
size: number;
updatedAt: string;
contentType: string;
bytes: Buffer;
};
export type DesignSystemPackageInfo = {
manifest?: DesignSystemProjectManifest;
availableFiles?: string[];
sourceEvidence?: {
scannedFileCount?: number;
tokenCount?: number;
snippetCount?: number;
confidence?: Record<string, string | number>;
evidenceExcerpt?: string;
tokenContract?: {
contract?: string;
grade?: 'excellent' | 'usable' | 'needs-review' | 'needs-rebuild';
score?: number;
recommendRebuild?: boolean;
sourceBackedA1?: number;
requiredA1?: number;
fallbackTokens?: number;
selfCheckOk?: boolean;
};
};
};
export type DesignSystemRevision = {
id: string;
designSystemId: string;
status: DesignSystemRevisionStatus;
feedback: string;
baseBody: string;
proposedBody: string;
createdAt: string;
updatedAt: string;
sectionTitle?: string;
jobId?: string;
fileChanges?: DesignSystemRevisionFileChange[];
};
export type DesignSystemRevisionFileChange = {
path: string;
baseContent: string;
proposedContent: string;
};
type ColorToken = { name: string; value: string };
type SwatchRow = { values: string[]; filledAllSlots: boolean };
type DesignSystemProjectManifest = {
schemaVersion: 'od-design-system-project/v1';
id: string;
name: string;
category: string;
description?: string;
files: {
design: 'DESIGN.md';
tokens: 'tokens.css';
designTokens?: 'design-tokens.json';
tailwind?: 'tailwind-v4.css';
components?: 'components.html';
};
assetsDir?: 'assets';
previewDir?: 'preview';
usage?: string;
componentsManifest?: string;
fonts?: Array<{
family: string;
file: string;
weight?: number | string;
style?: string;
}>;
preview?: {
dir: string;
pages: Array<{
path: string;
role?: string;
title?: string;
}>;
};
sourceFiles?: {
scanned?: string;
evidence?: string;
tokens?: string;
report?: string;
snippets?: string;
};
importMode?: 'normalized' | 'hybrid' | 'verbatim';
craft?: {
applies?: string[];
suggested?: string[];
exemptions?: string[];
};
runtime?: DesignSystemRuntimePaths;
};
export type DesignSystemProvenance = {
companyBlurb?: string;
sourceUrls?: string[];
githubUrls?: string[];
localCodeFiles?: string[];
figFiles?: string[];
assetFiles?: string[];
notes?: string;
sourceNotes?: string;
};
type UserDesignSystemMetadata = {
title?: string;
category?: string;
surface?: DesignSystemSurface;
status?: DesignSystemStatus;
artifactMode?: DesignSystemArtifactMode;
createdAt?: string;
updatedAt?: string;
provenance?: DesignSystemProvenance;
projectId?: string;
teamSynced?: boolean;
/** Workspace that claimed this system; absent on anything written before #145. */
workspaceId?: string;
};
type AtomicTextFileWrite = {
targetPath: string;
content: string;
};
type AtomicTextFileSnapshot =
| { existed: true; content: string }
| { existed: false };
export const LEGACY_DESIGN_SYSTEM_ARTIFACTS = [
{
legacyPath: 'preview/colors-ui-palette.html',
replacementPaths: ['preview/colors-primary.html'],
},
{
legacyPath: 'preview/colors-node-types.html',
replacementPaths: ['preview/colors-theme-light.html', 'preview/colors-theme-dark.html'],
},
{
legacyPath: 'preview/typography-scale.html',
replacementPaths: ['preview/typography-specimens.html'],
},
{
legacyPath: 'preview/spacing-system.html',
replacementPaths: ['preview/spacing-tokens.html', 'preview/spacing-radius.html', 'preview/spacing-shadows.html'],
},
{
legacyPath: 'preview/logo-variants.html',
replacementPaths: ['preview/brand-assets.html'],
},
{
legacyPath: 'ui_kits/generated_interface',
replacementPaths: ['ui_kits/app/index.html'],
removeDirectory: true,
},
] as const;
export type UserDesignSystemInput = {
title?: string;
summary?: string;
category?: string;
surface?: DesignSystemSurface;
status?: DesignSystemStatus;
artifactMode?: DesignSystemArtifactMode;
body?: string;
sourceNotes?: string;
provenance?: DesignSystemProvenance;
/**
* Workspace to claim the new system for (#145). Set by the daemon from the
* active workspace selection at creation time; omitted leaves the system
* unclaimed for local/unscoped use and quarantined from scoped catalogs.
*
* Only `createUserDesignSystem` reads it — an update must never re-home an
* existing system just because the caller happened to be elsewhere.
*/
workspaceId?: string;
/** Internal write-fence: logical ids already claimed in workspace_resources. */
reservedResourceIds?: Iterable<string>;
};
export type UserDesignSystemRevisionInput = {
feedback: string;
baseBody: string;
proposedBody: string;
sectionTitle?: string;
jobId?: string;
fileChanges?: DesignSystemRevisionFileChange[];
};
export type DesignSystemListOptions = {
idPrefix?: string;
source?: DesignSystemSource;
isEditable?: boolean;
defaultStatus?: DesignSystemStatus;
/**
* Restrict the listing to design systems visible from this workspace (#145).
*
* User design systems all live in ONE flat directory under the daemon data
* root — there is no per-workspace store — so without this filter a system
* authored in workspace A also showed up in a brand-new workspace B.
*
* A positive scope is fail-closed: both systems claimed by another workspace
* and UNCLAIMED systems (no `workspaceId` in metadata) are hidden. Historical
* ownerless systems remain on disk and visible to truly unscoped/local
* callers; startup migration claims only those whose project has one exact
* persisted workspace binding.
*
* Omitted means a truly unscoped internal lookup and lists everything.
* Explicitly empty (`null`/`''`) is the signed-out/local catalog lane: it
* lists only ownerless local systems and hides every claimed system.
*/
workspaceId?: string | null;
};
export async function listDesignSystems(
root: string,
options: DesignSystemListOptions = {},
): Promise<DesignSystemSummary[]> {
const out: DesignSystemSummary[] = [];
let entries = [];
try {
entries = await readdir(root, { withFileTypes: true });
} catch {
return out;
}
for (const entry of entries) {
if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
const brandRoot = path.join(root, entry.name);
const manifest = await readProjectManifest(brandRoot, entry.name);
const designPath = path.join(brandRoot, manifest?.files.design ?? 'DESIGN.md');
try {
const stats = await stat(designPath);
if (!stats.isFile()) continue;
const raw = await readFile(designPath, 'utf8');
const metadata = await readUserMetadata(root, entry.name);
if (!designSystemVisibleFromWorkspace(metadata.workspaceId, options.workspaceId)) continue;
const { data: frontmatter, body } = parseFrontmatter(raw);
const titleMatch = /^#\s+(.+?)\s*$/m.exec(body);
const markdownTitle =
titleMatch?.[1] !== undefined ? cleanTitle(titleMatch[1]) : '';
const fallbackTitle = markdownTitle || stringField(frontmatter, 'name') || entry.name;
const title = cleanTitle(
metadata.title
?? manifest?.name
?? fallbackTitle,
);
const frontmatterCategory = stringField(frontmatter, 'category');
const category = (
metadata.category
?? manifest?.category
?? extractCategory(body)
?? frontmatterCategory
) || 'Uncategorized';
const markdownSummary = summarize(body);
const markdownSwatches = extractSwatches(body);
const frontmatterSwatchRow = swatchesFromFrontmatter(frontmatter);
const swatches = pickFinalSwatchRow(frontmatterSwatchRow, markdownSwatches);
out.push({
id: `${options.idPrefix ?? ''}${entry.name}`,
title,
category,
summary:
(manifest?.description?.trim() || markdownSummary)
|| stringField(frontmatter, 'description')
|| '',
swatches,
surface:
metadata.surface
?? extractSurface(body)
?? frontmatterSurface(frontmatter)
?? 'web',
body: raw,
source: options.source ?? 'built-in',
status: metadata.status ?? options.defaultStatus ?? 'published',
isEditable: options.isEditable ?? false,
...(metadata.createdAt ? { createdAt: metadata.createdAt } : {}),
...(metadata.updatedAt ? { updatedAt: metadata.updatedAt } : {}),
...(metadata.provenance ? { provenance: metadata.provenance } : {}),
...(metadata.projectId ? { projectId: metadata.projectId } : {}),
...(metadata.teamSynced ? { teamSynced: true } : {}),
...(metadata.workspaceId ? { workspaceId: metadata.workspaceId } : {}),
});
} catch {
// Skip.
}
}
return out;
}
/**
* Whether a design system claimed by `owner` should be listed while `scope` is
* the active workspace.
*
* `scope === undefined` (the `workspaceId` option key OMITTED, not merely
* empty) means the caller asked for the truly unscoped catalog — id
* resolution, install/import lookups, and (critically) `createUserDesignSystem`/
* `updateUserDesignSystem`/`linkUserDesignSystemProject` re-reading the system
* they just wrote by id — which must never hide anything, or writing a system
* claimed by a workspace would make `listDesignSystems(...).find(...)` fail to
* find what was just written (a real regression this fix must not introduce).
*
* `scope` present but empty (`null`/`''`) is a DIFFERENT case: a caller that
* DID ask to be scoped — `GET /api/design-systems` with no verified vela
* session — but has no workspace identity to offer. Spec 04 §10: that must
* hide a CLAIMED system, not show it, or "no scope" quietly becomes "trust
* everything". With a positive scope, no `owner` means QUARANTINED: absence of
* an ownership witness must not authorize a cross-workspace read. With an
* explicitly empty scope, ownerless local resources remain usable while all
* claimed workspace resources stay hidden.
*/
function designSystemVisibleFromWorkspace(
owner: string | undefined,
scope: string | null | undefined,
): boolean {
if (scope === undefined) return true;
const scopeId = scope?.trim();
const ownerId = owner?.trim();
if (!scopeId) return !ownerId;
if (!ownerId) return false;
return ownerId === scopeId;
}
async function designSystemDirectoryVisibleFromWorkspace(
root: string,
dirId: string,
scope: string | null | undefined,
): Promise<boolean> {
if (scope === undefined) return true;
const metadata = await readUserMetadata(root, dirId);
return designSystemVisibleFromWorkspace(metadata.workspaceId, scope);
}
function stringField(data: FrontmatterObject, key: string): string {
const v: FrontmatterValue | undefined = data[key];
return typeof v === 'string' ? v.trim() : '';
}
function frontmatterSurface(data: FrontmatterObject): DesignSystemSurface | undefined {
const v = stringField(data, 'surface').toLowerCase();
return isDesignSystemSurface(v) ? v : undefined;
}
function swatchesFromFrontmatter(data: FrontmatterObject): SwatchRow | null {
const raw = data['colors'];
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return null;
const colors: ColorToken[] = [];
const seen = new Set<string>();
for (const [name, value] of Object.entries(raw)) {
if (typeof value !== 'string') continue;
const hex = normalizeHex(value);
if (!hex) continue;
const cleanName = name.replace(/\s+/g, ' ').trim().toLowerCase();
const key = `${cleanName}|${hex}`;
if (seen.has(key)) continue;
seen.add(key);
colors.push({ name: cleanName, value: hex });
}
if (colors.length === 0) return null;
return pickSwatchRow(colors);
}
function pickFinalSwatchRow(
frontmatter: SwatchRow | null,
markdownSwatches: string[],
): string[] {
if (frontmatter !== null && frontmatter.filledAllSlots) return frontmatter.values;
if (markdownSwatches.length > 0) return markdownSwatches;
return frontmatter?.values ?? [];
}
export async function readDesignSystem(
root: string,
id: string,
options: { idPrefix?: string; workspaceId?: string | null } = {},
): Promise<string | null> {
const dirId = stripPrefixAndValidateId(id, options.idPrefix);
if (!dirId) return null;
if (!(await designSystemDirectoryVisibleFromWorkspace(root, dirId, options.workspaceId))) {
return null;
}
const brandRoot = path.join(root, dirId);
const manifest = await readProjectManifest(brandRoot, dirId);
const file = path.join(brandRoot, manifest?.files.design ?? 'DESIGN.md');
try {
return await readFile(file, 'utf8');
} catch {
return null;
}
}
export async function readDesignSystemPackageInfo(
root: string,
id: string,
options: { idPrefix?: string; workspaceId?: string | null } = {},
): Promise<DesignSystemPackageInfo | null> {
const dirId = stripPrefixAndValidateId(id, options.idPrefix);
if (!dirId) return null;
if (!(await designSystemDirectoryVisibleFromWorkspace(root, dirId, options.workspaceId))) {
return null;
}
const brandRoot = path.join(root, dirId);
const manifest = await readProjectManifest(brandRoot, dirId);
if (manifest === null) return null;
const sourceEvidence = await readDesignSystemSourceEvidence(brandRoot, manifest);
const availableFiles = await listAvailableDesignSystemPackageFiles(brandRoot, manifest);
return {
manifest,
...(availableFiles.length > 0 ? { availableFiles } : {}),
...(sourceEvidence ? { sourceEvidence } : {}),
};
}
export async function readDesignSystemRuntime(
root: string,
id: string,
options: { idPrefix?: string } = {},
): Promise<DesignSystemRuntimeLoadResult> {
const dirId = stripPrefixAndValidateId(id, options.idPrefix);
if (!dirId) return { mode: 'legacy' };
const brandRoot = path.join(root, dirId);
const raw = await readFileOptional(path.join(brandRoot, 'manifest.json'));
if (raw === undefined) return { mode: 'legacy' };
let value: unknown;
try {
value = JSON.parse(raw) as unknown;
} catch (error) {
return {
mode: 'invalid',
errors: [`manifest.json: ${error instanceof Error ? error.message : String(error)}`],
};
}
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
return { mode: 'invalid', errors: ['manifest.json must contain an object'] };
}
const record = value as Record<string, unknown>;
if (record.id !== dirId) {
return { mode: 'invalid', errors: [`manifest.json id must match ${dirId}`] };
}
if (record.runtime === undefined) return { mode: 'legacy' };
const parsedRuntime = DesignSystemRuntimePathsSchema.safeParse(record.runtime);
if (!parsedRuntime.success) {
return {
mode: 'invalid',
errors: parsedRuntime.error.issues.map((issue) => {
const suffix = issue.path.length === 0
? ''
: issue.path.map((part) => typeof part === 'number' ? `[${part}]` : `.${part}`).join('');
return `manifest.json: $.runtime${suffix} ${issue.message}`;
}),
};
}
return loadDesignSystemRuntimePackage(brandRoot, parsedRuntime.data);
}
/** Resolve the active package with the same built-in → installed precedence used by prompt assets. */
export async function resolveDesignSystemRuntime(
designSystemId: string,
builtInRoot: string,
userInstalledRoot: string,
): Promise<DesignSystemRuntimeLoadResult> {
if (designSystemId.startsWith('user:')) {
return readDesignSystemRuntime(userInstalledRoot, designSystemId, { idPrefix: 'user:' });
}
const builtIn = await readDesignSystemRuntime(builtInRoot, designSystemId);
if (builtIn.mode !== 'legacy') return builtIn;
return readDesignSystemRuntime(userInstalledRoot, designSystemId);
}
export type DesignSystemRuntimePromptContext =
| { mode: 'legacy' }
| { mode: 'structured'; intentIndex: string }
| { mode: 'invalid'; issue: string };
export async function resolveDesignSystemRuntimePromptContext(
designSystemId: string,
builtInRoot: string,
userInstalledRoot: string,
env: NodeJS.ProcessEnv = process.env,
): Promise<DesignSystemRuntimePromptContext> {
if (!isDesignTokenChannelEnabled(env)) return { mode: 'legacy' };
const runtime = await resolveDesignSystemRuntime(
designSystemId,
builtInRoot,
userInstalledRoot,
);
if (runtime.mode === 'structured') {
return {
mode: 'structured',
intentIndex: summarizeDesignSystemIntentMapForPrompt(runtime.bundle),
};
}
if (runtime.mode === 'invalid') {
return { mode: 'invalid', issue: runtime.errors.join('\n') };
}
return { mode: 'legacy' };
}
async function listAvailableDesignSystemPackageFiles(
brandRoot: string,
manifest: DesignSystemProjectManifest,
): Promise<string[]> {
const candidates = new Set<string>(DESIGN_SYSTEM_STATIC_SYSTEM_FILES);
const add = (filePath: string | undefined): void => {
const cleanPath = typeof filePath === 'string' ? sanitizeRelativeFilePath(filePath) : null;
if (cleanPath) candidates.add(cleanPath);
};
add(manifest.files.design);
add(manifest.files.tokens);
add(manifest.files.components);
add(manifest.files.designTokens);
add(manifest.files.tailwind);
add(manifest.usage);
add(manifest.componentsManifest);
add(manifest.runtime?.components);
add(manifest.runtime?.intents);
add(manifest.runtime?.lint);
add(manifest.runtime?.fallback);
for (const page of manifest.preview?.pages ?? []) add(page.path);
for (const font of manifest.fonts ?? []) add(font.file);
const out: string[] = [];
const resolvedRoot = path.resolve(brandRoot);
for (const relativePath of Array.from(candidates).sort()) {
const filePath = path.resolve(brandRoot, relativePath);
if (filePath !== resolvedRoot && !filePath.startsWith(`${resolvedRoot}${path.sep}`)) continue;
try {
const stats = await stat(filePath);
if (stats.isFile()) out.push(relativePath);
} catch (err) {
if (!isAbsenceError(err)) throw err;
}
}
return out;
}
/**
* Structured (compiled) form of a brand's design system. Optional sibling
* files alongside DESIGN.md that, when present, give agents a
* machine-readable token contract and a worked fixture instead of having
* to re-derive both from prose. Both fields are individually optional —
* the daemon falls back to the DESIGN.md-only path when neither is
* available, which is the current state for the ~138 brands without
* hand-authored or derived tokens.
*
* - `tokensCss` — verbatim content of `<brand>/tokens.css`.
* - `usageMd` — optional agent-facing router for the package.
* - `fixtureHtml` — verbatim content of `<brand>/components.html`.
* - `componentsManifest` — concise summary derived from components.html
* or read from components.manifest.json cache
* for prompt injection; when absent, callers
* can fall back to `fixtureHtml`.
* - `pullIndex` — short manifest-derived file index. It lists
* richer preview/source evidence paths without
* loading those files into the push prompt.
*/
export type DesignSystemAssets = {
usageMd?: string | undefined;
tokensCss?: string | undefined;
fixtureHtml?: string | undefined;
componentsManifest?: string | undefined;
pullIndex?: string | undefined;
importMode?: 'normalized' | 'hybrid' | 'verbatim' | undefined;
craftApplies?: string[] | undefined;
craftExemptions?: string[] | undefined;
};
const DESIGN_SYSTEM_ASSETS_CACHE_LIMIT = 128;
const designSystemAssetsCache = new Map<string, Promise<DesignSystemAssets> | DesignSystemAssets>();
export function clearDesignSystemAssetsCacheForTests(): void {
designSystemAssetsCache.clear();
}
export async function readDesignSystemAssets(
root: string,
id: string,
): Promise<DesignSystemAssets> {
const dirId = stripPrefixAndValidateId(id, id.startsWith('user:') ? 'user:' : '');
if (!dirId) return {};
const brandRoot = path.join(root, dirId);
const manifest = await readProjectManifest(brandRoot, dirId);
const [usageMd, tokensCss, fixtureHtml, componentsManifestJson] = await Promise.all([
readManifestFileOptional(brandRoot, manifest?.usage ?? 'USAGE.md'),
readFileOptional(path.join(brandRoot, manifest?.files.tokens ?? 'tokens.css')),
manifest?.files.components === undefined && manifest !== null
? Promise.resolve(undefined)
: readFileOptional(path.join(brandRoot, manifest?.files.components ?? 'components.html')),
readManifestFileOptional(brandRoot, manifest?.componentsManifest ?? 'components.manifest.json'),
]);
return withComponentsManifest(id, {
usageMd,
tokensCss,
fixtureHtml,
componentsManifestJson,
pullIndex: buildDesignSystemPullIndex(manifest),
importMode: manifest?.importMode,
craftApplies: manifest?.craft?.applies,
craftExemptions: manifest?.craft?.exemptions,
});
}
export async function readDesignSystemPullFile(
root: string,
id: string,
relativePath: string,
): Promise<DesignSystemPullFileDetail | null> {
const dirId = stripPrefixAndValidateId(id, id.startsWith('user:') ? 'user:' : '');
const cleanPath = sanitizeRelativeFilePath(relativePath);
if (!dirId || !cleanPath) return null;
const brandRoot = path.join(root, dirId);
const manifest = await readProjectManifest(brandRoot, dirId);
if (manifest === null) return null;
const allowed = await buildDesignSystemPullFileAllowlist(brandRoot, manifest);
if (!allowed.has(cleanPath)) return null;
const resolvedRoot = path.resolve(brandRoot);
const filePath = path.resolve(brandRoot, cleanPath);
if (filePath !== resolvedRoot && !filePath.startsWith(`${resolvedRoot}${path.sep}`)) {
return null;
}
try {
const stats = await stat(filePath);
if (!stats.isFile()) return null;
const bytes = await readFile(filePath);
const encoding = isTextDesignSystemPullFile(cleanPath) ? 'utf8' : 'base64';
return {
path: cleanPath,
name: path.basename(cleanPath),
kind: classifyDesignSystemFile(cleanPath, false),
size: stats.size,
updatedAt: stats.mtime.toISOString(),
encoding,
content: encoding === 'utf8' ? bytes.toString('utf8') : bytes.toString('base64'),
};
} catch (err) {
if (isAbsenceError(err)) return null;
throw err;
}
}
export async function readDesignSystemStaticFile(
root: string,
id: string,
relativePath: string,
options: { idPrefix?: string; workspaceId?: string | null } = {},
): Promise<DesignSystemStaticFileDetail | null> {
const dirId = stripPrefixAndValidateId(id, options.idPrefix);
const cleanPath = sanitizeRelativeFilePath(relativePath);
if (!dirId || !cleanPath) return null;
if (!(await designSystemDirectoryVisibleFromWorkspace(root, dirId, options.workspaceId))) {
return null;
}
const brandRoot = path.join(root, dirId);
const manifest = await readProjectManifest(brandRoot, dirId);
if (!(await isAllowedDesignSystemStaticFile(brandRoot, manifest, cleanPath))) return null;
const resolvedRoot = path.resolve(brandRoot);
const filePath = path.resolve(brandRoot, cleanPath);
if (filePath !== resolvedRoot && !filePath.startsWith(`${resolvedRoot}${path.sep}`)) {
return null;
}
try {
const stats = await stat(filePath);
if (!stats.isFile()) return null;
const bytes = await readFile(filePath);
return {
path: cleanPath,
name: path.basename(cleanPath),
kind: classifyDesignSystemFile(cleanPath, false),
size: stats.size,
updatedAt: stats.mtime.toISOString(),
contentType: designSystemStaticContentType(cleanPath),
bytes,
};
} catch (err) {
if (isAbsenceError(err)) return null;
throw err;
}
}
export function isDesignTokenChannelEnabled(
env: NodeJS.ProcessEnv = process.env,
): boolean {
return env.OD_DESIGN_TOKEN_CHANNEL !== '0';
}
export function digestDesignSystemContext(input: {
id?: string | null;
title?: string | null;
body?: string | null;
usageMd?: string | null;
tokensCss?: string | null;
componentsManifest?: string | null;
fixtureHtml?: string | null;
pullIndex?: string | null;
intentIndex?: string | null;
runtimeIssue?: string | null;
importMode?: string | null;
}): string | null {
const hasContent = [
input.body,
input.usageMd,
input.tokensCss,
input.componentsManifest,
input.fixtureHtml,
input.pullIndex,
input.intentIndex,
input.runtimeIssue,
input.importMode,
].some((value) => typeof value === 'string' && value.length > 0);
if (!hasContent) return null;
const payload = {
id: input.id ?? null,
title: input.title ?? null,
body: input.body ?? null,
usageMd: input.usageMd ?? null,
tokensCss: input.tokensCss ?? null,
componentsManifest: input.componentsManifest ?? null,
fixtureHtml: input.fixtureHtml ?? null,
pullIndex: input.pullIndex ?? null,
intentIndex: input.intentIndex ?? null,
runtimeIssue: input.runtimeIssue ?? null,
importMode: input.importMode ?? null,
};
return createHash('sha256').update(JSON.stringify(payload), 'utf8').digest('hex');
}
export async function resolveDesignSystemAssets(
designSystemId: string,
builtInRoot: string,
userInstalledRoot: string,
env: NodeJS.ProcessEnv = process.env,
): Promise<DesignSystemAssets> {
if (!isDesignTokenChannelEnabled(env)) {
return {
usageMd: undefined,
tokensCss: undefined,
fixtureHtml: undefined,
componentsManifest: undefined,
pullIndex: undefined,
importMode: undefined,
craftApplies: undefined,
craftExemptions: undefined,
};
}
const fingerprint = await designSystemAssetsCacheFingerprint(
designSystemId,
builtInRoot,
userInstalledRoot,
env,
);
const cacheKey = [
designSystemId,
builtInRoot,
userInstalledRoot,
env.OD_DESIGN_TOKEN_CHANNEL ?? '',
fingerprint,
].join('\0');
const cached = designSystemAssetsCache.get(cacheKey);
if (cached) return cached;
const pending = resolveDesignSystemAssetsUncached(
designSystemId,
builtInRoot,
userInstalledRoot,
)
.then((assets) => {
designSystemAssetsCache.set(cacheKey, assets);
pruneDesignSystemAssetsCache();
return assets;
})
.catch((error) => {
designSystemAssetsCache.delete(cacheKey);
throw error;
});
designSystemAssetsCache.set(cacheKey, pending);
pruneDesignSystemAssetsCache();
return pending;
}
async function resolveDesignSystemAssetsUncached(
designSystemId: string,
builtInRoot: string,
userInstalledRoot: string,
): Promise<DesignSystemAssets> {
if (designSystemId.startsWith('user:')) {
return readDesignSystemAssets(userInstalledRoot, designSystemId);
}
const builtIn = await readDesignSystemAssets(builtInRoot, designSystemId);
if (builtIn.tokensCss !== undefined && builtIn.fixtureHtml !== undefined) {
return builtIn;
}
const userInstalled = await readDesignSystemAssets(userInstalledRoot, designSystemId);
return withComponentsManifest(designSystemId, {
usageMd: builtIn.usageMd ?? userInstalled.usageMd,
tokensCss: builtIn.tokensCss ?? userInstalled.tokensCss,
fixtureHtml: builtIn.fixtureHtml ?? userInstalled.fixtureHtml,
componentsManifestJson: undefined,
componentsManifest: builtIn.componentsManifest ?? userInstalled.componentsManifest,
pullIndex: builtIn.pullIndex ?? userInstalled.pullIndex,
importMode: builtIn.importMode ?? userInstalled.importMode,
craftApplies: builtIn.craftApplies ?? userInstalled.craftApplies,
craftExemptions: builtIn.craftExemptions ?? userInstalled.craftExemptions,
});
}
function pruneDesignSystemAssetsCache(): void {
while (designSystemAssetsCache.size > DESIGN_SYSTEM_ASSETS_CACHE_LIMIT) {
const oldest = designSystemAssetsCache.keys().next().value;
if (oldest === undefined) return;
designSystemAssetsCache.delete(oldest);
}
}
async function designSystemAssetsCacheFingerprint(
designSystemId: string,
builtInRoot: string,
userInstalledRoot: string,
env: NodeJS.ProcessEnv,
): Promise<string> {
const roots = designSystemId.startsWith('user:')
? [designSystemAssetsRootFingerprint(userInstalledRoot, designSystemId)]
: [
designSystemAssetsRootFingerprint(builtInRoot, designSystemId),
designSystemAssetsRootFingerprint(userInstalledRoot, designSystemId),
];
const payload = {
tokenChannel: env.OD_DESIGN_TOKEN_CHANNEL ?? null,
roots: await Promise.all(roots),
};
return createHash('sha256').update(JSON.stringify(payload), 'utf8').digest('hex');
}
async function designSystemAssetsRootFingerprint(
root: string,
id: string,
): Promise<unknown> {
const dirId = stripPrefixAndValidateId(id, id.startsWith('user:') ? 'user:' : '');
if (!dirId) return { root, id, invalid: true };
const brandRoot = path.join(root, dirId);
const manifest = await readProjectManifest(brandRoot, dirId);
const candidates = new Set<string>([
'manifest.json',
manifest?.usage ?? 'USAGE.md',
manifest?.files.tokens ?? 'tokens.css',
manifest?.files.components ?? 'components.html',
manifest?.componentsManifest ?? 'components.manifest.json',
]);
return {
root,
id,
files: await Promise.all(
Array.from(candidates)
.filter((filePath) => typeof filePath === 'string' && filePath.length > 0)
.sort()
.map(async (filePath) => fileFingerprint(brandRoot, filePath)),
),
};
}
async function fileFingerprint(root: string, relativePath: string): Promise<unknown> {
const cleanPath = sanitizeRelativeFilePath(relativePath);
if (!cleanPath) return { path: relativePath, unsafe: true };
try {
const stats = await stat(path.join(root, cleanPath));
return {
path: cleanPath,
size: stats.size,
mtimeMs: stats.mtimeMs,
isFile: stats.isFile(),
isDirectory: stats.isDirectory(),
};
} catch (err) {
if (isAbsenceError(err)) return { path: cleanPath, absent: true };