@usalyt/registry 0.0.0-stage → 0.0.1

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.
@@ -0,0 +1,442 @@
1
+ import fs from "fs-extra";
2
+ import path from "node:path";
3
+
4
+ export const REGISTRY_NAME = "usalyt";
5
+ export const REGISTRY_VERSION = "0.0.1";
6
+ export const REGISTRY_LICENSE = "GPL-3.0-only";
7
+ export const REGISTRY_SCHEMA_REFERENCE = "./schema/registry.schema.json";
8
+ export const REGISTRY_REPOSITORY = {
9
+ type: "git",
10
+ url: "git+https://github.com/Usalyt/ui.git",
11
+ directory: "usalyt/packages/registry",
12
+ } as const;
13
+
14
+ export interface RegistryFile {
15
+ path: string;
16
+ type: string;
17
+ content: string;
18
+ }
19
+
20
+ export interface RegistryItem {
21
+ name: string;
22
+ type: string;
23
+ title: string;
24
+ description: string;
25
+ license: string;
26
+ dependencies: string[];
27
+ devDependencies: string[];
28
+ registryDependencies: string[];
29
+ dependencyVersions: Record<string, string>;
30
+ files: RegistryFile[];
31
+ }
32
+
33
+ export interface Registry {
34
+ $schema: string;
35
+ name: string;
36
+ version: string;
37
+ license: string;
38
+ repository: typeof REGISTRY_REPOSITORY;
39
+ dependencyLicenses: Record<string, string>;
40
+ items: RegistryItem[];
41
+ }
42
+
43
+ export interface RegistryBuildStats {
44
+ primitives: number;
45
+ blocks: number;
46
+ libraries: number;
47
+ items: number;
48
+ }
49
+
50
+ export interface RegistryBuildResult {
51
+ registry: Registry;
52
+ json: string;
53
+ stats: RegistryBuildStats;
54
+ }
55
+
56
+ export interface RegistryBuildOptions {
57
+ /** UI source root that contains `components/`, `blocks/`, and `lib/`. */
58
+ sourceRoot: string;
59
+ /** Root of the `@usalyt/registry` package, used for the notices file. */
60
+ packageRoot: string;
61
+ }
62
+
63
+ interface UiPackageManifest {
64
+ name?: string;
65
+ dependencies?: Record<string, string>;
66
+ peerDependencies?: Record<string, string>;
67
+ }
68
+
69
+ const IMPORT_PATTERN =
70
+ /(?:import|export)\s+(?:[^"'()]*?\s+from\s+)?["']([^"']+)["']/g;
71
+
72
+ const RUNTIME_PEERS = new Set(["react", "react-dom"]);
73
+
74
+ const posix = path.posix;
75
+
76
+ function toTitle(name: string): string {
77
+ return name
78
+ .split("-")
79
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
80
+ .join(" ");
81
+ }
82
+
83
+ function extractSpecifiers(content: string): string[] {
84
+ const specifiers = new Set<string>();
85
+ for (const match of content.matchAll(IMPORT_PATTERN)) {
86
+ specifiers.add(match[1]);
87
+ }
88
+ return [...specifiers];
89
+ }
90
+
91
+ function packageNameFromSpecifier(specifier: string): string | null {
92
+ if (specifier.startsWith(".") || specifier.startsWith("node:")) {
93
+ return null;
94
+ }
95
+ const root = specifier.startsWith("@")
96
+ ? specifier.split("/").slice(0, 2).join("/")
97
+ : specifier.split("/")[0];
98
+ if (RUNTIME_PEERS.has(root)) {
99
+ return null;
100
+ }
101
+ return root;
102
+ }
103
+
104
+ function isItemSourceFile(fileName: string): boolean {
105
+ if (fileName.endsWith(".test.ts") || fileName.endsWith(".test.tsx")) {
106
+ return false;
107
+ }
108
+ if (fileName.endsWith(".stories.ts") || fileName.endsWith(".stories.tsx")) {
109
+ return false;
110
+ }
111
+ return fileName.endsWith(".ts") || fileName.endsWith(".tsx");
112
+ }
113
+
114
+ async function listItemDirectories(root: string): Promise<string[]> {
115
+ const entries = await fs.readdir(root, { withFileTypes: true });
116
+ return entries
117
+ .filter((entry) => entry.isDirectory())
118
+ .map((entry) => entry.name)
119
+ .sort();
120
+ }
121
+
122
+ async function readItemFiles(
123
+ sourceRoot: string,
124
+ kind: "components" | "blocks",
125
+ itemName: string,
126
+ type: string
127
+ ): Promise<RegistryFile[]> {
128
+ const itemDir = path.join(sourceRoot, kind, itemName);
129
+ const fileNames = (await fs.readdir(itemDir))
130
+ .filter(isItemSourceFile)
131
+ .sort();
132
+
133
+ const files: RegistryFile[] = [];
134
+ for (const fileName of fileNames) {
135
+ files.push({
136
+ path: `${kind}/${itemName}/${fileName}`,
137
+ type,
138
+ content: await fs.readFile(path.join(itemDir, fileName), "utf-8"),
139
+ });
140
+ }
141
+
142
+ return files;
143
+ }
144
+
145
+ function sourcePathFor(
146
+ itemName: string,
147
+ fileName: string,
148
+ kind: "components" | "blocks"
149
+ ): string {
150
+ return `${kind}/${itemName}/${fileName}`;
151
+ }
152
+
153
+ function resolveRelativeImport(
154
+ sourcePath: string,
155
+ specifier: string,
156
+ knownPaths: Set<string>
157
+ ): string | null {
158
+ if (!specifier.startsWith(".")) {
159
+ return null;
160
+ }
161
+
162
+ const base = posix.normalize(
163
+ posix.join(posix.dirname(sourcePath), specifier)
164
+ );
165
+ const candidates = [
166
+ base,
167
+ `${base}.tsx`,
168
+ `${base}.ts`,
169
+ `${base}/index.ts`,
170
+ `${base}/index.tsx`,
171
+ ];
172
+
173
+ return candidates.find((candidate) => knownPaths.has(candidate)) ?? null;
174
+ }
175
+
176
+ function sortedRecord(entries: Iterable<[string, string]>): Record<string, string> {
177
+ return Object.fromEntries(
178
+ [...entries].sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
179
+ );
180
+ }
181
+
182
+ async function readUiPackageManifest(
183
+ sourceRoot: string
184
+ ): Promise<UiPackageManifest> {
185
+ const candidates = [
186
+ path.resolve(sourceRoot, "..", "package.json"),
187
+ path.resolve(sourceRoot, "package.json"),
188
+ ];
189
+
190
+ for (const candidate of candidates) {
191
+ if (!(await fs.pathExists(candidate))) {
192
+ continue;
193
+ }
194
+ const manifest = (await fs.readJson(candidate)) as UiPackageManifest;
195
+ if (manifest.name === "@usalyt/ui" && manifest.dependencies) {
196
+ return manifest;
197
+ }
198
+ }
199
+
200
+ throw new Error(
201
+ `Cannot find the @usalyt/ui package.json next to source root: ${sourceRoot}`
202
+ );
203
+ }
204
+
205
+ async function readNoticeLicenses(
206
+ packageRoot: string
207
+ ): Promise<Record<string, string>> {
208
+ const noticesPath = path.join(packageRoot, "THIRD_PARTY_NOTICES.md");
209
+ if (!(await fs.pathExists(noticesPath))) {
210
+ throw new Error(`Third-party notices file not found: ${noticesPath}`);
211
+ }
212
+
213
+ const licenses: Record<string, string> = {};
214
+ const text = await fs.readFile(noticesPath, "utf-8");
215
+
216
+ for (const rawLine of text.split("\n")) {
217
+ const line = rawLine.trimEnd();
218
+ const match = line.match(/^\| `([^`]+)` \| [^|]+ \| ([^|]+) \|$/);
219
+ if (match) {
220
+ licenses[match[1]] = match[2].trim();
221
+ }
222
+ }
223
+
224
+ return licenses;
225
+ }
226
+
227
+ function buildDependencyLicenses(
228
+ directDependencyNames: string[],
229
+ notices: Record<string, string>
230
+ ): Record<string, string> {
231
+ const entries: Array<[string, string]> = [];
232
+ const missing: string[] = [];
233
+
234
+ for (const name of directDependencyNames) {
235
+ const license = notices[name];
236
+ if (!license) {
237
+ missing.push(name);
238
+ continue;
239
+ }
240
+ entries.push([name, license]);
241
+ }
242
+
243
+ if (missing.length > 0) {
244
+ throw new Error(
245
+ `Missing audited licenses in THIRD_PARTY_NOTICES.md for: ${missing.join(", ")}`
246
+ );
247
+ }
248
+
249
+ return sortedRecord(entries);
250
+ }
251
+
252
+ /**
253
+ * Builds the registry data from an explicit UI source root. The function only
254
+ * reads files below `sourceRoot` and the package-local notices file, and it
255
+ * never records absolute paths or timestamps.
256
+ */
257
+ export async function buildRegistry(
258
+ options: RegistryBuildOptions
259
+ ): Promise<RegistryBuildResult> {
260
+ const sourceRoot = path.resolve(options.sourceRoot);
261
+ const componentsDir = path.join(sourceRoot, "components");
262
+ const blocksDir = path.join(sourceRoot, "blocks");
263
+ const utilsPath = path.join(sourceRoot, "lib", "utils.ts");
264
+
265
+ if (!(await fs.pathExists(componentsDir))) {
266
+ throw new Error(`UI source root not found or incomplete: ${sourceRoot}`);
267
+ }
268
+ if (!(await fs.pathExists(blocksDir))) {
269
+ throw new Error(`UI blocks directory not found: ${blocksDir}`);
270
+ }
271
+ if (!(await fs.pathExists(utilsPath))) {
272
+ throw new Error(`Shared utils source not found: ${utilsPath}`);
273
+ }
274
+
275
+ const uiPackage = await readUiPackageManifest(sourceRoot);
276
+ const declaredVersions: Record<string, string> = {
277
+ ...(uiPackage.dependencies ?? {}),
278
+ ...(uiPackage.peerDependencies ?? {}),
279
+ };
280
+
281
+ const primitiveNames = await listItemDirectories(componentsDir);
282
+ const blockNames = await listItemDirectories(blocksDir);
283
+
284
+ const sourceIndex = new Map<string, string>();
285
+ for (const name of primitiveNames) {
286
+ for (const fileName of (await fs.readdir(path.join(componentsDir, name))).sort()) {
287
+ if (isItemSourceFile(fileName)) {
288
+ sourceIndex.set(sourcePathFor(name, fileName, "components"), name);
289
+ }
290
+ }
291
+ }
292
+ for (const name of blockNames) {
293
+ for (const fileName of (await fs.readdir(path.join(blocksDir, name))).sort()) {
294
+ if (isItemSourceFile(fileName)) {
295
+ sourceIndex.set(sourcePathFor(name, fileName, "blocks"), name);
296
+ }
297
+ }
298
+ }
299
+ sourceIndex.set("lib/utils.ts", "utils");
300
+
301
+ const knownPaths = new Set(sourceIndex.keys());
302
+
303
+ const registryDependenciesFor = (itemName: string, files: RegistryFile[]): string[] => {
304
+ const dependencies = new Set<string>();
305
+ for (const file of files) {
306
+ for (const specifier of extractSpecifiers(file.content)) {
307
+ const resolved = resolveRelativeImport(file.path, specifier, knownPaths);
308
+ if (!resolved) {
309
+ continue;
310
+ }
311
+ const dependency = sourceIndex.get(resolved);
312
+ if (dependency && dependency !== itemName) {
313
+ dependencies.add(dependency);
314
+ }
315
+ }
316
+ }
317
+ return [...dependencies].sort();
318
+ };
319
+
320
+ const dependencyVersionsFor = (
321
+ itemName: string,
322
+ files: RegistryFile[]
323
+ ): { dependencies: string[]; dependencyVersions: Record<string, string> } => {
324
+ const dependencies = new Set<string>();
325
+
326
+ for (const file of files) {
327
+ for (const specifier of extractSpecifiers(file.content)) {
328
+ const packageName = packageNameFromSpecifier(specifier);
329
+ if (!packageName) {
330
+ continue;
331
+ }
332
+ if (!declaredVersions[packageName]) {
333
+ throw new Error(
334
+ `${itemName}: imported package "${packageName}" is not declared by @usalyt/ui`
335
+ );
336
+ }
337
+ dependencies.add(packageName);
338
+ }
339
+ }
340
+
341
+ const sortedDependencies = [...dependencies].sort();
342
+ return {
343
+ dependencies: sortedDependencies,
344
+ dependencyVersions: sortedRecord(
345
+ sortedDependencies.map((name) => [name, declaredVersions[name]])
346
+ ),
347
+ };
348
+ };
349
+
350
+ const items: RegistryItem[] = [];
351
+
352
+ for (const name of primitiveNames) {
353
+ const files = await readItemFiles(sourceRoot, "components", name, "registry:ui");
354
+ const title = toTitle(name);
355
+ const { dependencies, dependencyVersions } = dependencyVersionsFor(name, files);
356
+
357
+ items.push({
358
+ name,
359
+ type: "registry:ui",
360
+ title,
361
+ description: `Accessible ${title} primitive component built with Base UI and Tailwind v4.`,
362
+ license: REGISTRY_LICENSE,
363
+ dependencies,
364
+ devDependencies: [],
365
+ registryDependencies: registryDependenciesFor(name, files),
366
+ dependencyVersions,
367
+ files,
368
+ });
369
+ }
370
+
371
+ for (const name of blockNames) {
372
+ const files = await readItemFiles(sourceRoot, "blocks", name, "registry:block");
373
+ const title = toTitle(name);
374
+ const { dependencies, dependencyVersions } = dependencyVersionsFor(name, files);
375
+
376
+ items.push({
377
+ name,
378
+ type: "registry:block",
379
+ title: `${title} Block`,
380
+ description: `Composed ${title} block built from Usalyt primitives, Base UI and Tailwind v4.`,
381
+ license: REGISTRY_LICENSE,
382
+ dependencies,
383
+ devDependencies: [],
384
+ registryDependencies: registryDependenciesFor(name, files),
385
+ dependencyVersions,
386
+ files,
387
+ });
388
+ }
389
+
390
+ const utilsFiles: RegistryFile[] = [
391
+ {
392
+ path: "lib/utils.ts",
393
+ type: "registry:lib",
394
+ content: await fs.readFile(utilsPath, "utf-8"),
395
+ },
396
+ ];
397
+ const utilsDependencies = dependencyVersionsFor("utils", utilsFiles);
398
+
399
+ items.push({
400
+ name: "utils",
401
+ type: "registry:lib",
402
+ title: "Utils",
403
+ description: "Shared cn() class merge utility for Usalyt components.",
404
+ license: REGISTRY_LICENSE,
405
+ dependencies: utilsDependencies.dependencies,
406
+ devDependencies: [],
407
+ registryDependencies: registryDependenciesFor("utils", utilsFiles),
408
+ dependencyVersions: utilsDependencies.dependencyVersions,
409
+ files: utilsFiles,
410
+ });
411
+
412
+ items.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));
413
+
414
+ const notices = await readNoticeLicenses(options.packageRoot);
415
+ const directDependencyNames = [
416
+ ...new Set([
417
+ ...Object.keys(uiPackage.dependencies ?? {}),
418
+ ...Object.keys(uiPackage.peerDependencies ?? {}),
419
+ ]),
420
+ ].sort();
421
+
422
+ const registry: Registry = {
423
+ $schema: REGISTRY_SCHEMA_REFERENCE,
424
+ name: REGISTRY_NAME,
425
+ version: REGISTRY_VERSION,
426
+ license: REGISTRY_LICENSE,
427
+ repository: REGISTRY_REPOSITORY,
428
+ dependencyLicenses: buildDependencyLicenses(directDependencyNames, notices),
429
+ items,
430
+ };
431
+
432
+ return {
433
+ registry,
434
+ json: `${JSON.stringify(registry, null, 2)}\n`,
435
+ stats: {
436
+ primitives: primitiveNames.length,
437
+ blocks: blockNames.length,
438
+ libraries: 1,
439
+ items: items.length,
440
+ },
441
+ };
442
+ }