sordo 0.4.0 → 1.0.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 (152) hide show
  1. package/CHANGELOG.md +6 -116
  2. package/README.md +8 -175
  3. package/bin/sordo.ts +1 -4
  4. package/package.json +17 -41
  5. package/src/agents-md.ts +1 -0
  6. package/src/ai.ts +1 -0
  7. package/src/build.ts +1 -0
  8. package/src/client.ts +1 -0
  9. package/src/config.ts +1 -0
  10. package/src/dev.ts +1 -0
  11. package/src/index.ts +1 -55
  12. package/src/middleware.ts +1 -0
  13. package/src/plugin.ts +1 -0
  14. package/src/render.ts +1 -0
  15. package/src/router.ts +1 -0
  16. package/src/server.ts +1 -0
  17. package/CLAUDE.md +0 -124
  18. package/src/adapters/bun.ts +0 -59
  19. package/src/adapters/edge.ts +0 -75
  20. package/src/adapters/types.ts +0 -43
  21. package/src/agents-md/collect.ts +0 -113
  22. package/src/agents-md/generate.ts +0 -44
  23. package/src/agents-md/index.ts +0 -9
  24. package/src/agents-md/render.ts +0 -150
  25. package/src/agents-md/subprocess-entry.ts +0 -92
  26. package/src/agents-md/subprocess-runner.ts +0 -111
  27. package/src/agents-md/write.ts +0 -38
  28. package/src/agents-md/zod-to-json-schema.ts +0 -18
  29. package/src/ai/context.ts +0 -72
  30. package/src/ai/define.ts +0 -15
  31. package/src/ai/errors.ts +0 -51
  32. package/src/ai/index.ts +0 -36
  33. package/src/ai/middleware.ts +0 -21
  34. package/src/ai/registry.ts +0 -96
  35. package/src/ai/run.ts +0 -185
  36. package/src/ai/scan.ts +0 -42
  37. package/src/ai/stream.ts +0 -71
  38. package/src/ai/triggers.ts +0 -124
  39. package/src/ai/types.ts +0 -67
  40. package/src/ai/validate.ts +0 -82
  41. package/src/build/assets.ts +0 -48
  42. package/src/build/client-entry.ts +0 -43
  43. package/src/build/css.ts +0 -102
  44. package/src/build/embedded.ts +0 -66
  45. package/src/build/hash.ts +0 -21
  46. package/src/build/index.ts +0 -480
  47. package/src/build/macros/agents-hash.macro.ts +0 -9
  48. package/src/build/macros/agents.macro.ts +0 -21
  49. package/src/build/macros/env.macro.ts +0 -25
  50. package/src/build/macros/inline-assets.macro.ts +0 -28
  51. package/src/build/macros/manifest.macro.ts +0 -8
  52. package/src/build/macros/routes.macro.ts +0 -10
  53. package/src/build/page-entry.ts +0 -136
  54. package/src/build/scan-islands.ts +0 -39
  55. package/src/build/server-entry.ts +0 -256
  56. package/src/cli/ansi.ts +0 -41
  57. package/src/cli/build.ts +0 -195
  58. package/src/cli/commands/add/apply.ts +0 -31
  59. package/src/cli/commands/add/component-diff.ts +0 -116
  60. package/src/cli/commands/add/diff.ts +0 -153
  61. package/src/cli/commands/add/internal.ts +0 -41
  62. package/src/cli/commands/add/load-catalog.ts +0 -22
  63. package/src/cli/commands/add/peer-deps.ts +0 -115
  64. package/src/cli/commands/add/registry-fetch.ts +0 -122
  65. package/src/cli/commands/add/shadcn.ts +0 -285
  66. package/src/cli/commands/add/source.ts +0 -273
  67. package/src/cli/commands/add/stamper.ts +0 -73
  68. package/src/cli/commands/add/tokens.ts +0 -81
  69. package/src/cli/commands/add/ui-paths.ts +0 -113
  70. package/src/cli/commands/add.ts +0 -427
  71. package/src/cli/commands/deploy.ts +0 -143
  72. package/src/cli/commands/migrate.ts +0 -149
  73. package/src/cli/commands/secret.ts +0 -316
  74. package/src/cli/commands/ui/build.ts +0 -111
  75. package/src/cli/commands/ui/init.ts +0 -135
  76. package/src/cli/commands/ui/migrate/git-guard.ts +0 -19
  77. package/src/cli/commands/ui/migrate/radix.ts +0 -67
  78. package/src/cli/commands/ui/migrate/rtl.ts +0 -148
  79. package/src/cli/commands/ui/shadcn.ts +0 -82
  80. package/src/cli/commands/ui/view.ts +0 -63
  81. package/src/cli/commands/ui.ts +0 -86
  82. package/src/cli/commands/update.ts +0 -134
  83. package/src/cli/commands/upgrade.ts +0 -53
  84. package/src/cli/commands/view.ts +0 -34
  85. package/src/cli/dev.ts +0 -393
  86. package/src/cli/doctor/config-checks.ts +0 -63
  87. package/src/cli/doctor/deps.ts +0 -295
  88. package/src/cli/doctor/hydrate.ts +0 -65
  89. package/src/cli/doctor/monorepo.ts +0 -158
  90. package/src/cli/doctor/probes.ts +0 -16
  91. package/src/cli/doctor/report.ts +0 -72
  92. package/src/cli/doctor/toolchain.ts +0 -95
  93. package/src/cli/doctor/types.ts +0 -36
  94. package/src/cli/doctor.ts +0 -127
  95. package/src/cli/index.ts +0 -168
  96. package/src/cli/log.ts +0 -135
  97. package/src/cli/run/affected.ts +0 -79
  98. package/src/cli/run/cache-key.ts +0 -177
  99. package/src/cli/run/cache-store.ts +0 -0
  100. package/src/cli/run/files.ts +0 -96
  101. package/src/cli/run/git.ts +0 -13
  102. package/src/cli/run/runner.ts +0 -189
  103. package/src/cli/run/workspace.ts +0 -216
  104. package/src/cli/run.ts +0 -184
  105. package/src/cli/start.ts +0 -99
  106. package/src/cli/update-check.ts +0 -157
  107. package/src/client/index.ts +0 -65
  108. package/src/client/link.tsx +0 -61
  109. package/src/client/page.ts +0 -250
  110. package/src/config/define.ts +0 -5
  111. package/src/config/env.ts +0 -36
  112. package/src/config/load.ts +0 -152
  113. package/src/config/schema.ts +0 -135
  114. package/src/config/secrets.ts +0 -108
  115. package/src/dev/client.ts +0 -112
  116. package/src/dev/hot.ts +0 -24
  117. package/src/dev/index.ts +0 -4
  118. package/src/dev/tree.ts +0 -95
  119. package/src/dev/watcher.ts +0 -95
  120. package/src/internal/hmr-client.ts +0 -52
  121. package/src/internal/open-in-editor.ts +0 -23
  122. package/src/internal/runtime.ts +0 -30
  123. package/src/middleware/cookie-jar.ts +0 -135
  124. package/src/middleware/cookies.ts +0 -60
  125. package/src/middleware/index.ts +0 -127
  126. package/src/middleware/request-id.ts +0 -22
  127. package/src/middleware/response-helpers.ts +0 -25
  128. package/src/plugin/index.ts +0 -109
  129. package/src/render/bootstrap.ts +0 -44
  130. package/src/render/dev-error.tsx +0 -73
  131. package/src/render/index.tsx +0 -261
  132. package/src/render/island.tsx +0 -33
  133. package/src/render/meta.tsx +0 -48
  134. package/src/render/shell.tsx +0 -41
  135. package/src/router/conflict.ts +0 -20
  136. package/src/router/filesystem.ts +0 -37
  137. package/src/router/index.ts +0 -247
  138. package/src/router/match.ts +0 -91
  139. package/src/router/pattern.ts +0 -88
  140. package/src/server/index.ts +0 -250
  141. package/src/server/inline-assets.ts +0 -39
  142. package/src/types.ts +0 -53
  143. package/src/ui/schema.ts +0 -68
  144. package/src/ui/types.ts +0 -10
  145. package/templates/_internal/cn.ts +0 -6
  146. package/templates/_internal/slot.ts +0 -50
  147. package/templates/_internal/variants.ts +0 -1
  148. package/templates/themes/neutral/tokens.css +0 -46
  149. package/templates/themes/slate/tokens.css +0 -46
  150. package/templates/themes/stone/tokens.css +0 -46
  151. package/templates/themes/zinc/tokens.css +0 -46
  152. package/templates/tokens.css +0 -46
@@ -1,285 +0,0 @@
1
- import { basename } from "node:path";
2
- import { z } from "zod";
3
- import { SafeRelPath } from "../../../ui/schema.ts";
4
- import type { ComponentEntry, ComponentFile } from "../../../ui/types.ts";
5
- import { type ComponentPayload, RegistryError } from "./registry-fetch.ts";
6
- import { assertAppFileAllowed } from "./ui-paths.ts";
7
-
8
- // Adapter from the upstream shadcn/ui registry-item JSON
9
- // (https://ui.shadcn.com/schema/registry-item.json) to a sordo payload. The
10
- // stamped source stays byte-for-byte upstream except for the
11
- // `@/registry/<style>/…` → `@/…` import rewrite the shadcn CLI applies too.
12
-
13
- // Built-in namespaces, overridable via config.ui.registries. new-york-v4 is the
14
- // Tailwind v4 style, matching the sordo token pipeline.
15
- export const DEFAULT_REGISTRIES: Record<string, string> = {
16
- "@shadcn": "https://ui.shadcn.com/r/styles/new-york-v4",
17
- };
18
-
19
- const ItemType = z.enum([
20
- "registry:ui",
21
- "registry:lib",
22
- "registry:hook",
23
- "registry:component",
24
- "registry:block",
25
- "registry:page",
26
- "registry:file",
27
- ]);
28
-
29
- const CssVars = z.record(z.string(), z.string());
30
-
31
- // Validated strictly where the mapper depends on a field; everything else
32
- // (`$schema`, title, docs, meta, …) passes through untouched.
33
- const ShadcnItemSchema = z.object({
34
- name: z.string().min(1),
35
- type: ItemType,
36
- dependencies: z.array(z.string()).optional(),
37
- devDependencies: z.array(z.string()).optional(),
38
- registryDependencies: z.array(z.string()).optional(),
39
- files: z
40
- .array(
41
- z.object({
42
- path: z.string().min(1),
43
- content: z.string(),
44
- type: ItemType,
45
- target: z.string().optional(),
46
- }),
47
- )
48
- .min(1),
49
- cssVars: z
50
- .object({
51
- theme: CssVars.optional(),
52
- light: CssVars.optional(),
53
- dark: CssVars.optional(),
54
- })
55
- .optional(),
56
- });
57
-
58
- type ShadcnItem = z.infer<typeof ShadcnItemSchema>;
59
-
60
- export interface MappedItem {
61
- payload: ComponentPayload;
62
- // Upstream names, `@ns/name` refs, or URLs this item needs stamped first.
63
- registryDeps: string[];
64
- // Deps declared without a version; the caller pins them before stamping.
65
- unpinned: string[];
66
- }
67
-
68
- // A shadcn item has typed `files` with inline `content` and no sordo
69
- // `entry` wrapper.
70
- export function isShadcnItem(raw: unknown): boolean {
71
- if (typeof raw !== "object" || raw === null || "entry" in raw) return false;
72
- const r = raw as { type?: unknown; files?: unknown };
73
- return (
74
- typeof r.type === "string" &&
75
- r.type.startsWith("registry:") &&
76
- Array.isArray(r.files)
77
- );
78
- }
79
-
80
- export function parseShadcnItem(raw: unknown, source: string): ShadcnItem {
81
- const parsed = ShadcnItemSchema.safeParse(raw);
82
- if (!parsed.success) {
83
- throw new RegistryError(
84
- `shadcn registry item from ${source} has an unsupported shape: ${parsed.error.issues
85
- .map((i) => `${i.path.join(".") || "<root>"}: ${i.message}`)
86
- .join("; ")}`,
87
- );
88
- }
89
- return parsed.data;
90
- }
91
-
92
- const REGISTRY_IMPORT_RE =
93
- /(["'])@\/registry\/[^/"']+\/(ui|lib|hooks|components|blocks)\/([^"']+)\1/g;
94
-
95
- const ALIAS_DIR: Record<string, string> = {
96
- ui: "components/ui",
97
- lib: "lib",
98
- hooks: "hooks",
99
- components: "components",
100
- blocks: "components",
101
- };
102
-
103
- // `@/registry/new-york-v4/ui/button` → `@/components/ui/button`, the same
104
- // default-alias rewrite `npx shadcn add` performs. Nothing else is touched.
105
- export function rewriteRegistryImports(source: string): string {
106
- return source.replace(
107
- REGISTRY_IMPORT_RE,
108
- (_m, q: string, kind: string, rest: string) =>
109
- `${q}@/${ALIAS_DIR[kind] ?? kind}/${rest}${q}`,
110
- );
111
- }
112
-
113
- // Sibling registry items a file imports. Upstream items don't always list
114
- // these in `registryDependencies`, but the stamped file can't build without
115
- // them.
116
- function inferRegistryDeps(source: string): string[] {
117
- const out: string[] = [];
118
- for (const m of source.matchAll(REGISTRY_IMPORT_RE)) {
119
- const rest = m[3] ?? "";
120
- const name = rest.split("/")[0]?.replace(/\.[jt]sx?$/, "");
121
- if (name) out.push(name);
122
- }
123
- return out;
124
- }
125
-
126
- const BARE_IMPORT_RE =
127
- /(?:from|import)\s*["']([^"'./@][^"']*|@[^/"']+\/[^"']+)["']/g;
128
- // Provided by every sordo app; never written into package.json.
129
- const HOST_PACKAGES = new Set(["react", "react-dom"]);
130
-
131
- // npm packages a file imports. Upstream items sometimes omit one from
132
- // `dependencies` (button → class-variance-authority) because the shadcn CLI
133
- // assumes its init already installed it.
134
- function inferPackageDeps(source: string): string[] {
135
- const out: string[] = [];
136
- for (const m of source.matchAll(BARE_IMPORT_RE)) {
137
- const spec = m[1] ?? "";
138
- const parts = spec.split("/");
139
- const name = spec.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
140
- if (name && !HOST_PACKAGES.has(name) && !name.startsWith("bun:")) {
141
- out.push(name);
142
- }
143
- }
144
- return out;
145
- }
146
-
147
- function destination(
148
- file: ShadcnItem["files"][number],
149
- ): Pick<ComponentFile, "to" | "root"> {
150
- const base = basename(file.path);
151
- if (file.target) {
152
- // Targets are project-relative upstream. Only app/{components,hooks,lib}
153
- // is honored; anything else (routes, config, dotfiles) is refused.
154
- const rel = file.target
155
- .replace(/^~\//, "")
156
- .replace(/^\.\//, "")
157
- .replace(/^app\//, "");
158
- const dest: ComponentFile = { from: "", to: rel, root: "app" };
159
- const safe = SafeRelPath.safeParse(rel);
160
- try {
161
- if (!safe.success) throw new Error("unsafe path");
162
- assertAppFileAllowed(dest);
163
- } catch {
164
- throw new RegistryError(
165
- `shadcn file target ${file.target} is outside app/{components,hooks,lib}; refusing to stamp it`,
166
- );
167
- }
168
- return { to: rel, root: "app" };
169
- }
170
- switch (file.type) {
171
- case "registry:ui":
172
- return { to: base };
173
- case "registry:lib":
174
- return { to: `lib/${base}`, root: "app" };
175
- case "registry:hook":
176
- return { to: `hooks/${base}`, root: "app" };
177
- case "registry:component":
178
- case "registry:block":
179
- return { to: `components/${base}`, root: "app" };
180
- default:
181
- throw new RegistryError(
182
- `shadcn file ${file.path} (${file.type}) needs a \`target\``,
183
- );
184
- }
185
- }
186
-
187
- // `name@range` with scoped names (`@radix-ui/react-dialog@^1.1.0`).
188
- export function splitDep(spec: string): { name: string; range?: string } {
189
- const at = spec.lastIndexOf("@");
190
- if (at > 0) return { name: spec.slice(0, at), range: spec.slice(at + 1) };
191
- return { name: spec };
192
- }
193
-
194
- function tokenBlock(group: string, cssVars: ShadcnItem["cssVars"]): string {
195
- const rule = (selector: string, vars?: Record<string, string>) =>
196
- vars && Object.keys(vars).length > 0
197
- ? `${selector} {\n${Object.entries(vars)
198
- .map(([k, v]) => ` --${k}: ${v};`)
199
- .join("\n")}\n}\n`
200
- : "";
201
- return `/* @sordo:tokens ${group} */
202
- ${rule("@theme inline", cssVars?.theme)}${rule(":root", cssVars?.light)}${rule(".dark", cssVars?.dark)}/* @sordo:end ${group} */`;
203
- }
204
-
205
- export function mapShadcnItem(item: ShadcnItem, source: string): MappedItem {
206
- const templates: Record<string, string> = {};
207
- const files: ComponentFile[] = [];
208
- const inferred: string[] = [];
209
- const importedPackages: string[] = [];
210
- for (const f of item.files) {
211
- const dest = destination(f);
212
- const from = `shadcn/${dest.root ?? "components"}/${dest.to}`;
213
- templates[from] = rewriteRegistryImports(f.content);
214
- inferred.push(...inferRegistryDeps(f.content));
215
- importedPackages.push(...inferPackageDeps(f.content));
216
- // Omit `root` for component files so the entry validates against older
217
- // schemas too.
218
- files.push(dest.root ? { from, ...dest } : { from, to: dest.to });
219
- }
220
-
221
- const peerDeps: Record<string, string> = {};
222
- const unpinned: string[] = [];
223
- for (const spec of item.dependencies ?? []) {
224
- const { name, range } = splitDep(spec);
225
- peerDeps[name] = range ?? "latest";
226
- if (!range) unpinned.push(name);
227
- }
228
- for (const name of importedPackages) {
229
- if (name in peerDeps) continue;
230
- peerDeps[name] = "latest";
231
- unpinned.push(name);
232
- }
233
-
234
- let tokens: string[] | undefined;
235
- const vars = item.cssVars;
236
- if (vars && (vars.theme || vars.light || vars.dark)) {
237
- const group = `shadcn-${item.name}`;
238
- templates["tokens.css"] = tokenBlock(group, vars);
239
- tokens = [group];
240
- }
241
-
242
- const entry: ComponentEntry = {
243
- name: item.name,
244
- spec: `shadcn:${source}`,
245
- phase: 0,
246
- kind: item.type === "registry:block" ? "recipe" : "primitive",
247
- // Hydration is the page's job (`export const hydrate = true`), not the
248
- // component's.
249
- island: "no",
250
- status: "completed",
251
- files,
252
- peerDeps,
253
- internalHelpers: [],
254
- ...(tokens ? { tokens } : {}),
255
- };
256
-
257
- const registryDeps = [
258
- ...new Set([...(item.registryDependencies ?? []), ...inferred]),
259
- ].filter((d) => d !== item.name);
260
-
261
- return { payload: { entry, templates }, registryDeps, unpinned };
262
- }
263
-
264
- // Turn bare `latest` into `^<current>` via the npm registry so stamped apps
265
- // don't float on every install. Best effort: offline keeps `latest`.
266
- export async function pinDeps(
267
- peerDeps: Record<string, string>,
268
- names: string[],
269
- fetchImpl: typeof fetch = fetch,
270
- ): Promise<Record<string, string>> {
271
- const out = { ...peerDeps };
272
- await Promise.all(
273
- names.map(async (name) => {
274
- try {
275
- const res = await fetchImpl(
276
- `https://registry.npmjs.org/${name}/latest`,
277
- );
278
- if (!res.ok) return;
279
- const { version } = (await res.json()) as { version?: unknown };
280
- if (typeof version === "string") out[name] = `^${version}`;
281
- } catch {}
282
- }),
283
- );
284
- return out;
285
- }
@@ -1,273 +0,0 @@
1
- import { mkdtemp, rm } from "node:fs/promises";
2
- import { tmpdir } from "node:os";
3
- import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
4
- import type { ComponentEntry } from "../../../ui/types.ts";
5
- import { log } from "../../log.ts";
6
- import type { Catalog } from "./load-catalog.ts";
7
- import {
8
- type ComponentPayload,
9
- componentTarget,
10
- fetchJson,
11
- parsePayload,
12
- RegistryError,
13
- readJsonFile,
14
- } from "./registry-fetch.ts";
15
- import {
16
- DEFAULT_REGISTRIES,
17
- isShadcnItem,
18
- mapShadcnItem,
19
- parseShadcnItem,
20
- pinDeps,
21
- } from "./shadcn.ts";
22
-
23
- // One resolved component ready for the stamp pipeline. `templatesDir` is the dir
24
- // the existing stamper/internal/tokens/view code reads source from — the
25
- // built-in catalog dir for catalog names, the file's own dir for a single local
26
- // file, or a throwaway temp dir for materialized remote payloads.
27
- export interface ResolvedSource {
28
- entry: ComponentEntry;
29
- templatesDir: string;
30
- fromCatalog: boolean;
31
- cleanup?: () => Promise<void>;
32
- }
33
-
34
- export interface ResolveOptions {
35
- catalog: Catalog;
36
- registries: Record<string, string>;
37
- cwd: string;
38
- allowInsecure: boolean;
39
- // Injectable for tests; forwarded to the registry fetch. Defaults to global.
40
- fetchImpl?: typeof fetch;
41
- }
42
-
43
- export type SourceKind =
44
- | { kind: "name"; name: string }
45
- | { kind: "namespaced"; ns: string; name: string }
46
- | { kind: "local"; path: string }
47
- | { kind: "url"; url: string };
48
-
49
- // Classify an `add` positional. Order matters: URL, then namespaced (`@ns/x`),
50
- // then path-like (prefix, embedded slash, or a source/payload extension),
51
- // otherwise a built-in catalog name (cli/15).
52
- export function classifySource(arg: string): SourceKind {
53
- if (/^https?:\/\//i.test(arg)) return { kind: "url", url: arg };
54
- if (arg.startsWith("@")) {
55
- const slash = arg.indexOf("/");
56
- if (slash > 0) {
57
- return {
58
- kind: "namespaced",
59
- ns: arg.slice(0, slash),
60
- name: arg.slice(slash + 1),
61
- };
62
- }
63
- }
64
- if (
65
- arg.startsWith("./") ||
66
- arg.startsWith("../") ||
67
- arg.startsWith("/") ||
68
- arg.includes("/") ||
69
- /\.(tsx?|jsx?|json)$/i.test(arg)
70
- ) {
71
- return { kind: "local", path: arg };
72
- }
73
- return { kind: "name", name: arg };
74
- }
75
-
76
- async function materialize(
77
- payload: ComponentPayload,
78
- ): Promise<{ templatesDir: string; cleanup: () => Promise<void> }> {
79
- const dir = await mkdtemp(join(tmpdir(), "sordo-reg-"));
80
- const root = resolve(dir);
81
- for (const [rel, contents] of Object.entries(payload.templates)) {
82
- // Defense-in-depth: the payload schema already rejects unsafe keys, but
83
- // never let a join escape the temp dir even if that boundary regresses.
84
- const dest = resolve(dir, rel);
85
- if (dest !== root && !dest.startsWith(root + sep)) {
86
- throw new RegistryError(`unsafe template path escapes temp dir: ${rel}`);
87
- }
88
- await Bun.write(dest, contents);
89
- }
90
- return {
91
- templatesDir: dir,
92
- cleanup: () => rm(dir, { recursive: true, force: true }),
93
- };
94
- }
95
-
96
- function synthLocalEntry(absPath: string, original: string): ComponentEntry {
97
- const base = basename(absPath);
98
- const name = base.replace(/\.(tsx|ts|jsx|js)$/i, "");
99
- return {
100
- name,
101
- spec: `local:${original}`,
102
- phase: 0,
103
- kind: "primitive",
104
- island: "no",
105
- status: "completed",
106
- files: [{ from: base, to: base }],
107
- peerDeps: {},
108
- internalHelpers: [],
109
- };
110
- }
111
-
112
- const isUrl = (s: string) => /^https?:\/\//i.test(s);
113
-
114
- // Load one registry document (URL or local .json) into stampable sources. A
115
- // sordo payload yields itself; a shadcn registry item is mapped, its deps
116
- // pinned, and its registryDependencies resolved first — depth-first, deduped
117
- // by target via `seen` so shared deps (e.g. `button`) stamp once.
118
- async function resolveRegistryTarget(
119
- target: string,
120
- opts: ResolveOptions,
121
- seen: Set<string>,
122
- ): Promise<ResolvedSource[]> {
123
- seen.add(target);
124
- const raw = isUrl(target)
125
- ? await fetchJson(target, {
126
- allowInsecure: opts.allowInsecure,
127
- fetchImpl: opts.fetchImpl,
128
- })
129
- : await readJsonFile(target);
130
- if (!isShadcnItem(raw)) {
131
- return [await materializeSource(parsePayload(raw))];
132
- }
133
- const mapped = mapShadcnItem(parseShadcnItem(raw, target), target);
134
- mapped.payload.entry.peerDeps = await pinDeps(
135
- mapped.payload.entry.peerDeps,
136
- mapped.unpinned,
137
- opts.fetchImpl,
138
- );
139
- // Re-validate the mapped entry against ComponentEntrySchema before stamping.
140
- const payload = parsePayload(mapped.payload);
141
- const out: ResolvedSource[] = [];
142
- for (const dep of mapped.registryDeps) {
143
- const depTarget = registryDepTarget(dep, target, opts);
144
- if (seen.has(depTarget)) continue;
145
- out.push(...(await resolveRegistryTarget(depTarget, opts, seen)));
146
- }
147
- out.push(await materializeSource(payload));
148
- return out;
149
- }
150
-
151
- // A shadcn registryDependency is a URL, an `@ns/name` ref, or a bare name
152
- // that lives next to the item that named it.
153
- function registryDepTarget(
154
- dep: string,
155
- parent: string,
156
- opts: ResolveOptions,
157
- ): string {
158
- if (isUrl(dep)) return dep;
159
- const kind = classifySource(dep);
160
- if (kind.kind === "namespaced")
161
- return namespacedTarget(kind.ns, kind.name, opts);
162
- const dir = isUrl(parent) ? new URL(".", parent).href : `${dirname(parent)}/`;
163
- return isUrl(dir) ? componentTarget(dir, dep) : join(dir, `${dep}.json`);
164
- }
165
-
166
- async function materializeSource(
167
- payload: ComponentPayload,
168
- ): Promise<ResolvedSource> {
169
- const mat = await materialize(payload);
170
- return {
171
- entry: payload.entry,
172
- templatesDir: mat.templatesDir,
173
- fromCatalog: false,
174
- cleanup: mat.cleanup,
175
- };
176
- }
177
-
178
- async function resolveLocal(
179
- path: string,
180
- opts: ResolveOptions,
181
- seen: Set<string>,
182
- ): Promise<ResolvedSource[]> {
183
- const abs = isAbsolute(path) ? path : resolve(opts.cwd, path);
184
- if (/\.json$/i.test(abs)) return resolveRegistryTarget(abs, opts, seen);
185
- if (!(await Bun.file(abs).exists())) {
186
- throw new RegistryError(`file not found: ${path}`);
187
- }
188
- return [
189
- {
190
- entry: synthLocalEntry(abs, path),
191
- templatesDir: dirname(abs),
192
- fromCatalog: false,
193
- },
194
- ];
195
- }
196
-
197
- function namespacedTarget(
198
- ns: string,
199
- name: string,
200
- opts: ResolveOptions,
201
- ): string {
202
- const base = opts.registries[ns] ?? DEFAULT_REGISTRIES[ns];
203
- if (!base) {
204
- throw new RegistryError(
205
- `no registry configured for namespace ${ns}; add it to config.ui.registries`,
206
- );
207
- }
208
- return isUrl(base)
209
- ? componentTarget(base, name)
210
- : join(isAbsolute(base) ? base : resolve(opts.cwd, base), `${name}.json`);
211
- }
212
-
213
- async function resolveOne(
214
- arg: string,
215
- opts: ResolveOptions,
216
- seen: Set<string>,
217
- ): Promise<ResolvedSource[]> {
218
- const kind = classifySource(arg);
219
- switch (kind.kind) {
220
- case "name": {
221
- const entry = opts.catalog.components.find((c) => c.name === kind.name);
222
- if (!entry) {
223
- throw new RegistryError(
224
- `unknown component: ${kind.name} (try @shadcn/${kind.name})`,
225
- );
226
- }
227
- return [
228
- {
229
- entry,
230
- templatesDir: opts.catalog.templatesDir,
231
- fromCatalog: true,
232
- },
233
- ];
234
- }
235
- case "namespaced":
236
- return resolveRegistryTarget(
237
- namespacedTarget(kind.ns, kind.name, opts),
238
- opts,
239
- seen,
240
- );
241
- case "url":
242
- return resolveRegistryTarget(kind.url, opts, seen);
243
- case "local":
244
- return resolveLocal(kind.path, opts, seen);
245
- }
246
- }
247
-
248
- // Resolve every positional into a stampable source. On the first failure logs
249
- // the reason, cleans up any temp dirs already materialized, and returns null so
250
- // the caller exits without writing anything.
251
- export async function resolveSources(
252
- args: string[],
253
- opts: ResolveOptions,
254
- ): Promise<ResolvedSource[] | null> {
255
- const out: ResolvedSource[] = [];
256
- const seen = new Set<string>();
257
- for (const arg of args) {
258
- try {
259
- out.push(...(await resolveOne(arg, opts, seen)));
260
- } catch (err) {
261
- log.error(err instanceof Error ? err.message : String(err));
262
- await cleanupSources(out);
263
- return null;
264
- }
265
- }
266
- return out;
267
- }
268
-
269
- export async function cleanupSources(sources: ResolvedSource[]): Promise<void> {
270
- for (const s of sources) {
271
- if (s.cleanup) await s.cleanup();
272
- }
273
- }
@@ -1,73 +0,0 @@
1
- import { dirname, resolve, sep } from "node:path";
2
- import type { ComponentEntry } from "../../../ui/types.ts";
3
- import { log } from "../../log.ts";
4
- import {
5
- assertAppFileAllowed,
6
- fileDest,
7
- fileRootDir,
8
- type UiPaths,
9
- } from "./ui-paths.ts";
10
-
11
- export interface StampPlan {
12
- from: string;
13
- to: string;
14
- exists: boolean;
15
- }
16
-
17
- export async function planStamp(
18
- entry: ComponentEntry,
19
- uiPaths: UiPaths,
20
- templatesDir: string,
21
- ): Promise<StampPlan[]> {
22
- const out: StampPlan[] = [];
23
- const tplRoot = resolve(templatesDir);
24
- for (const f of entry.files) {
25
- // Defense-in-depth: ComponentFileSchema already rejects unsafe from/to,
26
- // but assert each join stays within its root before any read/write.
27
- assertAppFileAllowed(f);
28
- const from = resolve(templatesDir, f.from);
29
- const compRoot = resolve(fileRootDir(uiPaths, f));
30
- const to = fileDest(uiPaths, f);
31
- if (from !== tplRoot && !from.startsWith(tplRoot + sep)) {
32
- throw new Error(
33
- `unsafe template source escapes templates dir: ${f.from}`,
34
- );
35
- }
36
- if (to !== compRoot && !to.startsWith(compRoot + sep)) {
37
- throw new Error(
38
- `unsafe component target escapes its destination dir: ${f.to}`,
39
- );
40
- }
41
- out.push({ from, to, exists: await Bun.file(to).exists() });
42
- }
43
- return out;
44
- }
45
-
46
- export async function applyStamp(
47
- plan: StampPlan[],
48
- opts: { force: boolean },
49
- ): Promise<{ written: number; skipped: number }> {
50
- let written = 0;
51
- let skipped = 0;
52
- for (const p of plan) {
53
- if (p.exists && !opts.force) {
54
- log.dim(` skip ${p.to} (exists)`);
55
- skipped++;
56
- continue;
57
- }
58
- const src = Bun.file(p.from);
59
- if (!(await src.exists())) {
60
- log.error(`missing template: ${p.from}`);
61
- throw new Error(`template not found: ${p.from}`);
62
- }
63
- await ensureDir(dirname(p.to));
64
- await Bun.write(p.to, src);
65
- log.success(` wrote ${p.to}`);
66
- written++;
67
- }
68
- return { written, skipped };
69
- }
70
-
71
- async function ensureDir(dir: string): Promise<void> {
72
- await Bun.$`mkdir -p ${dir}`.quiet();
73
- }
@@ -1,81 +0,0 @@
1
- import { dirname, join } from "node:path";
2
- import { log } from "../../log.ts";
3
- import type { UiPaths } from "./ui-paths.ts";
4
-
5
- const START = (group: string) => `/* @sordo:tokens ${group} */`;
6
- const END = (group: string) => `/* @sordo:end ${group} */`;
7
-
8
- // Resolve the token CSS to read from. A named theme reads the preset payload
9
- // under templates/themes/<name>/tokens.css; absent, the default token set.
10
- function tokenSourcePath(templatesDir: string, themeName?: string): string {
11
- return themeName
12
- ? join(templatesDir, "themes", themeName, "tokens.css")
13
- : join(templatesDir, "tokens.css");
14
- }
15
-
16
- // True if a named base-color preset ships in the catalog.
17
- export function themeExists(
18
- templatesDir: string,
19
- themeName: string,
20
- ): Promise<boolean> {
21
- return Bun.file(tokenSourcePath(templatesDir, themeName)).exists();
22
- }
23
-
24
- export async function mergeTokens(
25
- groups: string[],
26
- uiPaths: UiPaths,
27
- templatesDir: string,
28
- opts: { dryRun: boolean; themeName?: string; force?: boolean },
29
- ): Promise<{ added: string[] }> {
30
- if (groups.length === 0) return { added: [] };
31
- const sourcePath = tokenSourcePath(templatesDir, opts.themeName);
32
- if (!(await Bun.file(sourcePath).exists())) {
33
- throw new Error(`unknown theme preset: ${opts.themeName}`);
34
- }
35
- const source = await Bun.file(sourcePath).text();
36
- const target = uiPaths.tokensFile;
37
- const existing = (await Bun.file(target).exists())
38
- ? await Bun.file(target).text()
39
- : "";
40
- let out = existing;
41
- const added: string[] = [];
42
- for (const group of groups) {
43
- const block = extractBlock(source, group);
44
- if (!block) {
45
- log.warn(`token group "${group}" not found in templates/tokens.css`);
46
- continue;
47
- }
48
- const present = out.includes(START(group));
49
- if (present && !opts.force) continue;
50
- if (present) {
51
- out = replaceBlock(out, group, block);
52
- } else {
53
- if (out.length > 0 && !out.endsWith("\n")) out += "\n";
54
- out += `${block}\n`;
55
- }
56
- added.push(group);
57
- }
58
- if (added.length === 0) return { added: [] };
59
- if (!opts.dryRun) {
60
- await Bun.$`mkdir -p ${dirname(target)}`.quiet();
61
- await Bun.write(target, out);
62
- }
63
- for (const g of added) log.success(` tokens: +${g} -> ${target}`);
64
- return { added };
65
- }
66
-
67
- export function extractBlock(source: string, group: string): string | null {
68
- const start = source.indexOf(START(group));
69
- const end = source.indexOf(END(group));
70
- if (start === -1 || end === -1 || end < start) return null;
71
- return source.slice(start, end + END(group).length);
72
- }
73
-
74
- // Replace an existing fenced group block in `target` with `block`, preserving
75
- // everything outside the START…END markers. Used by --force re-merges.
76
- function replaceBlock(target: string, group: string, block: string): string {
77
- const start = target.indexOf(START(group));
78
- const end = target.indexOf(END(group));
79
- if (start === -1 || end === -1 || end < start) return target;
80
- return target.slice(0, start) + block + target.slice(end + END(group).length);
81
- }