designsource 0.9.0 → 0.10.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.
- package/README.md +3 -2
- package/dist/index.js +1025 -200
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -39,6 +39,10 @@ function accountMessageForResponse(status, body, api) {
|
|
|
39
39
|
if (status === 404) return LINKED_PROJECT_GONE;
|
|
40
40
|
return messageForResponse(status, body, api);
|
|
41
41
|
}
|
|
42
|
+
var SCOPE_LOGIN_AGAIN = "Your sign-in predates screen generation. Run npx designsource login again in this folder.";
|
|
43
|
+
var GENERATE_NEEDS_LOGIN = "Making screens needs the user's own sign-in: ask the user to run npx designsource login in a terminal in this folder, then restart this app. This app runs designsource with a project token, which can list, read and pull screens but not make them.";
|
|
44
|
+
var SCREEN_NOT_MADE = "The answer did not arrive, so the screen may or may not have been saved. Check the Screens view in the workbench (or call list_screens, which needs Pro) before trying again. A call that was interrupted can still be charged for the work that ran.";
|
|
45
|
+
var FUNDING_HINT = (api) => `Add credits or a key: ${api}/credits`;
|
|
42
46
|
|
|
43
47
|
// src/paths.ts
|
|
44
48
|
import { isAbsolute, resolve, sep } from "node:path";
|
|
@@ -156,7 +160,7 @@ function libOf(utilsFile, utilsAlias) {
|
|
|
156
160
|
return { libDir: dir === "." ? "" : dir, libAlias: slash > 0 ? utilsAlias.slice(0, slash) : "" };
|
|
157
161
|
}
|
|
158
162
|
function rewriteForApp(contents, t) {
|
|
159
|
-
return contents.replace(/(['"])@\/components\/ui\//g, (_, q) => `${q}${t.uiAlias}/`).replace(/(['"])@\/lib\/utils\1/g, (_, q) => `${q}${t.utilsAlias}${q}`).replace(/(['"])@\/components\/(design-system|blocks)\//g, (_, q, dir) => `${q}${t.componentsAlias}/${dir}/`).replace(/(['"])@\/components\/(preview-gallery|custom-surface|sample-surfaces|mockup-media|sample-media)\1/g, (_, q, file) => `${q}${t.componentsAlias}/${file}${q}`).replace(/(['"])@\/lib\/(mockup-schema|surface-inference|mockup-media)\1/g, (_, q, file) => `${q}${t.libAlias}/${file}${q}`);
|
|
163
|
+
return contents.replace(/(['"])@\/components\/ui\//g, (_, q) => `${q}${t.uiAlias}/`).replace(/(['"])@\/lib\/utils\1/g, (_, q) => `${q}${t.utilsAlias}${q}`).replace(/(['"])@\/components\/screens\//g, (_, q) => `${q}${t.componentsAlias}/screens/`).replace(/(['"])@\/components\/(design-system|blocks)\//g, (_, q, dir) => `${q}${t.componentsAlias}/${dir}/`).replace(/(['"])@\/components\/(preview-gallery|custom-surface|sample-surfaces|mockup-media|sample-media)\1/g, (_, q, file) => `${q}${t.componentsAlias}/${file}${q}`).replace(/(['"])@\/lib\/(mockup-schema|surface-inference|mockup-media)\1/g, (_, q, file) => `${q}${t.libAlias}/${file}${q}`);
|
|
160
164
|
}
|
|
161
165
|
|
|
162
166
|
// src/add/setup.ts
|
|
@@ -629,7 +633,7 @@ var isHttpUrl = (value) => {
|
|
|
629
633
|
}
|
|
630
634
|
};
|
|
631
635
|
var JSON_ENTRY_KEYS = /* @__PURE__ */ new Set(["command", "args", "type", "env"]);
|
|
632
|
-
var TOML_ENTRY_KEYS = /* @__PURE__ */ new Set(["command", "args", "startup_timeout_sec"]);
|
|
636
|
+
var TOML_ENTRY_KEYS = /* @__PURE__ */ new Set(["command", "args", "startup_timeout_sec", "tool_timeout_sec"]);
|
|
633
637
|
function isOurJsonEntry(entry) {
|
|
634
638
|
if (!isObject(entry) || !Object.keys(entry).every((k) => JSON_ENTRY_KEYS.has(k))) return false;
|
|
635
639
|
if (entry.type !== void 0 && entry.type !== "stdio") return false;
|
|
@@ -791,7 +795,7 @@ function insertJsonEntry(text, key, entry) {
|
|
|
791
795
|
var OURS = ["mcp_servers", "designsource"];
|
|
792
796
|
function codexTable(projectId, eol) {
|
|
793
797
|
const { command, args } = serverEntry(projectId);
|
|
794
|
-
return [`[mcp_servers.designsource]`, `command = "${command}"`, `args = [${args.map((a) => `"${a}"`).join(", ")}]`, "startup_timeout_sec = 60", ""].join(eol);
|
|
798
|
+
return [`[mcp_servers.designsource]`, `command = "${command}"`, `args = [${args.map((a) => `"${a}"`).join(", ")}]`, "startup_timeout_sec = 60", "tool_timeout_sec = 300", ""].join(eol);
|
|
795
799
|
}
|
|
796
800
|
function tomlLines(text) {
|
|
797
801
|
const lines = [];
|
|
@@ -943,10 +947,14 @@ function planToml(path, text, projectId) {
|
|
|
943
947
|
let args = null;
|
|
944
948
|
let hasEnv = false;
|
|
945
949
|
let otherKey = false;
|
|
950
|
+
let hasToolTimeout = false;
|
|
951
|
+
let lastContent = ours;
|
|
946
952
|
for (let n = ours + 1; n < lines.length && !headers[n]; n++) {
|
|
947
953
|
const line = lines[n];
|
|
954
|
+
if (!/^\s*(#.*)?$/.test(line.text)) lastContent = n;
|
|
948
955
|
const key = line.free ? tomlKey(line.text) : null;
|
|
949
956
|
if (key && (key.path.length !== 1 || !TOML_ENTRY_KEYS.has(key.path[0]))) otherKey = true;
|
|
957
|
+
if (key && key.path.length === 1 && key.path[0] === "tool_timeout_sec") hasToolTimeout = true;
|
|
950
958
|
if (key && key.path.length === 1 && (key.path[0] === "command" || key.path[0] === "args")) {
|
|
951
959
|
const values = tomlStrings(text, line.start + key.valueAt);
|
|
952
960
|
words.push(...key.path[0] === "command" ? values.flatMap((v) => v.split(/\s+/)) : values);
|
|
@@ -964,6 +972,13 @@ function planToml(path, text, projectId) {
|
|
|
964
972
|
if (!header || header.array || !samePath(header.path, [...OURS, "env"])) continue;
|
|
965
973
|
for (let m = n + 1; m < lines.length && !headers[m]; m++) if (lines[m].free && tomlKey(lines[m].text)) hasEnv = true;
|
|
966
974
|
}
|
|
975
|
+
const keeps = projectId === null && namesAProject(args) ? { keepsProject: true } : {};
|
|
976
|
+
if (!hasToolTimeout) {
|
|
977
|
+
let at = Math.min(lines[lastContent].end, text.length);
|
|
978
|
+
if (text[at - 1] === "\r") at--;
|
|
979
|
+
const contents = at >= text.length ? text + eol + "tool_timeout_sec = 300" + eol : text.slice(0, at) + eol + "tool_timeout_sec = 300" + text.slice(at);
|
|
980
|
+
return { path, status: "update", contents, hasEnv, ...keeps };
|
|
981
|
+
}
|
|
967
982
|
return { path, status: "unchanged", contents: text, hasEnv, ...projectId === null && namesAProject(args) ? { keepsProject: true } : {} };
|
|
968
983
|
}
|
|
969
984
|
let next = ours + 1;
|
|
@@ -976,6 +991,13 @@ function planToml(path, text, projectId) {
|
|
|
976
991
|
return { path, status: "update", contents: text.slice(0, lines[ours].start) + codexTable(projectId, eol) + text.slice(cut) };
|
|
977
992
|
}
|
|
978
993
|
|
|
994
|
+
// src/add/screen-rules.ts
|
|
995
|
+
var SCREEN_SLUG = /^[a-z][a-z0-9-]{0,39}$/;
|
|
996
|
+
var RESERVED_SCREEN_SLUGS = ["all", "shell", "app-shell", "parts"];
|
|
997
|
+
var SCREEN_COMPONENT = /^[A-Z][A-Za-z0-9]*Screen$/;
|
|
998
|
+
var SCREEN_PART_FILE = /^[a-z][a-z0-9-]*\.tsx?$/;
|
|
999
|
+
var SCREENS_QUERY_MAX = 50;
|
|
1000
|
+
|
|
979
1001
|
// src/args.ts
|
|
980
1002
|
var FRAMEWORKS = ["next", "vue", "svelte", "angular", "css"];
|
|
981
1003
|
var INTEGRATE_FRAMEWORKS = ["vue", "svelte", "angular", "css"];
|
|
@@ -998,10 +1020,11 @@ Run a command with --help for its options. In a terminal, no command shows a men
|
|
|
998
1020
|
`;
|
|
999
1021
|
var TOKEN_LINE = " --token the project token (workbench \u2192 Project settings); or DS_SYNC_TOKEN";
|
|
1000
1022
|
var API_LINE = ` --api API origin (default ${DEFAULT_API_ORIGIN})`;
|
|
1001
|
-
var CREATE_USAGE = `designsource create [folder] [--token <project token>] [--api <origin>] [--force]
|
|
1023
|
+
var CREATE_USAGE = `designsource create [folder] [--no-screens] [--token <project token>] [--api <origin>] [--force]
|
|
1002
1024
|
|
|
1003
|
-
Writes a runnable Next.js project from your design system. Asks for anything not given.
|
|
1025
|
+
Writes a runnable Next.js project from your design system, with your screens on /app. Asks for anything not given.
|
|
1004
1026
|
folder target folder (default ${CREATE_DEFAULT_FOLDER}); must be new or empty
|
|
1027
|
+
--no-screens leave the project's screens out (no /app routes)
|
|
1005
1028
|
${TOKEN_LINE}
|
|
1006
1029
|
${API_LINE}
|
|
1007
1030
|
--force overwrite files the starter writes in a non-empty folder
|
|
@@ -1015,7 +1038,7 @@ ${TOKEN_LINE}
|
|
|
1015
1038
|
${API_LINE}
|
|
1016
1039
|
--force overwrite files the bundle writes when design-system/ already exists
|
|
1017
1040
|
`;
|
|
1018
|
-
var ADD_USAGE = `designsource add [names\u2026] [--yes] [--all] [--force] [--skip-install] [--no-blocks] [--token <project token>] [--api <origin>]
|
|
1041
|
+
var ADD_USAGE = `designsource add [names\u2026] [--yes] [--all] [--force] [--skip-install] [--no-blocks] [--screen <name>|all|shell] [--token <project token>] [--api <origin>]
|
|
1019
1042
|
|
|
1020
1043
|
Adds your design system's UI kit to the React app in this folder: the theme in its global stylesheet, the
|
|
1021
1044
|
components and the libraries they import. Sets up Tailwind and the shadcn config when the app has none.
|
|
@@ -1028,6 +1051,8 @@ your components, blocks and sample pages.
|
|
|
1028
1051
|
--force replace component files add did not write, and edited ones
|
|
1029
1052
|
--skip-install write the files, then print the install command instead of running it
|
|
1030
1053
|
--no-blocks the /design-system section without its blocks and their libraries (blocks already there stay)
|
|
1054
|
+
--screen screens from DS source, by file name (repeatable, or comma-separated); all for every one; shell for
|
|
1055
|
+
a sidebar app shell listing the screens in the app
|
|
1031
1056
|
--token the project token (workbench \u2192 Project settings); or DS_SYNC_TOKEN
|
|
1032
1057
|
--api API origin (default ${DEFAULT_API_ORIGIN})
|
|
1033
1058
|
`;
|
|
@@ -1148,10 +1173,23 @@ function switchOf(arg, usage) {
|
|
|
1148
1173
|
}
|
|
1149
1174
|
var unknownOption = (arg, usage) => new ArgsError(`Unknown option ${arg.name}`, usage);
|
|
1150
1175
|
var ADD_SWITCHES = /* @__PURE__ */ new Map([["yes", "yes"], ["all", "all"], ["force", "force"], ["skip-install", "skipInstall"], ["no-blocks", "noBlocks"]]);
|
|
1176
|
+
var SCREEN_NAME_MESSAGE = "--screen takes screen names from DS source (letters, digits and dashes), or all.";
|
|
1177
|
+
function screensIn(values, usage) {
|
|
1178
|
+
const words = values.flatMap((v) => v.split(",").map((w) => w.trim()));
|
|
1179
|
+
if (words.some((n) => n === "")) throw new ArgsError(SCREEN_NAME_MESSAGE, usage);
|
|
1180
|
+
const shell = words.includes("shell") ? { shell: true } : {};
|
|
1181
|
+
const names = words.filter((n) => n !== "shell");
|
|
1182
|
+
if (names.includes("all")) return { screens: "all", ...shell };
|
|
1183
|
+
for (const n of names) {
|
|
1184
|
+
if (!SCREEN_SLUG.test(n) || RESERVED_SCREEN_SLUGS.includes(n)) throw new ArgsError(SCREEN_NAME_MESSAGE, usage);
|
|
1185
|
+
}
|
|
1186
|
+
return { ...names.length > 0 ? { screens: [...new Set(names)] } : {}, ...shell };
|
|
1187
|
+
}
|
|
1151
1188
|
function parseAdd(argv, env) {
|
|
1152
1189
|
const args = { components: [], api: DEFAULT_API_ORIGIN, yes: false, all: false, force: false, skipInstall: false, noBlocks: false };
|
|
1153
1190
|
if (env.DS_SYNC_TOKEN) args.token = env.DS_SYNC_TOKEN;
|
|
1154
|
-
|
|
1191
|
+
const screenValues = [];
|
|
1192
|
+
for (const arg of scan(argv, ["token", "api", "screen"], [...ADD_SWITCHES.keys()])) {
|
|
1155
1193
|
if (arg.kind === "help") return { kind: "help", verb: "add" };
|
|
1156
1194
|
if (arg.kind === "positional") {
|
|
1157
1195
|
args.components.push(arg.value);
|
|
@@ -1161,11 +1199,13 @@ function parseAdd(argv, env) {
|
|
|
1161
1199
|
if (field) args[field] = switchOf(arg, ADD_USAGE);
|
|
1162
1200
|
else if (arg.known === null) throw unknownOption(arg, ADD_USAGE);
|
|
1163
1201
|
else if (arg.key === "token") args.token = valueOf(arg, ADD_USAGE);
|
|
1202
|
+
else if (arg.key === "screen") screenValues.push(valueOf(arg, ADD_USAGE));
|
|
1164
1203
|
else {
|
|
1165
1204
|
args.api = parseApiOrigin(valueOf(arg, ADD_USAGE), ADD_USAGE);
|
|
1166
1205
|
args.apiGiven = true;
|
|
1167
1206
|
}
|
|
1168
1207
|
}
|
|
1208
|
+
if (screenValues.length) Object.assign(args, screensIn(screenValues, ADD_USAGE));
|
|
1169
1209
|
return { kind: "add", args };
|
|
1170
1210
|
}
|
|
1171
1211
|
function appsIn(value, usage = CONNECT_USAGE) {
|
|
@@ -1244,7 +1284,8 @@ function parseVerb(verb, argv, env) {
|
|
|
1244
1284
|
const usage = usageFor(verb);
|
|
1245
1285
|
const args = baseArgs(env);
|
|
1246
1286
|
const strings = verb === "integrate" ? ["framework", "token", "api"] : ["token", "api"];
|
|
1247
|
-
|
|
1287
|
+
const booleans = verb === "create" ? ["force", "no-screens"] : ["force"];
|
|
1288
|
+
for (const arg of scan(argv, strings, booleans)) {
|
|
1248
1289
|
if (arg.kind === "help") return { kind: "help", verb };
|
|
1249
1290
|
if (arg.kind === "positional") {
|
|
1250
1291
|
if (args.folder !== void 0) throw new ArgsError("Expected one folder argument", usage);
|
|
@@ -1253,6 +1294,7 @@ function parseVerb(verb, argv, env) {
|
|
|
1253
1294
|
}
|
|
1254
1295
|
if (arg.known === null) throw unknownOption(arg, usage);
|
|
1255
1296
|
if (arg.key === "force") args.force = switchOf(arg, usage);
|
|
1297
|
+
else if (arg.key === "no-screens") args.noScreens = switchOf(arg, usage);
|
|
1256
1298
|
else if (arg.key === "framework") {
|
|
1257
1299
|
const value = valueOf(arg, usage);
|
|
1258
1300
|
if (!isIntegrateFramework(value)) throw new ArgsError(`Unknown framework "${value}" \u2014 one of ${INTEGRATE_FRAMEWORKS.join(", ")}`, usage);
|
|
@@ -1457,12 +1499,207 @@ function planFiles(root, t, components, manifest) {
|
|
|
1457
1499
|
// src/add/section.ts
|
|
1458
1500
|
import { existsSync as existsSync6, readdirSync as readdirSync2, readFileSync as readFileSync6 } from "node:fs";
|
|
1459
1501
|
import { join as join4 } from "node:path";
|
|
1502
|
+
|
|
1503
|
+
// src/add/screen-gen.ts
|
|
1504
|
+
var SCREEN_KINDS = ["list", "detail", "settings", "form", "dashboard"];
|
|
1505
|
+
var SCREEN_KIND_ICON_NAMES = {
|
|
1506
|
+
list: "ListDetailsIcon",
|
|
1507
|
+
detail: "UserIcon",
|
|
1508
|
+
settings: "SettingsIcon",
|
|
1509
|
+
form: "FileTextIcon",
|
|
1510
|
+
dashboard: "DashboardIcon"
|
|
1511
|
+
};
|
|
1512
|
+
function jsonLiteral(value, indent) {
|
|
1513
|
+
return JSON.stringify(value, null, indent).replace(/[\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`).replace(/<\//g, "<\\/");
|
|
1514
|
+
}
|
|
1515
|
+
function screenComponentName(slug) {
|
|
1516
|
+
return slug.split("-").filter(Boolean).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("") + "Screen";
|
|
1517
|
+
}
|
|
1518
|
+
function checkShellScreens(screens) {
|
|
1519
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1520
|
+
for (const s of screens) {
|
|
1521
|
+
if (typeof s.slug !== "string" || !SCREEN_SLUG.test(s.slug)) throw new Error("Invalid screen slug");
|
|
1522
|
+
if (RESERVED_SCREEN_SLUGS.includes(s.slug)) throw new Error("Reserved screen slug");
|
|
1523
|
+
if (seen.has(s.slug)) throw new Error("Duplicate screen slug");
|
|
1524
|
+
seen.add(s.slug);
|
|
1525
|
+
if (!SCREEN_KINDS.includes(s.kind)) throw new Error("Unknown screen kind");
|
|
1526
|
+
if (typeof s.title !== "string") throw new Error("Invalid screen title");
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
function assembleAppShell(input) {
|
|
1530
|
+
checkShellScreens(input.screens);
|
|
1531
|
+
if (typeof input.name !== "string") throw new Error("Invalid app name");
|
|
1532
|
+
if (input.hrefFor !== "app" && input.hrefFor !== "root") throw new Error("Invalid hrefFor");
|
|
1533
|
+
const prefix = input.hrefFor === "app" ? "/app/" : "/";
|
|
1534
|
+
const links = input.screens.map((s) => ({ href: `${prefix}${s.slug}`, title: s.title, kind: s.kind }));
|
|
1535
|
+
const icons = [...new Set(SCREEN_KINDS.map((k) => SCREEN_KIND_ICON_NAMES[k]))].sort();
|
|
1536
|
+
const kindIcons = SCREEN_KINDS.map((k) => ` ${k}: ${SCREEN_KIND_ICON_NAMES[k]},`);
|
|
1537
|
+
return [
|
|
1538
|
+
"'use client'",
|
|
1539
|
+
"",
|
|
1540
|
+
"import { useEffect, useState, type ReactNode } from 'react'",
|
|
1541
|
+
`import { ${icons.join(", ")}, type IconComponent } from '@/components/ui/icons'`,
|
|
1542
|
+
"import {",
|
|
1543
|
+
" Sidebar,",
|
|
1544
|
+
" SidebarContent,",
|
|
1545
|
+
" SidebarGroup,",
|
|
1546
|
+
" SidebarGroupContent,",
|
|
1547
|
+
" SidebarHeader,",
|
|
1548
|
+
" SidebarInset,",
|
|
1549
|
+
" SidebarMenu,",
|
|
1550
|
+
" SidebarMenuButton,",
|
|
1551
|
+
" SidebarMenuItem,",
|
|
1552
|
+
" SidebarProvider,",
|
|
1553
|
+
" SidebarTrigger,",
|
|
1554
|
+
"} from '@/components/ui/sidebar'",
|
|
1555
|
+
"",
|
|
1556
|
+
`type ScreenKind = ${SCREEN_KINDS.map((k) => `'${k}'`).join(" | ")}`,
|
|
1557
|
+
"type ShellLink = { href: string; title: string; kind: ScreenKind }",
|
|
1558
|
+
"",
|
|
1559
|
+
`const NAME: string = ${jsonLiteral(input.name)}`,
|
|
1560
|
+
"",
|
|
1561
|
+
`const SCREENS: ShellLink[] = ${jsonLiteral(links, 2)}`,
|
|
1562
|
+
"",
|
|
1563
|
+
"const KIND_ICONS: Record<ScreenKind, IconComponent> = {",
|
|
1564
|
+
...kindIcons,
|
|
1565
|
+
"}",
|
|
1566
|
+
"",
|
|
1567
|
+
"/** The current path, read after mount so the first client render matches the server. */",
|
|
1568
|
+
"function useCurrentPath(): string | null {",
|
|
1569
|
+
" const [path, setPath] = useState<string | null>(null)",
|
|
1570
|
+
" useEffect(() => {",
|
|
1571
|
+
" const read = () => setPath(window.location.pathname.replace(/\\/+$/, '') || '/')",
|
|
1572
|
+
" read()",
|
|
1573
|
+
" window.addEventListener('popstate', read)",
|
|
1574
|
+
" return () => window.removeEventListener('popstate', read)",
|
|
1575
|
+
" }, [])",
|
|
1576
|
+
" return path",
|
|
1577
|
+
"}",
|
|
1578
|
+
"",
|
|
1579
|
+
"export function AppShell({ children }: { children: ReactNode }) {",
|
|
1580
|
+
" const path = useCurrentPath()",
|
|
1581
|
+
" return (",
|
|
1582
|
+
' <div className="@container/stage">',
|
|
1583
|
+
" <SidebarProvider>",
|
|
1584
|
+
" <Sidebar>",
|
|
1585
|
+
" <SidebarHeader>",
|
|
1586
|
+
' <div className="truncate px-2 py-1.5 text-sm font-semibold">{NAME}</div>',
|
|
1587
|
+
" </SidebarHeader>",
|
|
1588
|
+
" <SidebarContent>",
|
|
1589
|
+
" <SidebarGroup>",
|
|
1590
|
+
" <SidebarGroupContent>",
|
|
1591
|
+
" <SidebarMenu>",
|
|
1592
|
+
" {SCREENS.map((screen) => {",
|
|
1593
|
+
" const Icon = KIND_ICONS[screen.kind]",
|
|
1594
|
+
" const active = path === screen.href",
|
|
1595
|
+
" return (",
|
|
1596
|
+
" <SidebarMenuItem key={screen.href}>",
|
|
1597
|
+
" <SidebarMenuButton asChild isActive={active} tooltip={screen.title}>",
|
|
1598
|
+
" <a href={screen.href} aria-current={active ? 'page' : undefined}>",
|
|
1599
|
+
" <Icon />",
|
|
1600
|
+
" <span>{screen.title}</span>",
|
|
1601
|
+
" </a>",
|
|
1602
|
+
" </SidebarMenuButton>",
|
|
1603
|
+
" </SidebarMenuItem>",
|
|
1604
|
+
" )",
|
|
1605
|
+
" })}",
|
|
1606
|
+
" </SidebarMenu>",
|
|
1607
|
+
" </SidebarGroupContent>",
|
|
1608
|
+
" </SidebarGroup>",
|
|
1609
|
+
" </SidebarContent>",
|
|
1610
|
+
" </Sidebar>",
|
|
1611
|
+
" <SidebarInset>",
|
|
1612
|
+
' <header className="flex h-12 shrink-0 items-center gap-2 border-b px-4 @[40rem]/stage:px-6">',
|
|
1613
|
+
' <SidebarTrigger className="-ml-1" />',
|
|
1614
|
+
" </header>",
|
|
1615
|
+
' <div className="flex flex-1 flex-col">{children}</div>',
|
|
1616
|
+
" </SidebarInset>",
|
|
1617
|
+
" </SidebarProvider>",
|
|
1618
|
+
" </div>",
|
|
1619
|
+
" )",
|
|
1620
|
+
"}",
|
|
1621
|
+
"",
|
|
1622
|
+
"AppShell.displayName = 'AppShell'",
|
|
1623
|
+
""
|
|
1624
|
+
].join("\n");
|
|
1625
|
+
}
|
|
1626
|
+
var DEFAULT_SCREENS_IMPORT = "@/components/screens";
|
|
1627
|
+
var SCREENS_IMPORT = /^[A-Za-z0-9@~#_.-]+(?:\/[A-Za-z0-9@~#_.-]+)*$/;
|
|
1628
|
+
var HEAD = [
|
|
1629
|
+
`export type SectionScreenKind = ${SCREEN_KINDS.map((k) => `'${k}'`).join(" | ")}`,
|
|
1630
|
+
"export type SectionScreenEntry = { slug: string; title: string; kind: SectionScreenKind }"
|
|
1631
|
+
];
|
|
1632
|
+
function assembleScreenRegistry(input) {
|
|
1633
|
+
checkShellScreens(input.screens);
|
|
1634
|
+
const screensImport = input.screensImport ?? DEFAULT_SCREENS_IMPORT;
|
|
1635
|
+
if (typeof screensImport !== "string" || !SCREENS_IMPORT.test(screensImport)) throw new Error("Invalid screensImport");
|
|
1636
|
+
const entries = input.screens.map((s) => ({ slug: s.slug, title: s.title, kind: s.kind }));
|
|
1637
|
+
if (entries.length === 0) {
|
|
1638
|
+
return [
|
|
1639
|
+
...HEAD,
|
|
1640
|
+
"",
|
|
1641
|
+
"export const SECTION_SCREENS: SectionScreenEntry[] = []",
|
|
1642
|
+
"",
|
|
1643
|
+
"/** No screens yet: every slug renders nothing, and the view around this says what is missing. */",
|
|
1644
|
+
// A typed const rather than a function with an unused parameter, which a stock Next lint config warns about.
|
|
1645
|
+
"export const SectionScreen: ((props: { slug: string }) => null) & { displayName?: string } = () => null",
|
|
1646
|
+
"",
|
|
1647
|
+
"SectionScreen.displayName = 'SectionScreen'",
|
|
1648
|
+
""
|
|
1649
|
+
].join("\n");
|
|
1650
|
+
}
|
|
1651
|
+
const views = entries.map(
|
|
1652
|
+
(s) => ` ${jsonLiteral(s.slug)}: lazy(() => import(${jsonLiteral(`${screensImport}/${s.slug}`)}).then((m) => ({ default: m.${screenComponentName(s.slug)} }))),`
|
|
1653
|
+
);
|
|
1654
|
+
return [
|
|
1655
|
+
"import { lazy, Suspense, type ComponentType } from 'react'",
|
|
1656
|
+
"",
|
|
1657
|
+
...HEAD,
|
|
1658
|
+
"",
|
|
1659
|
+
`export const SECTION_SCREENS: SectionScreenEntry[] = ${jsonLiteral(entries, 2)}`,
|
|
1660
|
+
"",
|
|
1661
|
+
"const VIEWS: Record<string, ComponentType> = {",
|
|
1662
|
+
...views,
|
|
1663
|
+
"}",
|
|
1664
|
+
"",
|
|
1665
|
+
"export function SectionScreen({ slug }: { slug: string }) {",
|
|
1666
|
+
" const View = Object.prototype.hasOwnProperty.call(VIEWS, slug) ? VIEWS[slug] : undefined",
|
|
1667
|
+
" if (!View) return null",
|
|
1668
|
+
" return (",
|
|
1669
|
+
" <Suspense fallback={null}>",
|
|
1670
|
+
" <View />",
|
|
1671
|
+
" </Suspense>",
|
|
1672
|
+
" )",
|
|
1673
|
+
"}",
|
|
1674
|
+
"",
|
|
1675
|
+
"SectionScreen.displayName = 'SectionScreen'",
|
|
1676
|
+
""
|
|
1677
|
+
].join("\n");
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
// src/add/section.ts
|
|
1460
1681
|
var SECTION_NEEDS_FULL_KIT = "The /design-system section comes with the full kit: run designsource add --all.";
|
|
1461
1682
|
var SECTION_NEEDS_FULL_KIT_FOR_AGENT = 'The /design-system section comes with the full kit: call add_ui_kit again with every component in "components" (list_components names them).';
|
|
1462
1683
|
var NO_COMPONENTS_DIR = (alias) => `tsconfig.json does not resolve components.json's components alias "${alias}"; the /design-system section goes in that folder, so add a paths entry for it.`;
|
|
1463
1684
|
var NO_LIB_ALIAS = (alias) => `components.json's utils alias "${alias}" has no folder; the /design-system section needs one, such as "@/lib/utils".`;
|
|
1464
1685
|
var NO_APP_ROUTER = "This Next.js app uses the Pages Router; the /design-system section needs the App Router, so it was skipped.";
|
|
1465
1686
|
var OWN_DESIGN_SYSTEM_ROUTE = (path) => `Skipped the /design-system section: this app already has its own /design-system route (${path}).`;
|
|
1687
|
+
var REGISTRY_KEY = "section/section-screens.tsx";
|
|
1688
|
+
var REGISTRY_STAMP = "section:screens";
|
|
1689
|
+
var sectionKnowsScreens = (manifest) => manifest.section?.files.some((f) => f.key === REGISTRY_KEY) ?? false;
|
|
1690
|
+
function sectionReadsScreens(root, t) {
|
|
1691
|
+
if (t.componentsDir === null) return false;
|
|
1692
|
+
try {
|
|
1693
|
+
const routes = readFileSync6(resolveInside(root, join22(t.componentsDir, "design-system/section-routes.ts")), "utf8");
|
|
1694
|
+
return /from ['"]\.\/section-screens['"]/.test(routes);
|
|
1695
|
+
} catch {
|
|
1696
|
+
return false;
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
var registryPath = (componentsDir) => join22(componentsDir, "design-system/section-screens.tsx");
|
|
1700
|
+
function registryFile(componentsDir, t, screens) {
|
|
1701
|
+
return stamped(registryPath(componentsDir), REGISTRY_STAMP, rewriteForApp(assembleScreenRegistry({ screens }), t));
|
|
1702
|
+
}
|
|
1466
1703
|
function shownBlockGroups(groups, blocks, keptBlockIds = []) {
|
|
1467
1704
|
if (blocks === "write") return groups;
|
|
1468
1705
|
if (blocks === "skip") return [];
|
|
@@ -1511,12 +1748,19 @@ function planSectionFiles(input) {
|
|
|
1511
1748
|
const files = [];
|
|
1512
1749
|
for (const f of section.files) {
|
|
1513
1750
|
if (f.block && blocks !== "write") continue;
|
|
1751
|
+
if (f.key === REGISTRY_KEY) continue;
|
|
1514
1752
|
const { path, name } = placeManifestFile(f.key, componentsDir, t);
|
|
1515
1753
|
let contents = rewriteForApp(f.contents, t);
|
|
1516
1754
|
if (f.key === "section/section-views.tsx" && blocks === "skip") contents = pointAtStub(contents, t.componentsAlias);
|
|
1517
1755
|
files.push(stamped(path, name, contents));
|
|
1518
1756
|
}
|
|
1519
1757
|
if (blocks === "skip") files.push(stamped(ds("block-view.tsx"), "section:block-view", NO_BLOCKS_VIEW));
|
|
1758
|
+
const screens = sectionKnowsScreens(manifest);
|
|
1759
|
+
if (screens && input.screens !== null) files.push(registryFile(componentsDir, t, input.screens));
|
|
1760
|
+
else if (screens && !input.registryOnDisk) {
|
|
1761
|
+
const fallback = section.files.find((f) => f.key === REGISTRY_KEY);
|
|
1762
|
+
files.push(stamped(registryPath(componentsDir), REGISTRY_STAMP, rewriteForApp(fallback.contents, t)));
|
|
1763
|
+
}
|
|
1520
1764
|
const hasMockup = section.mockupSpec !== null;
|
|
1521
1765
|
const darkMarker = vite ? { kind: "class", name: "dark" } : input.darkMarker;
|
|
1522
1766
|
const config = {
|
|
@@ -1530,7 +1774,7 @@ function planSectionFiles(input) {
|
|
|
1530
1774
|
files.push(stamped(ds("section-config.ts"), "section:config", cliSectionConfig(config)));
|
|
1531
1775
|
if (hasMockup) files.push(stamped(ds("page.json"), "section:page", `${JSON.stringify(section.mockupSpec, null, 2)}
|
|
1532
1776
|
`));
|
|
1533
|
-
files.push(stamped(ds("section-routes.ts"), "section:routes", vite ? viteSectionRoutes(hasMockup, t) : sectionRoutes(hasMockup, t)));
|
|
1777
|
+
files.push(stamped(ds("section-routes.ts"), "section:routes", vite ? viteSectionRoutes(hasMockup, screens, t) : sectionRoutes(hasMockup, screens, t)));
|
|
1534
1778
|
if (vite) {
|
|
1535
1779
|
const entry = (file) => join22(input.srcDir, `design-system/${file}`);
|
|
1536
1780
|
files.push(stamped("design-system.html", "section:page-html", vitePage(manifest.name, entry("main.tsx"))));
|
|
@@ -1541,7 +1785,7 @@ function planSectionFiles(input) {
|
|
|
1541
1785
|
files.push(stamped(ds("section-theme.css"), "section:theme", section.themeCss));
|
|
1542
1786
|
files.push(stamped(ds("section-page.tsx"), "section:section-page", NEXT_SECTION_PAGE));
|
|
1543
1787
|
files.push(stamped(`${input.appDir}/design-system/layout.tsx`, "section:route:layout", nextLayout(t)));
|
|
1544
|
-
files.push(stamped(`${input.appDir}/design-system/[[...path]]/page.tsx`, "section:route:page", nextPage(t)));
|
|
1788
|
+
files.push(stamped(`${input.appDir}/design-system/[[...path]]/page.tsx`, "section:route:page", nextPage(t, screens)));
|
|
1545
1789
|
return files;
|
|
1546
1790
|
}
|
|
1547
1791
|
var NO_BLOCKS_VIEW = `// This project was added without blocks (designsource add --no-blocks): the section has no Blocks views.
|
|
@@ -1562,21 +1806,22 @@ export const MOCKUP_SPEC: StoredMockupSpec | null = mockupSpecShapeSchema.parse(
|
|
|
1562
1806
|
export const MOCKUP_SPEC: StoredMockupSpec | null = null
|
|
1563
1807
|
`;
|
|
1564
1808
|
}
|
|
1565
|
-
var
|
|
1809
|
+
var routesImports = (screens) => `import { SECTION_CONFIG } from './section-config'
|
|
1566
1810
|
import { parseSectionPath, type SectionFeatures, type SectionRoute, sectionPath } from './section-nav'
|
|
1567
|
-
|
|
1568
|
-
|
|
1811
|
+
${screens ? `import { SECTION_SCREENS } from './section-screens'
|
|
1812
|
+
` : ""}`;
|
|
1813
|
+
var features = (screens) => `export const SECTION_FEATURES: SectionFeatures = {
|
|
1569
1814
|
hasMockup: SECTION_CONFIG.hasMockup,
|
|
1570
1815
|
hasBlocks: SECTION_CONFIG.hasBlocks,
|
|
1571
1816
|
blockIds: SECTION_CONFIG.blockGroups.flatMap((group) => group.blocks.map((block) => block.id)),
|
|
1572
|
-
}
|
|
1817
|
+
${screens ? " screenSlugs: SECTION_SCREENS.map((screen) => screen.slug),\n" : ""}}
|
|
1573
1818
|
`;
|
|
1574
|
-
function sectionRoutes(hasMockup, t) {
|
|
1575
|
-
return `${
|
|
1819
|
+
function sectionRoutes(hasMockup, screens, t) {
|
|
1820
|
+
return `${routesImports(screens)}${mockupModule(hasMockup, t)}
|
|
1576
1821
|
/** Where the section lives. */
|
|
1577
1822
|
export const SECTION_BASE = '/design-system'
|
|
1578
1823
|
|
|
1579
|
-
${
|
|
1824
|
+
${features(screens)}
|
|
1580
1825
|
/** A \`sectionPath()\` result as an href. */
|
|
1581
1826
|
export const sectionHref = (path: string) => \`\${SECTION_BASE}\${path}\`
|
|
1582
1827
|
|
|
@@ -1586,9 +1831,9 @@ export const hrefFor = (route: SectionRoute) => sectionHref(sectionPath(route))
|
|
|
1586
1831
|
export const routeFor = (pathname: string) => parseSectionPath(pathname.slice(SECTION_BASE.length), SECTION_FEATURES)
|
|
1587
1832
|
`;
|
|
1588
1833
|
}
|
|
1589
|
-
function viteSectionRoutes(hasMockup, t) {
|
|
1590
|
-
return `${
|
|
1591
|
-
${
|
|
1834
|
+
function viteSectionRoutes(hasMockup, screens, t) {
|
|
1835
|
+
return `${routesImports(screens)}${mockupModule(hasMockup, t)}
|
|
1836
|
+
${features(screens)}
|
|
1592
1837
|
/** A \`sectionPath()\` result as an href: the page's hash. */
|
|
1593
1838
|
export const sectionHref = (path: string) => \`#\${path}\`
|
|
1594
1839
|
|
|
@@ -1762,13 +2007,14 @@ function SectionLayout({ children }: { children: ReactNode }) {
|
|
|
1762
2007
|
SectionLayout.displayName = 'SectionLayout'
|
|
1763
2008
|
`;
|
|
1764
2009
|
}
|
|
1765
|
-
function nextPage(t) {
|
|
2010
|
+
function nextPage(t, screens) {
|
|
1766
2011
|
const c = t.componentsAlias;
|
|
1767
2012
|
return `import { componentSlug, GALLERY_COMPONENTS } from '${c}/design-system/gallery-groups'
|
|
1768
2013
|
import { NAV_ITEMS } from '${c}/design-system/section-nav'
|
|
1769
2014
|
import { SectionPage } from '${c}/design-system/section-page'
|
|
1770
2015
|
import { SECTION_FEATURES } from '${c}/design-system/section-routes'
|
|
1771
|
-
|
|
2016
|
+
${screens ? `import { SECTION_SCREENS } from '${c}/design-system/section-screens'
|
|
2017
|
+
` : ""}
|
|
1772
2018
|
export const metadata = { title: 'Design system' }
|
|
1773
2019
|
|
|
1774
2020
|
// Every route of the section is prerendered; anything else renders the section's own "not found" view.
|
|
@@ -1779,7 +2025,7 @@ export function generateStaticParams() {
|
|
|
1779
2025
|
...views,
|
|
1780
2026
|
...GALLERY_COMPONENTS.map((title) => \`components/\${componentSlug(title)}\`),
|
|
1781
2027
|
...SECTION_FEATURES.blockIds.map((id) => \`blocks/\${id}\`),
|
|
1782
|
-
]
|
|
2028
|
+
${screens ? " ...SECTION_SCREENS.map((screen) => `screens/${screen.slug}`),\n" : ""} ]
|
|
1783
2029
|
return routes.map((route) => ({ path: route === '' ? [] : route.split('/') }))
|
|
1784
2030
|
}
|
|
1785
2031
|
|
|
@@ -1874,7 +2120,7 @@ function sectionPresent(root, t) {
|
|
|
1874
2120
|
}
|
|
1875
2121
|
|
|
1876
2122
|
// src/add/run-add.ts
|
|
1877
|
-
import { existsSync as
|
|
2123
|
+
import { existsSync as existsSync9, readFileSync as readFileSync9, statSync as statSync2 } from "node:fs";
|
|
1878
2124
|
import { join as join5 } from "node:path";
|
|
1879
2125
|
|
|
1880
2126
|
// src/write.ts
|
|
@@ -2038,6 +2284,79 @@ async function requestJson(opts, fetchImpl = fetch) {
|
|
|
2038
2284
|
}
|
|
2039
2285
|
return { status: res.status, body };
|
|
2040
2286
|
}
|
|
2287
|
+
var STREAM_TIMEOUT_MS = 3e5;
|
|
2288
|
+
var STREAM_LINE_MAX = 1024 * 1024;
|
|
2289
|
+
var isEvent = (v) => typeof v === "object" && v !== null && !Array.isArray(v) && typeof v.type === "string";
|
|
2290
|
+
async function postNdjson(opts, fetchImpl = fetch) {
|
|
2291
|
+
const url = new URL(opts.path, `${opts.api}/`);
|
|
2292
|
+
const controller = new AbortController();
|
|
2293
|
+
const timer = setTimeout(() => controller.abort(new DOMException("The operation timed out.", "TimeoutError")), opts.timeoutMs ?? STREAM_TIMEOUT_MS);
|
|
2294
|
+
try {
|
|
2295
|
+
let res;
|
|
2296
|
+
try {
|
|
2297
|
+
res = await fetchImpl(url.toString(), {
|
|
2298
|
+
method: "POST",
|
|
2299
|
+
headers: { Accept: "application/x-ndjson", "Content-Type": "application/json", Authorization: `Bearer ${opts.token}` },
|
|
2300
|
+
body: JSON.stringify(opts.body),
|
|
2301
|
+
signal: controller.signal
|
|
2302
|
+
});
|
|
2303
|
+
} catch {
|
|
2304
|
+
throw new ApiError(UNREACHABLE(opts.api), null);
|
|
2305
|
+
}
|
|
2306
|
+
if (!res.ok) {
|
|
2307
|
+
let body = null;
|
|
2308
|
+
try {
|
|
2309
|
+
body = await res.json();
|
|
2310
|
+
} catch {
|
|
2311
|
+
}
|
|
2312
|
+
return { kind: "refused", status: res.status, body };
|
|
2313
|
+
}
|
|
2314
|
+
if (!res.body) return { kind: "ended" };
|
|
2315
|
+
const reader = res.body.getReader();
|
|
2316
|
+
const decoder = new TextDecoder();
|
|
2317
|
+
let buffer = "";
|
|
2318
|
+
const take = (line) => {
|
|
2319
|
+
let event;
|
|
2320
|
+
try {
|
|
2321
|
+
event = JSON.parse(line);
|
|
2322
|
+
} catch {
|
|
2323
|
+
return null;
|
|
2324
|
+
}
|
|
2325
|
+
if (!isEvent(event)) return null;
|
|
2326
|
+
if (event.type === "result") return { kind: "result", data: event.data };
|
|
2327
|
+
if (event.type === "error") return { kind: "error", event };
|
|
2328
|
+
return null;
|
|
2329
|
+
};
|
|
2330
|
+
try {
|
|
2331
|
+
for (; ; ) {
|
|
2332
|
+
const { done, value } = await reader.read();
|
|
2333
|
+
buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });
|
|
2334
|
+
let nl;
|
|
2335
|
+
while ((nl = buffer.indexOf("\n")) !== -1) {
|
|
2336
|
+
if (nl > STREAM_LINE_MAX) break;
|
|
2337
|
+
const line = buffer.slice(0, nl).trim();
|
|
2338
|
+
buffer = buffer.slice(nl + 1);
|
|
2339
|
+
const outcome = line ? take(line) : null;
|
|
2340
|
+
if (outcome) {
|
|
2341
|
+
void reader.cancel().catch(() => {
|
|
2342
|
+
});
|
|
2343
|
+
return outcome;
|
|
2344
|
+
}
|
|
2345
|
+
}
|
|
2346
|
+
if (nl > STREAM_LINE_MAX || nl === -1 && buffer.length > STREAM_LINE_MAX) {
|
|
2347
|
+
void reader.cancel().catch(() => {
|
|
2348
|
+
});
|
|
2349
|
+
return { kind: "ended" };
|
|
2350
|
+
}
|
|
2351
|
+
if (done) return buffer.trim() && take(buffer.trim()) || { kind: "ended" };
|
|
2352
|
+
}
|
|
2353
|
+
} catch {
|
|
2354
|
+
return { kind: "ended" };
|
|
2355
|
+
}
|
|
2356
|
+
} finally {
|
|
2357
|
+
clearTimeout(timer);
|
|
2358
|
+
}
|
|
2359
|
+
}
|
|
2041
2360
|
|
|
2042
2361
|
// src/add/kit-manifest.ts
|
|
2043
2362
|
var malformed = () => new CliError("Unexpected response from the API \u2014 not a kit manifest.");
|
|
@@ -2052,6 +2371,15 @@ function validateSection(s) {
|
|
|
2052
2371
|
if (!isStringMap(s.packages) || !isStringMap(s.blockPackages)) throw malformed();
|
|
2053
2372
|
return { files: s.files, themeCss: s.themeCss, blockGroups: s.blockGroups, packages: s.packages, blockPackages: s.blockPackages, mockupSpec: s.mockupSpec ?? null };
|
|
2054
2373
|
}
|
|
2374
|
+
var isScreen = (s) => {
|
|
2375
|
+
if (!isRecord(s) || typeof s.slug !== "string" || !SCREEN_SLUG.test(s.slug) || typeof s.title !== "string") return false;
|
|
2376
|
+
if (typeof s.component !== "string" || !SCREEN_COMPONENT.test(s.component) || !isStrings(s.parts)) return false;
|
|
2377
|
+
if (!Array.isArray(s.files) || s.files.length !== 2) return false;
|
|
2378
|
+
if (!s.files.every((f) => isRecord(f) && typeof f.file === "string" && typeof f.contents === "string")) return false;
|
|
2379
|
+
return s.files[0].file === `${s.slug}.tsx` && s.files[1].file === `${s.slug}.data.ts`;
|
|
2380
|
+
};
|
|
2381
|
+
var isScreenPart = (p) => isRecord(p) && typeof p.name === "string" && typeof p.file === "string" && SCREEN_PART_FILE.test(p.file) && p.file.replace(/\.tsx?$/, "") === p.name && typeof p.contents === "string" && isStrings(p.kitImports) && isStrings(p.partImports) && isStrings(p.packages);
|
|
2382
|
+
var isScreenEntry = (e) => isRecord(e) && typeof e.slug === "string" && SCREEN_SLUG.test(e.slug) && !RESERVED_SCREEN_SLUGS.includes(e.slug) && typeof e.title === "string" && typeof e.available === "boolean" && (e.kind === void 0 || typeof e.kind === "string" && SCREEN_KINDS.includes(e.kind));
|
|
2055
2383
|
function validateKitManifest(json) {
|
|
2056
2384
|
if (!isRecord(json)) throw malformed();
|
|
2057
2385
|
if (typeof json.version !== "number") throw malformed();
|
|
@@ -2068,6 +2396,25 @@ function validateKitManifest(json) {
|
|
|
2068
2396
|
if (!isStrings(json.utilsPackages)) throw malformed();
|
|
2069
2397
|
if (!isStringMap(json.packages) || !isStringMap(json.devPackages)) throw malformed();
|
|
2070
2398
|
const section = json.section === void 0 ? void 0 : validateSection(json.section);
|
|
2399
|
+
const { screens, screenParts, screenIndex } = json;
|
|
2400
|
+
if (screens !== void 0 && !(Array.isArray(screens) && screens.every(isScreen))) throw malformed();
|
|
2401
|
+
if (screenParts !== void 0 && !(Array.isArray(screenParts) && screenParts.every(isScreenPart))) throw malformed();
|
|
2402
|
+
if (screenIndex !== void 0 && !(Array.isArray(screenIndex) && screenIndex.every(isScreenEntry))) throw malformed();
|
|
2403
|
+
if (screens !== void 0) {
|
|
2404
|
+
const slugs = /* @__PURE__ */ new Set();
|
|
2405
|
+
for (const s of screens) {
|
|
2406
|
+
if (RESERVED_SCREEN_SLUGS.includes(s.slug) || slugs.has(s.slug)) throw malformed();
|
|
2407
|
+
slugs.add(s.slug);
|
|
2408
|
+
}
|
|
2409
|
+
}
|
|
2410
|
+
if (screenParts !== void 0) {
|
|
2411
|
+
const names = /* @__PURE__ */ new Set();
|
|
2412
|
+
for (const p of screenParts) {
|
|
2413
|
+
if (names.has(p.name)) throw malformed();
|
|
2414
|
+
names.add(p.name);
|
|
2415
|
+
}
|
|
2416
|
+
for (const s of screens ?? []) if (s.parts.some((n) => !names.has(n))) throw malformed();
|
|
2417
|
+
} else if ((screens ?? []).some((s) => s.parts.length > 0)) throw malformed();
|
|
2071
2418
|
return {
|
|
2072
2419
|
version: 1,
|
|
2073
2420
|
kind: "kit",
|
|
@@ -2078,16 +2425,129 @@ function validateKitManifest(json) {
|
|
|
2078
2425
|
utilsPackages: json.utilsPackages,
|
|
2079
2426
|
packages: json.packages,
|
|
2080
2427
|
devPackages: json.devPackages,
|
|
2081
|
-
...section ? { section } : {}
|
|
2428
|
+
...section ? { section } : {},
|
|
2429
|
+
...screens !== void 0 ? { screens } : {},
|
|
2430
|
+
...screenParts !== void 0 ? { screenParts } : {},
|
|
2431
|
+
...screenIndex !== void 0 ? { screenIndex: screenIndex.map((e) => ({ slug: e.slug, title: e.title, available: e.available, kind: e.kind ?? "list" })) } : {}
|
|
2082
2432
|
};
|
|
2083
2433
|
}
|
|
2084
2434
|
|
|
2085
2435
|
// src/add/fetch-kit.ts
|
|
2086
2436
|
async function fetchKit(opts, fetchImpl = fetch) {
|
|
2087
|
-
const { api, token,
|
|
2437
|
+
const { api, token, screens, messages } = opts;
|
|
2438
|
+
const asAll = screens === "all" || Array.isArray(screens) && (screens.includes("all") || new Set(screens).size > SCREENS_QUERY_MAX);
|
|
2439
|
+
const query = screens === void 0 || Array.isArray(screens) && screens.length === 0 ? "" : `?screens=${encodeURIComponent(asAll ? "all" : screens.join(","))}`;
|
|
2440
|
+
const path = `${opts.path ?? "/api/kit"}${query}`;
|
|
2088
2441
|
return validateKitManifest(await getJson({ api, token, path, ...messages ? { messages } : {} }, fetchImpl));
|
|
2089
2442
|
}
|
|
2090
2443
|
|
|
2444
|
+
// src/connect/open-browser.ts
|
|
2445
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
2446
|
+
var launchDetached = (cmd, args) => new Promise((resolve8) => {
|
|
2447
|
+
try {
|
|
2448
|
+
const child = spawn2(cmd, args, {
|
|
2449
|
+
shell: false,
|
|
2450
|
+
stdio: "ignore",
|
|
2451
|
+
detached: true,
|
|
2452
|
+
windowsHide: true
|
|
2453
|
+
});
|
|
2454
|
+
child.once("error", () => resolve8(false));
|
|
2455
|
+
child.once("spawn", () => {
|
|
2456
|
+
child.unref();
|
|
2457
|
+
resolve8(true);
|
|
2458
|
+
});
|
|
2459
|
+
} catch {
|
|
2460
|
+
resolve8(false);
|
|
2461
|
+
}
|
|
2462
|
+
});
|
|
2463
|
+
function deviceUrl(api) {
|
|
2464
|
+
return new URL("/device", api).toString();
|
|
2465
|
+
}
|
|
2466
|
+
async function openBrowser(url, platform, launch = launchDetached) {
|
|
2467
|
+
let protocol;
|
|
2468
|
+
try {
|
|
2469
|
+
protocol = new URL(url).protocol;
|
|
2470
|
+
} catch {
|
|
2471
|
+
return false;
|
|
2472
|
+
}
|
|
2473
|
+
if (protocol !== "http:" && protocol !== "https:") return false;
|
|
2474
|
+
if (platform === "darwin") return launch("open", [url]);
|
|
2475
|
+
if (platform === "win32") return launch("rundll32", ["url.dll,FileProtocolHandler", url]);
|
|
2476
|
+
return launch("xdg-open", [url]);
|
|
2477
|
+
}
|
|
2478
|
+
|
|
2479
|
+
// src/connect/device-login.ts
|
|
2480
|
+
var DENIED_MESSAGE = "Sign-in was denied in the browser.";
|
|
2481
|
+
var EXPIRED_MESSAGE = "The code expired. Run npx designsource login again.";
|
|
2482
|
+
var UNEXPECTED = "Unexpected answer from the API. Run npx designsource login again.";
|
|
2483
|
+
var DEVICE_MAX_WAIT_MS = 6e5;
|
|
2484
|
+
var SLOW_DOWN_MS = 5e3;
|
|
2485
|
+
var DEFAULT_INTERVAL_MS = 5e3;
|
|
2486
|
+
var MIN_INTERVAL_MS = 1e3;
|
|
2487
|
+
var MAX_INTERVAL_MS = 6e4;
|
|
2488
|
+
var ACCOUNT_TOKEN = /^dsa_[A-Za-z0-9_-]{43}$/;
|
|
2489
|
+
var USER_CODE = /^[BCDFGHJKLMNPQRSTVWXZ23456789]{4}-[BCDFGHJKLMNPQRSTVWXZ23456789]{4}$/;
|
|
2490
|
+
var DEVICE_CODE = /^[A-Za-z0-9_-]{20,128}$/;
|
|
2491
|
+
var CLIENT_NAME_MAX = 60;
|
|
2492
|
+
var EMAIL_MAX = 254;
|
|
2493
|
+
function printable(text) {
|
|
2494
|
+
return text.replace(/[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u202a-\u202e\u2028\u2029\u2060-\u2069\ufeff]/g, "");
|
|
2495
|
+
}
|
|
2496
|
+
var NO_ACCOUNT_YET = "No account yet? Sign up on that page; it's free.";
|
|
2497
|
+
function clientName(hostname2) {
|
|
2498
|
+
const host = hostname2.replace(/[^A-Za-z0-9 '._-]/g, "-") || "this computer";
|
|
2499
|
+
return `designsource on ${host}`.slice(0, CLIENT_NAME_MAX).trimEnd();
|
|
2500
|
+
}
|
|
2501
|
+
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2502
|
+
var errorCode = (body) => isRecord2(body) && typeof body.error === "string" ? body.error : null;
|
|
2503
|
+
function seconds(value, fallback, min, max) {
|
|
2504
|
+
const ms = typeof value === "number" && Number.isFinite(value) ? value * 1e3 : fallback;
|
|
2505
|
+
return Math.min(max, Math.max(min, ms));
|
|
2506
|
+
}
|
|
2507
|
+
async function deviceLogin(opts) {
|
|
2508
|
+
const { api, fetchImpl, sleep, now, show, open } = opts;
|
|
2509
|
+
const started = now();
|
|
2510
|
+
const code2 = await requestJson({ api, path: "/api/device/code", method: "POST", body: { clientName: opts.clientName } }, fetchImpl);
|
|
2511
|
+
if (code2.status === 429) throw new CliError("Too many sign-in attempts from this network. Wait a while and run npx designsource login again.");
|
|
2512
|
+
if (code2.status !== 200) throw new CliError(`${api} answered ${code2.status}.`);
|
|
2513
|
+
const body = code2.body;
|
|
2514
|
+
if (!isRecord2(body) || typeof body.deviceCode !== "string" || !DEVICE_CODE.test(body.deviceCode) || typeof body.userCode !== "string" || !USER_CODE.test(body.userCode)) {
|
|
2515
|
+
throw new CliError(UNEXPECTED);
|
|
2516
|
+
}
|
|
2517
|
+
const deviceCode = body.deviceCode;
|
|
2518
|
+
let interval = seconds(body.interval, DEFAULT_INTERVAL_MS, MIN_INTERVAL_MS, MAX_INTERVAL_MS);
|
|
2519
|
+
const deadline = started + seconds(body.expiresIn, DEVICE_MAX_WAIT_MS, 0, DEVICE_MAX_WAIT_MS);
|
|
2520
|
+
const page = deviceUrl(api);
|
|
2521
|
+
show(`Open ${page} and enter ${body.userCode}`);
|
|
2522
|
+
show(NO_ACCOUNT_YET);
|
|
2523
|
+
await open(page);
|
|
2524
|
+
show("Waiting for you to approve it in the browser\u2026 (Ctrl+C to stop)");
|
|
2525
|
+
for (; ; ) {
|
|
2526
|
+
if (now() + interval > deadline) throw new CliError(EXPIRED_MESSAGE);
|
|
2527
|
+
await sleep(interval);
|
|
2528
|
+
const poll = await requestJson({ api, path: "/api/device/token", method: "POST", body: { deviceCode } }, fetchImpl);
|
|
2529
|
+
if (poll.status === 200) return accepted(poll.body);
|
|
2530
|
+
const error = poll.status === 400 ? errorCode(poll.body) : null;
|
|
2531
|
+
if (error === "authorization_pending") continue;
|
|
2532
|
+
if (error === "slow_down") {
|
|
2533
|
+
interval = Math.min(MAX_INTERVAL_MS, interval + SLOW_DOWN_MS);
|
|
2534
|
+
continue;
|
|
2535
|
+
}
|
|
2536
|
+
if (error === "access_denied") throw new CliError(DENIED_MESSAGE);
|
|
2537
|
+
if (error === "expired_token") throw new CliError(EXPIRED_MESSAGE);
|
|
2538
|
+
if (poll.status >= 500 || poll.status === 429) continue;
|
|
2539
|
+
throw new CliError(UNEXPECTED);
|
|
2540
|
+
}
|
|
2541
|
+
}
|
|
2542
|
+
function accepted(body) {
|
|
2543
|
+
if (!isRecord2(body) || typeof body.accessToken !== "string" || !ACCOUNT_TOKEN.test(body.accessToken)) throw new CliError("Unexpected account token from the API.");
|
|
2544
|
+
const account = body.account;
|
|
2545
|
+
if (!isRecord2(account) || typeof account.email !== "string") throw new CliError(UNEXPECTED);
|
|
2546
|
+
const email = printable(account.email).slice(0, EMAIL_MAX);
|
|
2547
|
+
if (email === "") throw new CliError(UNEXPECTED);
|
|
2548
|
+
return { token: body.accessToken, email };
|
|
2549
|
+
}
|
|
2550
|
+
|
|
2091
2551
|
// src/add/plan-packages.ts
|
|
2092
2552
|
function componentClosure(picked, manifest) {
|
|
2093
2553
|
const byName = new Map(manifest.components.map((c) => [c.name, c]));
|
|
@@ -2150,6 +2610,151 @@ function planPackages(components, manifest, appDeps, extra = {}) {
|
|
|
2150
2610
|
return { install, conflicts: [...conflictOf.values()], skipped, components: kept, extraConflicts };
|
|
2151
2611
|
}
|
|
2152
2612
|
|
|
2613
|
+
// src/add/screens.ts
|
|
2614
|
+
import { existsSync as existsSync8, readdirSync as readdirSync4, readFileSync as readFileSync8 } from "node:fs";
|
|
2615
|
+
var SCREENS_NEED_COMPONENTS_DIR = (alias) => `Screens go under your components folder, and tsconfig does not resolve "${alias}". Add the alias to tsconfig (or a components.json "components" alias), then run this again.`;
|
|
2616
|
+
var SCREEN_PART_EDITED = (slug, part) => `Skipped screen "${slug}": you edited screens/parts/${part} and the kit's version has changed since. Run again with --force to replace it.`;
|
|
2617
|
+
var SCREEN_PAIR_EDITED = (slug, editedPath) => `Skipped screen "${slug}": you edited ${editedPath} and the kit has since changed the file beside it, so they would no longer fit together. Run again with --force to replace both.`;
|
|
2618
|
+
var SCREEN_PART_EDITED_FOR_AGENT = (slug, part) => `Skipped screen "${slug}": the user edited screens/parts/${part} and the kit's version has changed since. Tell the user; they can replace it by running npx designsource add --force themselves.`;
|
|
2619
|
+
var SCREEN_PAIR_EDITED_FOR_AGENT = (slug, editedPath) => `Skipped screen "${slug}": the user edited ${editedPath} and the kit has since changed the file beside it, so they would no longer fit together. Tell the user; they can replace both by running npx designsource add --force themselves.`;
|
|
2620
|
+
var SHELL_FILE = "app-shell.tsx";
|
|
2621
|
+
var SHELL_STAMP = "screen:shell";
|
|
2622
|
+
function stampAt(root, path) {
|
|
2623
|
+
const abs = resolveInside(root, path);
|
|
2624
|
+
if (!existsSync8(abs)) return null;
|
|
2625
|
+
try {
|
|
2626
|
+
return readStamp(readFileSync8(abs, "utf8"));
|
|
2627
|
+
} catch {
|
|
2628
|
+
return null;
|
|
2629
|
+
}
|
|
2630
|
+
}
|
|
2631
|
+
var stampsIn = (root, dir, ext) => {
|
|
2632
|
+
let names;
|
|
2633
|
+
try {
|
|
2634
|
+
names = readdirSync4(resolveInside(root, dir), { withFileTypes: true }).filter((e) => e.isFile() && ext.test(e.name)).map((e) => e.name).sort();
|
|
2635
|
+
} catch {
|
|
2636
|
+
return [];
|
|
2637
|
+
}
|
|
2638
|
+
const found = [];
|
|
2639
|
+
for (const n of names) {
|
|
2640
|
+
const path = `${dir}/${n}`;
|
|
2641
|
+
let text;
|
|
2642
|
+
try {
|
|
2643
|
+
text = readFileSync8(resolveInside(root, path), "utf8");
|
|
2644
|
+
} catch {
|
|
2645
|
+
continue;
|
|
2646
|
+
}
|
|
2647
|
+
const stamp2 = readStamp(text);
|
|
2648
|
+
if (stamp2) found.push({ path, ...stamp2 });
|
|
2649
|
+
}
|
|
2650
|
+
return found;
|
|
2651
|
+
};
|
|
2652
|
+
function screensOnDisk(root, t) {
|
|
2653
|
+
const out = { slugs: [], parts: /* @__PURE__ */ new Map(), shell: false };
|
|
2654
|
+
if (t.componentsDir === null) return out;
|
|
2655
|
+
const dir = `${t.componentsDir}/screens`;
|
|
2656
|
+
for (const s of stampsIn(root, dir, /\.tsx$/)) {
|
|
2657
|
+
if (s.name === SHELL_STAMP) out.shell ||= s.path === `${dir}/${SHELL_FILE}`;
|
|
2658
|
+
else if (s.name.startsWith("screen:") && !s.name.endsWith(".data")) out.slugs.push(s.name.slice("screen:".length));
|
|
2659
|
+
}
|
|
2660
|
+
for (const p of stampsIn(root, `${dir}/parts`, /\.tsx?$/)) {
|
|
2661
|
+
if (p.name.startsWith("screen-part:")) out.parts.set(p.name.slice("screen-part:".length), { path: p.path, hash: p.hash, edited: p.edited });
|
|
2662
|
+
}
|
|
2663
|
+
return out;
|
|
2664
|
+
}
|
|
2665
|
+
function closureOf(names, byName) {
|
|
2666
|
+
const seen = /* @__PURE__ */ new Map();
|
|
2667
|
+
const visit = (name) => {
|
|
2668
|
+
if (seen.has(name)) return;
|
|
2669
|
+
const part = byName.get(name);
|
|
2670
|
+
if (!part) throw new CliError("Unexpected response from the API \u2014 not a kit manifest.");
|
|
2671
|
+
seen.set(name, part);
|
|
2672
|
+
for (const n of part.partImports) visit(n);
|
|
2673
|
+
};
|
|
2674
|
+
names.forEach(visit);
|
|
2675
|
+
return [...seen.values()];
|
|
2676
|
+
}
|
|
2677
|
+
function screenPartsOf(screen, manifest) {
|
|
2678
|
+
return closureOf(screen.parts, new Map((manifest.screenParts ?? []).map((p) => [p.name, p])));
|
|
2679
|
+
}
|
|
2680
|
+
function planScreenFiles(a) {
|
|
2681
|
+
const { root, targets: t, manifest, wanted, force = false } = a;
|
|
2682
|
+
if (t.componentsDir === null) throw new CliError(SCREENS_NEED_COMPONENTS_DIR(t.componentsAlias));
|
|
2683
|
+
const dir = `${t.componentsDir}/screens`;
|
|
2684
|
+
const byName = new Map((manifest.screenParts ?? []).map((p) => [p.name, p]));
|
|
2685
|
+
const disk = screensOnDisk(root, t);
|
|
2686
|
+
const plan = { write: [], edited: [], foreign: [], skipped: [], gone: [], kitComponents: [], added: [] };
|
|
2687
|
+
const rewritten = (p) => rewriteForApp(p.contents, t);
|
|
2688
|
+
const written = [];
|
|
2689
|
+
for (const screen of (manifest.screens ?? []).filter((s) => wanted.includes(s.slug))) {
|
|
2690
|
+
const parts = closureOf(screen.parts, byName);
|
|
2691
|
+
const blocker = force ? void 0 : parts.find((p) => {
|
|
2692
|
+
const on = disk.parts.get(p.name);
|
|
2693
|
+
return on !== void 0 && on.edited && on.hash !== hashOf(rewritten(p));
|
|
2694
|
+
});
|
|
2695
|
+
if (blocker) {
|
|
2696
|
+
plan.skipped.push({ slug: screen.slug, reason: SCREEN_PART_EDITED(screen.slug, blocker.file), agentReason: SCREEN_PART_EDITED_FOR_AGENT(screen.slug, blocker.file) });
|
|
2697
|
+
continue;
|
|
2698
|
+
}
|
|
2699
|
+
const files = screen.files.map((f) => {
|
|
2700
|
+
const path = `${dir}/${f.file}`;
|
|
2701
|
+
const stamp2 = stampAt(root, path);
|
|
2702
|
+
const kitChanged = stamp2 !== null && stamp2.hash !== hashOf(rewriteForApp(f.contents, t));
|
|
2703
|
+
return { ...f, path, edited: stamp2?.edited ?? false, kitChanged, current: stamp2 !== null && !stamp2.edited && !kitChanged };
|
|
2704
|
+
});
|
|
2705
|
+
const [a2, b] = files;
|
|
2706
|
+
const pairBlocker = force ? void 0 : a2.edited && b.kitChanged ? a2 : b.edited && a2.kitChanged ? b : void 0;
|
|
2707
|
+
if (pairBlocker) {
|
|
2708
|
+
plan.skipped.push({ slug: screen.slug, reason: SCREEN_PAIR_EDITED(screen.slug, pairBlocker.path), agentReason: SCREEN_PAIR_EDITED_FOR_AGENT(screen.slug, pairBlocker.path) });
|
|
2709
|
+
continue;
|
|
2710
|
+
}
|
|
2711
|
+
const kept = force ? files : files.filter((f, i) => !(f.current && files[1 - i].edited));
|
|
2712
|
+
written.push({ slug: screen.slug, component: screen.component, parts, files: kept });
|
|
2713
|
+
}
|
|
2714
|
+
const push = (path, name, contents, component, screen) => {
|
|
2715
|
+
const abs = resolveInside(root, path);
|
|
2716
|
+
plan.write.push({ path, contents: stampContents(name, rewriteForApp(contents, t)), component, ...screen !== void 0 ? { screen } : {} });
|
|
2717
|
+
const status = existingFileStatus(abs);
|
|
2718
|
+
if (status === "foreign") plan.foreign.push(path);
|
|
2719
|
+
else if (status === "edited") plan.edited.push(path);
|
|
2720
|
+
};
|
|
2721
|
+
const partsDone = /* @__PURE__ */ new Set();
|
|
2722
|
+
for (const s of written) {
|
|
2723
|
+
for (const f of s.files) {
|
|
2724
|
+
const name = f.file.endsWith(".data.ts") ? `screen:${s.slug}.data` : `screen:${s.slug}`;
|
|
2725
|
+
push(`${dir}/${f.file}`, name, f.contents, s.slug, s.slug);
|
|
2726
|
+
}
|
|
2727
|
+
plan.added.push({ slug: s.slug, component: s.component, importPath: `${t.componentsAlias}/screens/${s.slug}` });
|
|
2728
|
+
for (const p of s.parts) {
|
|
2729
|
+
if (partsDone.has(p.name)) continue;
|
|
2730
|
+
partsDone.add(p.name);
|
|
2731
|
+
const on = disk.parts.get(p.name);
|
|
2732
|
+
if (force || !(on && on.edited)) push(`${dir}/parts/${p.file}`, `screen-part:${p.name}`, p.contents, p.name);
|
|
2733
|
+
}
|
|
2734
|
+
}
|
|
2735
|
+
const kitComponents = /* @__PURE__ */ new Set();
|
|
2736
|
+
for (const s of written) for (const p of s.parts) for (const k of p.kitImports) kitComponents.add(k);
|
|
2737
|
+
plan.kitComponents = [...kitComponents].sort();
|
|
2738
|
+
const inIndex = new Set((manifest.screenIndex ?? []).map((e) => e.slug));
|
|
2739
|
+
plan.gone = manifest.screenIndex === void 0 ? [] : disk.slugs.filter((s) => !inIndex.has(s));
|
|
2740
|
+
return plan;
|
|
2741
|
+
}
|
|
2742
|
+
function shellScreensFor(slugs, index) {
|
|
2743
|
+
const bySlug = new Map((index ?? []).map((e) => [e.slug, e]));
|
|
2744
|
+
const valid = [...new Set(slugs)].filter((s) => SCREEN_SLUG.test(s) && !RESERVED_SCREEN_SLUGS.includes(s));
|
|
2745
|
+
return valid.sort((a, b) => a < b ? -1 : a > b ? 1 : 0).map((slug) => {
|
|
2746
|
+
const e = bySlug.get(slug);
|
|
2747
|
+
return e ? { slug, title: e.title, kind: e.kind } : { slug, title: slug, kind: "list" };
|
|
2748
|
+
});
|
|
2749
|
+
}
|
|
2750
|
+
function planShellFile(a) {
|
|
2751
|
+
const { targets: t } = a;
|
|
2752
|
+
if (t.componentsDir === null) throw new CliError(SCREENS_NEED_COMPONENTS_DIR(t.componentsAlias));
|
|
2753
|
+
const path = `${t.componentsDir}/screens/${SHELL_FILE}`;
|
|
2754
|
+
const contents = stampContents(SHELL_STAMP, rewriteForApp(assembleAppShell({ name: a.name, screens: a.screens, hrefFor: "root" }), t));
|
|
2755
|
+
return { path, contents, status: existingFileStatus(resolveInside(a.root, path)), importPath: `${t.componentsAlias}/screens/app-shell` };
|
|
2756
|
+
}
|
|
2757
|
+
|
|
2153
2758
|
// src/add/css-blocks.ts
|
|
2154
2759
|
var isSpace = (c) => c === " " || c === " " || c === "\n" || c === "\r" || c === "\f";
|
|
2155
2760
|
function commentEnd(css, at) {
|
|
@@ -2490,6 +3095,21 @@ var REPLACE_DECLINED = "Nothing was changed. Run again and answer yes to replace
|
|
|
2490
3095
|
var REPLACE_NEEDS_FORCE = (paths) => `These files exist and were not added by designsource: ${paths.join(", ")}. Pass --force to replace them.`;
|
|
2491
3096
|
var UNKNOWN_COMPONENTS = (names) => `Unknown component(s): ${names.join(", ")}. Run without names to pick from the list.`;
|
|
2492
3097
|
var SECTION_CONFLICT = (reason) => `Skipped the /design-system section: ${reason}.`;
|
|
3098
|
+
var SCREEN_UNAVAILABLE = "This screen's current version can't be built. Pick another version in DS source.";
|
|
3099
|
+
var SCREENS_NOT_SERVED = "This DS source server does not send screens yet. Try again later, or run add without --screen.";
|
|
3100
|
+
var SHELL_EMPTY = "The app shell lists no screens yet: each one you add with designsource add --screen joins its menu.";
|
|
3101
|
+
var SHELL_EMPTY_FOR_AGENT = "The app shell lists no screens yet: call add_ui_kit with screens to pull some first; each one joins its menu.";
|
|
3102
|
+
var SHELL_COMPONENTS = ["sidebar", "icons"];
|
|
3103
|
+
var SHELL_SKIPPED = (reason) => `Skipped the app shell: ${reason}.`;
|
|
3104
|
+
var SHELL_NOT_IN_KIT = (name) => `the kit from this DS source server has no ${name}`;
|
|
3105
|
+
var NO_SCREENS_YET = (project) => `${printable(project)} has no screens yet. Make one in the Screens view of the workbench.`;
|
|
3106
|
+
var UNKNOWN_SCREENS_SHOWN = 10;
|
|
3107
|
+
var UNKNOWN_SCREENS = (names, index, project) => {
|
|
3108
|
+
const head = `No screen${names.length === 1 ? "" : "s"} named ${names.map((n) => `"${printable(n)}"`).join(", ")} in ${printable(project)}.`;
|
|
3109
|
+
if (index.length === 0) return `${head} It has no screens yet.`;
|
|
3110
|
+
const shown = index.slice(0, UNKNOWN_SCREENS_SHOWN).map((e) => `${e.slug} (${printable(e.title)})`);
|
|
3111
|
+
return `${head} Its screens: ${[...shown, ...index.length > UNKNOWN_SCREENS_SHOWN ? ["\u2026"] : []].join(", ")}.`;
|
|
3112
|
+
};
|
|
2493
3113
|
var NO_THEME_FILE = (file) => `${file} does not exist. components.json names it as the app's stylesheet (tailwind.css); create it or fix the path, then run this again.`;
|
|
2494
3114
|
var INSTALL_FAILED = (command) => `Installing libraries failed. The files were written; run this to finish: ${command}`;
|
|
2495
3115
|
var UnknownComponentsError = class extends CliError {
|
|
@@ -2522,7 +3142,7 @@ function defaultTargets(root, info) {
|
|
|
2522
3142
|
const cssFile = findGlobalStylesheet(info);
|
|
2523
3143
|
if (readPaths(root)?.paths["@/*"]) return resolveTargets(root, { tailwind: { css: cssFile }, aliases: ALIASES });
|
|
2524
3144
|
const src = join5(root, "src");
|
|
2525
|
-
const prefix =
|
|
3145
|
+
const prefix = existsSync9(src) && statSync2(src).isDirectory() ? "src/" : "";
|
|
2526
3146
|
const utilsFile = `${prefix}lib/utils.ts`;
|
|
2527
3147
|
return {
|
|
2528
3148
|
uiDir: `${prefix}components/ui`,
|
|
@@ -2541,7 +3161,7 @@ function assertSameTargets(planned, actual) {
|
|
|
2541
3161
|
throw new CliError(`After setup, components.json resolves ${key} to "${actual[key]}" instead of "${planned[key]}". The kit was not written; run this again to add it there.`);
|
|
2542
3162
|
}
|
|
2543
3163
|
}
|
|
2544
|
-
async function chooseComponents(input, manifest, before, sectionOnDisk, questions) {
|
|
3164
|
+
async function chooseComponents(input, manifest, before, sectionOnDisk, questions, screens) {
|
|
2545
3165
|
const known = new Set(manifest.components.map((c) => c.name));
|
|
2546
3166
|
const offered = manifest.components.map((c) => c.name).filter((n) => n !== PORTAL);
|
|
2547
3167
|
const checked = (names) => {
|
|
@@ -2549,11 +3169,64 @@ async function chooseComponents(input, manifest, before, sectionOnDisk, question
|
|
|
2549
3169
|
if (unknown.length > 0) throw new UnknownComponentsError(unknown);
|
|
2550
3170
|
return [...new Set(names)];
|
|
2551
3171
|
};
|
|
2552
|
-
|
|
2553
|
-
if (input.all || sectionOnDisk) return offered;
|
|
3172
|
+
const withScreens = (names) => [.../* @__PURE__ */ new Set([...names, ...screens.components.filter((n) => known.has(n))])];
|
|
2554
3173
|
const earlier = before.filter((n) => known.has(n));
|
|
2555
|
-
if (
|
|
2556
|
-
|
|
3174
|
+
if (input.components.length > 0) return withScreens(checked(input.components));
|
|
3175
|
+
if (input.all || sectionOnDisk) return offered;
|
|
3176
|
+
if (screens.only || earlier.length > 0) return withScreens(earlier);
|
|
3177
|
+
return withScreens(checked(await questions.pickComponents(offered)));
|
|
3178
|
+
}
|
|
3179
|
+
function screensQuery(input, disk) {
|
|
3180
|
+
if (input.screens !== void 0) return input.screens === "all" || input.screens.length > 0 ? input.screens : void 0;
|
|
3181
|
+
if (!input.shell && (!input.refreshScreens || input.components.length > 0)) return void 0;
|
|
3182
|
+
const slugs = disk.slugs.filter((s) => SCREEN_SLUG.test(s) && !RESERVED_SCREEN_SLUGS.includes(s));
|
|
3183
|
+
return slugs.length > 0 ? slugs : void 0;
|
|
3184
|
+
}
|
|
3185
|
+
function screenConflict(slug, manifest, appDeps) {
|
|
3186
|
+
const screen = manifest.screens?.find((s) => s.slug === slug);
|
|
3187
|
+
if (!screen) return null;
|
|
3188
|
+
const parts = screenPartsOf(screen, manifest);
|
|
3189
|
+
const byName = new Map(manifest.components.map((c) => [c.name, c]));
|
|
3190
|
+
const components = componentClosure(parts.flatMap((p) => p.kitImports).filter((n) => byName.has(n)), manifest);
|
|
3191
|
+
for (const pkg of [...parts.flatMap((p) => p.packages), ...components.flatMap((n) => byName.get(n)?.packages ?? [])]) {
|
|
3192
|
+
const have = appDeps[pkg];
|
|
3193
|
+
const need = manifest.packages[pkg];
|
|
3194
|
+
if (have === void 0 || need === void 0) continue;
|
|
3195
|
+
const conflict = conflictBetween(pkg, have, need);
|
|
3196
|
+
if (conflict) return reasonFor(conflict);
|
|
3197
|
+
}
|
|
3198
|
+
return null;
|
|
3199
|
+
}
|
|
3200
|
+
function screenInstalls(slugs, manifest, appDeps) {
|
|
3201
|
+
const install = {};
|
|
3202
|
+
for (const screen of (manifest.screens ?? []).filter((s) => slugs.includes(s.slug))) {
|
|
3203
|
+
for (const pkg of screenPartsOf(screen, manifest).flatMap((p) => p.packages)) {
|
|
3204
|
+
const need = manifest.packages[pkg];
|
|
3205
|
+
if (need !== void 0 && appDeps[pkg] === void 0) install[pkg] = need;
|
|
3206
|
+
}
|
|
3207
|
+
}
|
|
3208
|
+
return install;
|
|
3209
|
+
}
|
|
3210
|
+
function selectScreens(query, explicit, manifest, appDeps) {
|
|
3211
|
+
const index = manifest.screenIndex;
|
|
3212
|
+
if (index === void 0) {
|
|
3213
|
+
if (explicit) throw new CliError(SCREENS_NOT_SERVED);
|
|
3214
|
+
return { wanted: [], skipped: [] };
|
|
3215
|
+
}
|
|
3216
|
+
const bySlug = new Map(index.map((e) => [e.slug, e]));
|
|
3217
|
+
if (explicit && query === "all" && index.length === 0) throw new CliError(NO_SCREENS_YET(manifest.name));
|
|
3218
|
+
if (explicit && query !== "all") {
|
|
3219
|
+
const unknown = query.filter((n) => !bySlug.has(n));
|
|
3220
|
+
if (unknown.length > 0) throw new CliError(UNKNOWN_SCREENS(unknown, index, manifest.name));
|
|
3221
|
+
}
|
|
3222
|
+
const asked = query === "all" ? index.map((e) => e.slug) : [...new Set(query)].filter((n) => bySlug.has(n));
|
|
3223
|
+
const selection = { wanted: [], skipped: [] };
|
|
3224
|
+
for (const slug of asked) {
|
|
3225
|
+
const reason = bySlug.get(slug).available ? screenConflict(slug, manifest, appDeps) : SCREEN_UNAVAILABLE;
|
|
3226
|
+
if (reason) selection.skipped.push({ slug, reason });
|
|
3227
|
+
else selection.wanted.push(slug);
|
|
3228
|
+
}
|
|
3229
|
+
return selection;
|
|
2557
3230
|
}
|
|
2558
3231
|
var SECTION_FRAMEWORKS = ["next", "vite"];
|
|
2559
3232
|
function sectionDecision(input) {
|
|
@@ -2565,7 +3238,7 @@ function sectionDecision(input) {
|
|
|
2565
3238
|
const blocks = !input.present ? input.blocksWanted ? "write" : "skip" : input.blocksOnDisk ? input.blocksWanted ? "write" : "keep" : "skip";
|
|
2566
3239
|
return { write: true, blocks, note: null };
|
|
2567
3240
|
}
|
|
2568
|
-
function planSection(root, input, info, t, manifest, chosen, onDisk) {
|
|
3241
|
+
function planSection(root, input, info, t, manifest, chosen, onDisk, screens) {
|
|
2569
3242
|
const none = (note) => ({ decision: { write: false, blocks: "skip", note }, files: () => [], paths: [], packages: {}, blockCount: 0 });
|
|
2570
3243
|
const section = manifest.section;
|
|
2571
3244
|
if (!section) return none(null);
|
|
@@ -2579,8 +3252,9 @@ function planSection(root, input, info, t, manifest, chosen, onDisk) {
|
|
|
2579
3252
|
if (t.componentsDir === null) return none(NO_COMPONENTS_DIR(t.componentsAlias));
|
|
2580
3253
|
if (!t.libAlias) return none(NO_LIB_ALIAS(t.utilsAlias));
|
|
2581
3254
|
const framework = info.framework === "vite" ? "vite" : "next";
|
|
2582
|
-
const srcDir =
|
|
2583
|
-
const
|
|
3255
|
+
const srcDir = existsSync9(join5(root, "src")) ? "src" : "";
|
|
3256
|
+
const registryOnDisk = existsSync9(resolveInside(root, registryPath(t.componentsDir)));
|
|
3257
|
+
const files = (darkMarker) => planSectionFiles({ framework, appDir, srcDir, targets: t, manifest, blocks: decision.blocks, keptBlockIds: blockIds, darkMarker, screens, registryOnDisk });
|
|
2584
3258
|
return {
|
|
2585
3259
|
decision,
|
|
2586
3260
|
files,
|
|
@@ -2611,14 +3285,30 @@ async function runAdd(input, deps) {
|
|
|
2611
3285
|
assertCanAdd(info);
|
|
2612
3286
|
const planned = info.shadcn ? resolveTargets(root, info.shadcn) : defaultTargets(root, info);
|
|
2613
3287
|
const cssAbs = resolveInside(root, planned.cssFile);
|
|
2614
|
-
if (!
|
|
3288
|
+
if (!existsSync9(cssAbs)) throw new CliError(NO_THEME_FILE(planned.cssFile));
|
|
2615
3289
|
assertKitUtils(root, info, planned);
|
|
2616
|
-
const
|
|
3290
|
+
const disk = screensOnDisk(root, planned);
|
|
3291
|
+
const query = screensQuery(input, disk);
|
|
3292
|
+
const manifest = await fetchKit({ api: input.api, token: input.token, path: input.kitPath, messages: input.messages, screens: query }, deps.fetchImpl);
|
|
3293
|
+
const shellAlone = input.shell === true && input.screens === void 0;
|
|
3294
|
+
const screenSelection = query === void 0 ? null : shellAlone ? { wanted: [], skipped: [] } : selectScreens(query, input.screens !== void 0, manifest, info.deps);
|
|
3295
|
+
const screenPlan = screenSelection === null ? null : planScreenFiles({ root, targets: planned, manifest, wanted: screenSelection.wanted, force: input.force });
|
|
3296
|
+
const fetchedScreens = query !== void 0 && manifest.screenIndex !== void 0;
|
|
3297
|
+
const screensAfter = shellScreensFor([...disk.slugs, ...(screenPlan?.added ?? []).map((a) => a.slug)], manifest.screenIndex);
|
|
3298
|
+
const bareRerun = input.refreshScreens === true && input.components.length === 0 && input.screens === void 0 && !input.shell;
|
|
3299
|
+
const noScreensLeft = bareRerun && screensAfter.length === 0;
|
|
3300
|
+
const listScreens2 = fetchedScreens || noScreensLeft;
|
|
3301
|
+
const writeShell = input.shell === true || disk.shell && listScreens2;
|
|
3302
|
+
const shellPlan = writeShell ? planShellFile({ root, targets: planned, name: manifest.name, screens: screensAfter }) : null;
|
|
2617
3303
|
const onDisk = sectionPresent(root, planned);
|
|
2618
|
-
const
|
|
2619
|
-
const
|
|
3304
|
+
const screensOnly = (input.screens !== void 0 || input.shell === true) && input.components.length === 0 && !input.all && !onDisk.present;
|
|
3305
|
+
const chosen = await chooseComponents(input, manifest, previouslyAdded(root, planned), onDisk.present, deps.questions, {
|
|
3306
|
+
components: [...screenPlan?.kitComponents ?? [], ...shellPlan ? SHELL_COMPONENTS : []],
|
|
3307
|
+
only: screensOnly
|
|
3308
|
+
});
|
|
3309
|
+
const section = planSection(root, input, info, planned, manifest, chosen, onDisk, listScreens2 ? screensAfter : null);
|
|
2620
3310
|
let packages = planPackages(chosen, manifest, info.deps);
|
|
2621
|
-
let sectionNote = section.decision.note;
|
|
3311
|
+
let sectionNote = screensOnly && section.decision.note === SECTION_NEEDS_FULL_KIT ? null : section.decision.note;
|
|
2622
3312
|
let writeSection = section.decision.write;
|
|
2623
3313
|
if (writeSection) {
|
|
2624
3314
|
const withSection = planPackages(chosen, manifest, info.deps, section.packages);
|
|
@@ -2628,8 +3318,14 @@ async function runAdd(input, deps) {
|
|
|
2628
3318
|
sectionNote = SECTION_CONFLICT(blocking);
|
|
2629
3319
|
} else packages = withSection;
|
|
2630
3320
|
}
|
|
3321
|
+
const shellBlocker = shellPlan === null ? null : SHELL_COMPONENTS.map(
|
|
3322
|
+
(name) => !manifest.components.some((c) => c.name === name) ? SHELL_NOT_IN_KIT(name) : packages.skipped.find((k) => k.name === name)?.reason ?? null
|
|
3323
|
+
).find((r) => r !== null) ?? null;
|
|
3324
|
+
const shellToWrite = shellBlocker === null ? shellPlan : null;
|
|
3325
|
+
const registryAlone = !writeSection && onDisk.present && fetchedScreens && (screenPlan?.write.length ?? 0) > 0 && planned.componentsDir !== null && sectionReadsScreens(root, planned) ? registryFile(planned.componentsDir, planned, screensAfter) : null;
|
|
2631
3326
|
const plan = planFiles(root, planned, componentClosure(packages.components, manifest), manifest);
|
|
2632
|
-
const sectionStatus =
|
|
3327
|
+
const sectionStatus = [...writeSection ? section.paths : [], ...registryAlone ? [registryAlone.path] : []].filter((p) => !p.endsWith(".json")).map((p) => [p, existingFileStatus(resolveInside(root, p))]);
|
|
3328
|
+
const shellStatus = shellToWrite ? [[shellToWrite.path, shellToWrite.status]] : [];
|
|
2633
3329
|
const setup = planSetup(info, manifest, deps.exec);
|
|
2634
3330
|
if (writeSection && info.framework === "vite") {
|
|
2635
3331
|
try {
|
|
@@ -2640,13 +3336,22 @@ async function runAdd(input, deps) {
|
|
|
2640
3336
|
sectionNote = VITE_INPUT_MANUAL;
|
|
2641
3337
|
}
|
|
2642
3338
|
}
|
|
2643
|
-
const replaceForeign = [
|
|
3339
|
+
const replaceForeign = [
|
|
3340
|
+
...plan.replaceForeign,
|
|
3341
|
+
...[...sectionStatus, ...shellStatus].filter(([, s]) => s === "foreign").map(([p]) => p),
|
|
3342
|
+
...screenPlan?.foreign ?? []
|
|
3343
|
+
];
|
|
2644
3344
|
if (replaceForeign.length > 0 && !await deps.questions.confirmReplace(replaceForeign)) throw new CliError(REPLACE_DECLINED);
|
|
2645
3345
|
const kept = [];
|
|
2646
|
-
for (const path of [...plan.edited, ...sectionStatus.filter(([, s]) => s === "edited").map(([p]) => p)]) {
|
|
3346
|
+
for (const path of [...plan.edited, ...[...sectionStatus, ...shellStatus].filter(([, s]) => s === "edited").map(([p]) => p)]) {
|
|
2647
3347
|
if (await deps.questions.keepEdits(path)) kept.push(path);
|
|
2648
3348
|
}
|
|
3349
|
+
const screensKept = [];
|
|
3350
|
+
for (const path of screenPlan?.edited ?? []) {
|
|
3351
|
+
if (await deps.questions.keepEdits(path)) screensKept.push(path);
|
|
3352
|
+
}
|
|
2649
3353
|
const writes = plan.write.filter((w) => !kept.includes(w.path));
|
|
3354
|
+
const screenWrites = (screenPlan?.write ?? []).filter((w) => !screensKept.includes(w.path));
|
|
2650
3355
|
if (!info.shadcn) deps.progress(NO_SHADCN);
|
|
2651
3356
|
for (const step of setup.steps) {
|
|
2652
3357
|
await step.run();
|
|
@@ -2657,16 +3362,18 @@ async function runAdd(input, deps) {
|
|
|
2657
3362
|
if (!written) throw new CliError("Setup did not leave a components.json. Run this again.");
|
|
2658
3363
|
assertSameTargets(planned, resolveTargets(root, written));
|
|
2659
3364
|
}
|
|
2660
|
-
const sheet =
|
|
3365
|
+
const sheet = readFileSync9(cssAbs, "utf8");
|
|
2661
3366
|
const dark = readDarkMarker(sheet);
|
|
2662
3367
|
if (writeSection && info.framework !== "vite" && !dark.known) sectionNote = UNKNOWN_DARK(dark.selector ?? "");
|
|
2663
|
-
const sectionWrites = writeSection ? section.files(dark.marker).filter((f) => !kept.includes(f.path))
|
|
3368
|
+
const sectionWrites = [...writeSection ? section.files(dark.marker) : [], ...registryAlone ? [registryAlone] : []].filter((f) => !kept.includes(f.path));
|
|
3369
|
+
const shellWrite = shellToWrite && !kept.includes(shellToWrite.path) ? shellToWrite : null;
|
|
3370
|
+
const registryWritten = listScreens2 && planned.componentsDir !== null && sectionWrites.some((f) => f.path === registryPath(planned.componentsDir));
|
|
2664
3371
|
const removeScaffolding = info.shadcn !== null || hasThemeRegion(sheet);
|
|
2665
3372
|
const themed = applyTheme(sheet, manifest.theme, { preflight: setup.preflight, removeScaffolding });
|
|
2666
3373
|
try {
|
|
2667
3374
|
writeFiles(
|
|
2668
3375
|
root,
|
|
2669
|
-
[{ path: planned.cssFile, contents: themed.css }, ...[...writes, ...sectionWrites].map(({ path, contents }) => ({ path, contents }))],
|
|
3376
|
+
[{ path: planned.cssFile, contents: themed.css }, ...[...writes, ...sectionWrites, ...screenWrites, ...shellWrite ? [shellWrite] : []].map(({ path, contents }) => ({ path, contents }))],
|
|
2670
3377
|
{ force: true, created: false }
|
|
2671
3378
|
);
|
|
2672
3379
|
} catch (e) {
|
|
@@ -2678,7 +3385,13 @@ async function runAdd(input, deps) {
|
|
|
2678
3385
|
const shown = added.filter((n) => n !== PORTAL).length;
|
|
2679
3386
|
if (shown > 0) deps.progress(`Adding ${shown} component${shown === 1 ? "" : "s"}\u2026 \u2713`);
|
|
2680
3387
|
if (writeSection) deps.progress("Adding the /design-system section\u2026 \u2713");
|
|
2681
|
-
const
|
|
3388
|
+
const screensAdded = (screenPlan?.added ?? []).filter((a) => screenWrites.some((w) => w.screen === a.slug));
|
|
3389
|
+
if (screensAdded.length > 0) deps.progress(`Adding ${screensAdded.length} screen${screensAdded.length === 1 ? "" : "s"}\u2026 \u2713`);
|
|
3390
|
+
if (shellWrite) deps.progress("Adding the app shell\u2026 \u2713");
|
|
3391
|
+
const install = { ...packages.install, ...screenInstalls((screenPlan?.added ?? []).map((s) => s.slug), manifest, info.deps) };
|
|
3392
|
+
const reactIs = manifest.packages["react-is"];
|
|
3393
|
+
if ("recharts" in install && reactIs !== void 0 && info.deps["react-is"] === void 0) install["react-is"] = reactIs;
|
|
3394
|
+
const commands = installCommands(info, manifest, install);
|
|
2682
3395
|
const installCommand = commands.map(printedCommand).join(" && ") || null;
|
|
2683
3396
|
if (installCommand && input.skipInstall) deps.progress(`Skipped installing libraries. Run: ${installCommand}`);
|
|
2684
3397
|
else if (installCommand) {
|
|
@@ -2705,13 +3418,38 @@ async function runAdd(input, deps) {
|
|
|
2705
3418
|
blocks: section.blockCount,
|
|
2706
3419
|
...section.decision.blocks === "keep" ? { blocksLeftInPlace: true } : {}
|
|
2707
3420
|
} : null,
|
|
2708
|
-
sectionNote
|
|
3421
|
+
sectionNote,
|
|
3422
|
+
screens: screenPlan === null || screenSelection === null ? null : {
|
|
3423
|
+
added: screensAdded,
|
|
3424
|
+
kept: screensKept,
|
|
3425
|
+
skipped: [...screenSelection.skipped, ...screenPlan.skipped],
|
|
3426
|
+
gone: screenPlan.gone,
|
|
3427
|
+
routeDir: info.framework === "next" ? nextAppDir(root) : null
|
|
3428
|
+
},
|
|
3429
|
+
screensView: registryWritten && screensAfter.length > 0 ? info.framework === "vite" ? "/design-system.html#/screens" : "/design-system/screens" : null,
|
|
3430
|
+
shell: shellWrite ? { importPath: shellWrite.importPath, screens: screensAfter.length } : null,
|
|
3431
|
+
shellNote: shellBlocker === null ? null : SHELL_SKIPPED(shellBlocker)
|
|
2709
3432
|
};
|
|
2710
3433
|
}
|
|
2711
3434
|
|
|
2712
3435
|
// src/add/summary.ts
|
|
2713
3436
|
var leftBlocksLine = (n, reader) => `Left ${n} block${n === 1 ? "" : "s"} in place; ${reader === "agent" ? "no_blocks" : "--no-blocks"} does not remove ${n === 1 ? "it" : "them"}.`;
|
|
2714
3437
|
var sectionNoteFor = (note, reader) => reader === "agent" && note === SECTION_NEEDS_FULL_KIT ? SECTION_NEEDS_FULL_KIT_FOR_AGENT : note;
|
|
3438
|
+
var screenSkipLine = (s, reader) => {
|
|
3439
|
+
const reason = reader === "agent" && s.agentReason ? s.agentReason : s.reason;
|
|
3440
|
+
return reason.startsWith("Skipped screen ") ? reason : `Skipped screen "${s.slug}": ${reason}`;
|
|
3441
|
+
};
|
|
3442
|
+
function screenLines(r, reader) {
|
|
3443
|
+
const first = r.added[0];
|
|
3444
|
+
const mount = !first ? [] : r.routeDir !== null ? [`Mount a screen on a route: ${r.routeDir}/${first.slug}/page.tsx \u2192 export { ${first.component} as default } from '${first.importPath}'`] : [`Render <${first.component} /> where you want it.`];
|
|
3445
|
+
return [
|
|
3446
|
+
...r.added.map((s) => `import { ${s.component} } from '${s.importPath}'`),
|
|
3447
|
+
...mount,
|
|
3448
|
+
...r.kept.map((path) => `Kept your edits to ${path}`),
|
|
3449
|
+
...r.skipped.map((skip) => screenSkipLine(skip, reader)),
|
|
3450
|
+
...r.gone.map((slug) => `Screen "${printable(slug)}" is no longer in DS source; left it in place`)
|
|
3451
|
+
];
|
|
3452
|
+
}
|
|
2715
3453
|
function summaryLines(r, reader = "cli") {
|
|
2716
3454
|
return [
|
|
2717
3455
|
...r.replacedTheme ? [`Replaced the theme in ${r.themeFile}`] : [],
|
|
@@ -2722,6 +3460,10 @@ function summaryLines(r, reader = "cli") {
|
|
|
2722
3460
|
...r.section?.blocksLeftInPlace ? [leftBlocksLine(r.section.blocks, reader)] : [],
|
|
2723
3461
|
...r.section ? [`Your design system: ${r.section.path}`] : [],
|
|
2724
3462
|
...r.sectionNote ? [sectionNoteFor(r.sectionNote, reader)] : [],
|
|
3463
|
+
...r.screens ? screenLines(r.screens, reader) : [],
|
|
3464
|
+
...r.screensView ? [`Your screens: ${r.screensView}`] : [],
|
|
3465
|
+
...r.shell ? [`import { AppShell } from '${r.shell.importPath}'`, ...r.shell.screens === 0 ? [reader === "agent" ? SHELL_EMPTY_FOR_AGENT : SHELL_EMPTY] : []] : [],
|
|
3466
|
+
...r.shellNote ? [r.shellNote] : [],
|
|
2725
3467
|
`Done. Your components now use "${r.projectName}" from designsource.app.`,
|
|
2726
3468
|
"Run it again any time to pull updates."
|
|
2727
3469
|
];
|
|
@@ -3021,7 +3763,7 @@ import { homedir } from "node:os";
|
|
|
3021
3763
|
|
|
3022
3764
|
// src/connect/store.ts
|
|
3023
3765
|
import { randomBytes } from "node:crypto";
|
|
3024
|
-
import { chmodSync, constants, copyFileSync, mkdirSync as mkdirSync2, readFileSync as
|
|
3766
|
+
import { chmodSync, constants, copyFileSync, mkdirSync as mkdirSync2, readFileSync as readFileSync10, renameSync, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
|
|
3025
3767
|
import { basename, dirname as dirname2, isAbsolute as isAbsolute2, join as join6, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
|
|
3026
3768
|
var WHERE = ["keychain", "secret-service", "dpapi", "file"];
|
|
3027
3769
|
function credentialsPath(env, platform, home) {
|
|
@@ -3037,7 +3779,7 @@ function isFileEntry(value) {
|
|
|
3037
3779
|
function readCredentials(path) {
|
|
3038
3780
|
let text;
|
|
3039
3781
|
try {
|
|
3040
|
-
text =
|
|
3782
|
+
text = readFileSync10(path, "utf8");
|
|
3041
3783
|
} catch {
|
|
3042
3784
|
return { version: 1, projects: {} };
|
|
3043
3785
|
}
|
|
@@ -3224,7 +3966,7 @@ function validateManifest(json) {
|
|
|
3224
3966
|
|
|
3225
3967
|
// src/fetch-manifest.ts
|
|
3226
3968
|
async function fetchManifest(opts, fetchImpl = fetch) {
|
|
3227
|
-
const query = { framework: opts.framework, ...opts.name ? { name: opts.name } : {} };
|
|
3969
|
+
const query = { framework: opts.framework, ...opts.name ? { name: opts.name } : {}, ...opts.screens ? { screens: opts.screens } : {} };
|
|
3228
3970
|
return validateManifest(await getJson({ api: opts.api, token: opts.token, path: "/api/starter", query }, fetchImpl));
|
|
3229
3971
|
}
|
|
3230
3972
|
|
|
@@ -3285,7 +4027,8 @@ async function savedToken(given, opts) {
|
|
|
3285
4027
|
async function scaffold(input, env, io) {
|
|
3286
4028
|
const { folder, framework, token, api, force } = input;
|
|
3287
4029
|
const { root, created } = planTarget(io.cwd, folder, framework, force);
|
|
3288
|
-
const
|
|
4030
|
+
const screens = input.screens === true && framework === "next" ? { screens: "all" } : {};
|
|
4031
|
+
const manifest = await fetchManifest({ api, token, framework, name: packageNameFor(folder), ...screens }, io.fetchImpl);
|
|
3289
4032
|
const { runner, version } = detectRunner(env.npm_config_user_agent);
|
|
3290
4033
|
const packageManager = runner === "pnpm" && version ? `pnpm@${version}` : void 0;
|
|
3291
4034
|
const { written } = writeFiles(root, manifest.files, { force, created, packageManager });
|
|
@@ -3338,7 +4081,7 @@ async function runAddCommand(args, io, exec = spawnExec, store) {
|
|
|
3338
4081
|
const targets = info.shadcn ? resolveTargets(root, info.shadcn) : defaultTargets(root, info);
|
|
3339
4082
|
assertKitUtils(root, info, targets);
|
|
3340
4083
|
let mode;
|
|
3341
|
-
if (interactive && args.components.length === 0 && !args.all) {
|
|
4084
|
+
if (interactive && args.components.length === 0 && !args.all && args.screens === void 0 && !args.shell) {
|
|
3342
4085
|
const first = previouslyAdded(root, targets).every((n) => n === "utils") && !sectionPresent(root, targets).present;
|
|
3343
4086
|
if (first) mode = await pick(PICK_QUESTION, ADD_MODES, 0);
|
|
3344
4087
|
}
|
|
@@ -3346,7 +4089,19 @@ async function runAddCommand(args, io, exec = spawnExec, store) {
|
|
|
3346
4089
|
const questions = interactive ? ttyQuestions(args, mode, io) : nonInteractiveQuestions(args);
|
|
3347
4090
|
try {
|
|
3348
4091
|
const result = await runAdd(
|
|
3349
|
-
{
|
|
4092
|
+
{
|
|
4093
|
+
root,
|
|
4094
|
+
token,
|
|
4095
|
+
api: apiFor(args, entry),
|
|
4096
|
+
components: args.components,
|
|
4097
|
+
skipInstall: args.skipInstall,
|
|
4098
|
+
all: args.all,
|
|
4099
|
+
blocks: !args.noBlocks,
|
|
4100
|
+
screens: args.screens,
|
|
4101
|
+
shell: args.shell,
|
|
4102
|
+
refreshScreens: true,
|
|
4103
|
+
force: args.force
|
|
4104
|
+
},
|
|
3350
4105
|
{ fetchImpl: io.fetchImpl, exec, questions, progress: (line) => io.stdout(`${line}
|
|
3351
4106
|
`) }
|
|
3352
4107
|
);
|
|
@@ -3360,7 +4115,7 @@ async function runAddCommand(args, io, exec = spawnExec, store) {
|
|
|
3360
4115
|
}
|
|
3361
4116
|
|
|
3362
4117
|
// src/commands/connect.ts
|
|
3363
|
-
import { accessSync, constants as constants2, existsSync as
|
|
4118
|
+
import { accessSync, constants as constants2, existsSync as existsSync11, statSync as statSync3 } from "node:fs";
|
|
3364
4119
|
import { homedir as homedir2 } from "node:os";
|
|
3365
4120
|
import { join as join8 } from "node:path";
|
|
3366
4121
|
|
|
@@ -3387,9 +4142,9 @@ async function fetchProject(opts, fetchImpl = fetch) {
|
|
|
3387
4142
|
}
|
|
3388
4143
|
|
|
3389
4144
|
// src/connect/project-root.ts
|
|
3390
|
-
import { existsSync as
|
|
4145
|
+
import { existsSync as existsSync10 } from "node:fs";
|
|
3391
4146
|
import { dirname as dirname3, isAbsolute as isAbsolute3, join as join7, relative as relative3, resolve as resolve5, sep as sep3 } from "node:path";
|
|
3392
|
-
function projectRoot(cwd, exists =
|
|
4147
|
+
function projectRoot(cwd, exists = existsSync10) {
|
|
3393
4148
|
let dir = resolve5(cwd);
|
|
3394
4149
|
for (; ; ) {
|
|
3395
4150
|
if (exists(join7(dir, ".git"))) return dir;
|
|
@@ -3435,7 +4190,7 @@ function defaultConnectDeps(env) {
|
|
|
3435
4190
|
const platform = process.platform;
|
|
3436
4191
|
return {
|
|
3437
4192
|
store: defaultStore(env),
|
|
3438
|
-
detect: () => detectApps({ env, platform, home, exists:
|
|
4193
|
+
detect: () => detectApps({ env, platform, home, exists: existsSync11, onPath: (bin) => onPath(bin, env, platform) }),
|
|
3439
4194
|
credentialsPath: credentialsPath(env, platform, home)
|
|
3440
4195
|
};
|
|
3441
4196
|
}
|
|
@@ -3573,7 +4328,7 @@ async function runCreate(args, env, io, store) {
|
|
|
3573
4328
|
const saved = await savedToken(args.token, { cwd: io.cwd, store });
|
|
3574
4329
|
const folder = args.folder ?? await askFolder(CREATE_DEFAULT_FOLDER);
|
|
3575
4330
|
const token = saved?.token ?? await requireToken(void 0);
|
|
3576
|
-
await scaffold({ folder, framework: "next", token, api: apiFor(args, saved?.entry), force: args.force }, env, io);
|
|
4331
|
+
await scaffold({ folder, framework: "next", token, api: apiFor(args, saved?.entry), force: args.force, screens: args.noScreens !== true }, env, io);
|
|
3577
4332
|
}
|
|
3578
4333
|
|
|
3579
4334
|
// src/commands/integrate.ts
|
|
@@ -3592,16 +4347,16 @@ async function runIntegrate(args, env, io, store) {
|
|
|
3592
4347
|
}
|
|
3593
4348
|
|
|
3594
4349
|
// src/commands/login.ts
|
|
3595
|
-
import { existsSync as
|
|
4350
|
+
import { existsSync as existsSync12 } from "node:fs";
|
|
3596
4351
|
import { join as join10 } from "node:path";
|
|
3597
4352
|
import { homedir as homedir3, hostname } from "node:os";
|
|
3598
4353
|
|
|
3599
4354
|
// src/connect/account-store.ts
|
|
3600
4355
|
import { createHash as createHash2 } from "node:crypto";
|
|
3601
|
-
import { readFileSync as
|
|
4356
|
+
import { readFileSync as readFileSync11, realpathSync } from "node:fs";
|
|
3602
4357
|
import { dirname as dirname4, join as join9, parse, resolve as resolve6, sep as sep4 } from "node:path";
|
|
3603
4358
|
var WHERE2 = ["keychain", "secret-service", "dpapi", "file"];
|
|
3604
|
-
var
|
|
4359
|
+
var ACCOUNT_TOKEN2 = /^dsa_[A-Za-z0-9_-]{43}$/;
|
|
3605
4360
|
var PROJECT_ID2 = /^[A-Za-z0-9_-]+$/;
|
|
3606
4361
|
var LABEL = "account";
|
|
3607
4362
|
function normaliseOrigin(origin) {
|
|
@@ -3633,15 +4388,15 @@ function normaliseFolder(folder) {
|
|
|
3633
4388
|
while (path.length > root.length && (path.endsWith(sep4) || path.endsWith("/"))) path = path.slice(0, -1);
|
|
3634
4389
|
return path;
|
|
3635
4390
|
}
|
|
3636
|
-
function
|
|
4391
|
+
function isRecord3(value) {
|
|
3637
4392
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3638
4393
|
}
|
|
3639
4394
|
function readAccount(value) {
|
|
3640
|
-
if (!
|
|
4395
|
+
if (!isRecord3(value)) return null;
|
|
3641
4396
|
const { email, where, folders, links, secret } = value;
|
|
3642
4397
|
if (typeof email !== "string" || !WHERE2.includes(where)) return null;
|
|
3643
4398
|
if (!Array.isArray(folders) || !folders.every((f) => typeof f === "string")) return null;
|
|
3644
|
-
if (!
|
|
4399
|
+
if (!isRecord3(links) || !Object.values(links).every((id) => typeof id === "string" && PROJECT_ID2.test(id))) return null;
|
|
3645
4400
|
if (secret !== void 0 && typeof secret !== "string") return null;
|
|
3646
4401
|
const entry = { email, where, folders: [...folders], links: Object.assign(/* @__PURE__ */ Object.create(null), links) };
|
|
3647
4402
|
if (secret !== void 0) entry.secret = secret;
|
|
@@ -3651,7 +4406,7 @@ function readAccounts(path) {
|
|
|
3651
4406
|
const accounts = /* @__PURE__ */ Object.create(null);
|
|
3652
4407
|
let text;
|
|
3653
4408
|
try {
|
|
3654
|
-
text =
|
|
4409
|
+
text = readFileSync11(path, "utf8");
|
|
3655
4410
|
} catch {
|
|
3656
4411
|
return { version: 1, accounts };
|
|
3657
4412
|
}
|
|
@@ -3661,7 +4416,7 @@ function readAccounts(path) {
|
|
|
3661
4416
|
} catch {
|
|
3662
4417
|
return { version: 1, accounts, unreadable: true };
|
|
3663
4418
|
}
|
|
3664
|
-
if (!
|
|
4419
|
+
if (!isRecord3(parsed) || parsed.version !== 1 || !isRecord3(parsed.accounts)) return { version: 1, accounts, unreadable: true };
|
|
3665
4420
|
for (const [origin, value] of Object.entries(parsed.accounts)) {
|
|
3666
4421
|
const entry = readAccount(value);
|
|
3667
4422
|
if (entry) accounts[origin] = entry;
|
|
@@ -3699,11 +4454,11 @@ function createAccountStore(opts) {
|
|
|
3699
4454
|
if (!Object.hasOwn(accounts, key)) return null;
|
|
3700
4455
|
const entry = accounts[key];
|
|
3701
4456
|
const value = entry.where === "file" ? entry.secret ?? null : await osBackend(entry.where).get(accountSecretId(key), entry.secret);
|
|
3702
|
-
return value !== null &&
|
|
4457
|
+
return value !== null && ACCOUNT_TOKEN2.test(value) ? value : null;
|
|
3703
4458
|
},
|
|
3704
4459
|
async save({ origin, email, token, folder }) {
|
|
3705
4460
|
const key = normaliseOrigin(origin);
|
|
3706
|
-
if (!
|
|
4461
|
+
if (!ACCOUNT_TOKEN2.test(token)) throw new CliError("Unexpected account token from the API.");
|
|
3707
4462
|
const id = accountSecretId(key);
|
|
3708
4463
|
const { unreadable, ...data } = readAccounts(path);
|
|
3709
4464
|
const previous = Object.hasOwn(data.accounts, key) ? data.accounts[key] : void 0;
|
|
@@ -3763,113 +4518,6 @@ function trustedRootFor(cwd) {
|
|
|
3763
4518
|
return normaliseFolder(projectRoot(normaliseFolder(cwd)));
|
|
3764
4519
|
}
|
|
3765
4520
|
|
|
3766
|
-
// src/connect/open-browser.ts
|
|
3767
|
-
import { spawn as spawn2 } from "node:child_process";
|
|
3768
|
-
var launchDetached = (cmd, args) => new Promise((resolve8) => {
|
|
3769
|
-
try {
|
|
3770
|
-
const child = spawn2(cmd, args, {
|
|
3771
|
-
shell: false,
|
|
3772
|
-
stdio: "ignore",
|
|
3773
|
-
detached: true,
|
|
3774
|
-
windowsHide: true
|
|
3775
|
-
});
|
|
3776
|
-
child.once("error", () => resolve8(false));
|
|
3777
|
-
child.once("spawn", () => {
|
|
3778
|
-
child.unref();
|
|
3779
|
-
resolve8(true);
|
|
3780
|
-
});
|
|
3781
|
-
} catch {
|
|
3782
|
-
resolve8(false);
|
|
3783
|
-
}
|
|
3784
|
-
});
|
|
3785
|
-
function deviceUrl(api) {
|
|
3786
|
-
return new URL("/device", api).toString();
|
|
3787
|
-
}
|
|
3788
|
-
async function openBrowser(url, platform, launch = launchDetached) {
|
|
3789
|
-
let protocol;
|
|
3790
|
-
try {
|
|
3791
|
-
protocol = new URL(url).protocol;
|
|
3792
|
-
} catch {
|
|
3793
|
-
return false;
|
|
3794
|
-
}
|
|
3795
|
-
if (protocol !== "http:" && protocol !== "https:") return false;
|
|
3796
|
-
if (platform === "darwin") return launch("open", [url]);
|
|
3797
|
-
if (platform === "win32") return launch("rundll32", ["url.dll,FileProtocolHandler", url]);
|
|
3798
|
-
return launch("xdg-open", [url]);
|
|
3799
|
-
}
|
|
3800
|
-
|
|
3801
|
-
// src/connect/device-login.ts
|
|
3802
|
-
var DENIED_MESSAGE = "Sign-in was denied in the browser.";
|
|
3803
|
-
var EXPIRED_MESSAGE = "The code expired. Run npx designsource login again.";
|
|
3804
|
-
var UNEXPECTED = "Unexpected answer from the API. Run npx designsource login again.";
|
|
3805
|
-
var DEVICE_MAX_WAIT_MS = 6e5;
|
|
3806
|
-
var SLOW_DOWN_MS = 5e3;
|
|
3807
|
-
var DEFAULT_INTERVAL_MS = 5e3;
|
|
3808
|
-
var MIN_INTERVAL_MS = 1e3;
|
|
3809
|
-
var MAX_INTERVAL_MS = 6e4;
|
|
3810
|
-
var ACCOUNT_TOKEN2 = /^dsa_[A-Za-z0-9_-]{43}$/;
|
|
3811
|
-
var USER_CODE = /^[BCDFGHJKLMNPQRSTVWXZ23456789]{4}-[BCDFGHJKLMNPQRSTVWXZ23456789]{4}$/;
|
|
3812
|
-
var DEVICE_CODE = /^[A-Za-z0-9_-]{20,128}$/;
|
|
3813
|
-
var CLIENT_NAME_MAX = 60;
|
|
3814
|
-
var EMAIL_MAX = 254;
|
|
3815
|
-
function printable(text) {
|
|
3816
|
-
return text.replace(/[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u202a-\u202e\u2028\u2029\u2060-\u2069\ufeff]/g, "");
|
|
3817
|
-
}
|
|
3818
|
-
var NO_ACCOUNT_YET = "No account yet? Sign up on that page; it's free.";
|
|
3819
|
-
function clientName(hostname2) {
|
|
3820
|
-
const host = hostname2.replace(/[^A-Za-z0-9 '._-]/g, "-") || "this computer";
|
|
3821
|
-
return `designsource on ${host}`.slice(0, CLIENT_NAME_MAX).trimEnd();
|
|
3822
|
-
}
|
|
3823
|
-
var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3824
|
-
var errorCode = (body) => isRecord3(body) && typeof body.error === "string" ? body.error : null;
|
|
3825
|
-
function seconds(value, fallback, min, max) {
|
|
3826
|
-
const ms = typeof value === "number" && Number.isFinite(value) ? value * 1e3 : fallback;
|
|
3827
|
-
return Math.min(max, Math.max(min, ms));
|
|
3828
|
-
}
|
|
3829
|
-
async function deviceLogin(opts) {
|
|
3830
|
-
const { api, fetchImpl, sleep, now, show, open } = opts;
|
|
3831
|
-
const started = now();
|
|
3832
|
-
const code2 = await requestJson({ api, path: "/api/device/code", method: "POST", body: { clientName: opts.clientName } }, fetchImpl);
|
|
3833
|
-
if (code2.status === 429) throw new CliError("Too many sign-in attempts from this network. Wait a while and run npx designsource login again.");
|
|
3834
|
-
if (code2.status !== 200) throw new CliError(`${api} answered ${code2.status}.`);
|
|
3835
|
-
const body = code2.body;
|
|
3836
|
-
if (!isRecord3(body) || typeof body.deviceCode !== "string" || !DEVICE_CODE.test(body.deviceCode) || typeof body.userCode !== "string" || !USER_CODE.test(body.userCode)) {
|
|
3837
|
-
throw new CliError(UNEXPECTED);
|
|
3838
|
-
}
|
|
3839
|
-
const deviceCode = body.deviceCode;
|
|
3840
|
-
let interval = seconds(body.interval, DEFAULT_INTERVAL_MS, MIN_INTERVAL_MS, MAX_INTERVAL_MS);
|
|
3841
|
-
const deadline = started + seconds(body.expiresIn, DEVICE_MAX_WAIT_MS, 0, DEVICE_MAX_WAIT_MS);
|
|
3842
|
-
const page = deviceUrl(api);
|
|
3843
|
-
show(`Open ${page} and enter ${body.userCode}`);
|
|
3844
|
-
show(NO_ACCOUNT_YET);
|
|
3845
|
-
await open(page);
|
|
3846
|
-
show("Waiting for you to approve it in the browser\u2026 (Ctrl+C to stop)");
|
|
3847
|
-
for (; ; ) {
|
|
3848
|
-
if (now() + interval > deadline) throw new CliError(EXPIRED_MESSAGE);
|
|
3849
|
-
await sleep(interval);
|
|
3850
|
-
const poll = await requestJson({ api, path: "/api/device/token", method: "POST", body: { deviceCode } }, fetchImpl);
|
|
3851
|
-
if (poll.status === 200) return accepted(poll.body);
|
|
3852
|
-
const error = poll.status === 400 ? errorCode(poll.body) : null;
|
|
3853
|
-
if (error === "authorization_pending") continue;
|
|
3854
|
-
if (error === "slow_down") {
|
|
3855
|
-
interval = Math.min(MAX_INTERVAL_MS, interval + SLOW_DOWN_MS);
|
|
3856
|
-
continue;
|
|
3857
|
-
}
|
|
3858
|
-
if (error === "access_denied") throw new CliError(DENIED_MESSAGE);
|
|
3859
|
-
if (error === "expired_token") throw new CliError(EXPIRED_MESSAGE);
|
|
3860
|
-
if (poll.status >= 500 || poll.status === 429) continue;
|
|
3861
|
-
throw new CliError(UNEXPECTED);
|
|
3862
|
-
}
|
|
3863
|
-
}
|
|
3864
|
-
function accepted(body) {
|
|
3865
|
-
if (!isRecord3(body) || typeof body.accessToken !== "string" || !ACCOUNT_TOKEN2.test(body.accessToken)) throw new CliError("Unexpected account token from the API.");
|
|
3866
|
-
const account = body.account;
|
|
3867
|
-
if (!isRecord3(account) || typeof account.email !== "string") throw new CliError(UNEXPECTED);
|
|
3868
|
-
const email = printable(account.email).slice(0, EMAIL_MAX);
|
|
3869
|
-
if (email === "") throw new CliError(UNEXPECTED);
|
|
3870
|
-
return { token: body.accessToken, email };
|
|
3871
|
-
}
|
|
3872
|
-
|
|
3873
4521
|
// src/commands/login.ts
|
|
3874
4522
|
function defaultLoginDeps(env) {
|
|
3875
4523
|
const home = homedir3();
|
|
@@ -3877,7 +4525,7 @@ function defaultLoginDeps(env) {
|
|
|
3877
4525
|
return {
|
|
3878
4526
|
accounts: createAccountStore({ env, platform, exec: spawnExec, home }),
|
|
3879
4527
|
accountPath: accountPath(env, platform, home),
|
|
3880
|
-
detect: () => detectApps({ env, platform, home, exists:
|
|
4528
|
+
detect: () => detectApps({ env, platform, home, exists: existsSync12, onPath: (bin) => onPath(bin, env, platform) }),
|
|
3881
4529
|
home,
|
|
3882
4530
|
terminal: process.stdin.isTTY === true && process.stdout.isTTY === true,
|
|
3883
4531
|
hostname: hostname(),
|
|
@@ -3886,6 +4534,7 @@ function defaultLoginDeps(env) {
|
|
|
3886
4534
|
}
|
|
3887
4535
|
var sleepFor = (ms) => new Promise((resolve8) => setTimeout(resolve8, ms));
|
|
3888
4536
|
var UNTRUSTED_LOGIN_SERVER = (api) => `designsource will not sign in to ${api} from a script: outside a terminal it signs in only to ${DEFAULT_API_ORIGIN} or a server on this computer. If you trust ${api}, run npx designsource login --api ${api} in a terminal yourself.`;
|
|
4537
|
+
var ACCOUNT_SCOPES_NEEDED = ["projects:create", "projects:read", "screens:create"];
|
|
3889
4538
|
var REVOKE_FAILED = "Could not reach the server to revoke this sign-in; revoke it on your profile page.";
|
|
3890
4539
|
function loginApi(args, terminal) {
|
|
3891
4540
|
const api = originOf(args.api);
|
|
@@ -3893,7 +4542,7 @@ function loginApi(args, terminal) {
|
|
|
3893
4542
|
throw new CliError(UNTRUSTED_LOGIN_SERVER(api));
|
|
3894
4543
|
}
|
|
3895
4544
|
var NOT_A_PROJECT = "Run npx designsource login inside a project folder (one with a .git folder or a package.json).";
|
|
3896
|
-
var isProjectFolder = (root) =>
|
|
4545
|
+
var isProjectFolder = (root) => existsSync12(join10(root, ".git")) || existsSync12(join10(root, "package.json"));
|
|
3897
4546
|
function savedLine2(where, file) {
|
|
3898
4547
|
if (where === "keychain") return "Saved the sign-in in the macOS keychain \u2713";
|
|
3899
4548
|
if (where === "secret-service") return "Saved the sign-in in the system keyring \u2713";
|
|
@@ -3944,11 +4593,12 @@ async function runLogin(args, io, deps = defaultLoginDeps(process.env)) {
|
|
|
3944
4593
|
const savedToken2 = saved ? await accounts.token(api).catch(() => null) : null;
|
|
3945
4594
|
if (terminal && saved && savedToken2) {
|
|
3946
4595
|
const check = await requestJson({ api, path: "/api/agent/projects", method: "GET", token: savedToken2 }, io.fetchImpl);
|
|
3947
|
-
|
|
4596
|
+
const stale = check.status === 200 && await lacksScope(api, savedToken2, io.fetchImpl);
|
|
4597
|
+
if (check.status === 200 && !stale) {
|
|
3948
4598
|
accounts.trust(api, root);
|
|
3949
4599
|
email = printable(saved.email);
|
|
3950
4600
|
head.push(`Already signed in on this computer; your agent may now use it from ${root}.`);
|
|
3951
|
-
} else if (check.status !== 401 && check.status !== 403) {
|
|
4601
|
+
} else if (check.status !== 200 && check.status !== 401 && check.status !== 403) {
|
|
3952
4602
|
throw new CliError(messageForResponse(check.status, check.body, api));
|
|
3953
4603
|
}
|
|
3954
4604
|
}
|
|
@@ -3989,6 +4639,17 @@ async function runLogin(args, io, deps = defaultLoginDeps(process.env)) {
|
|
|
3989
4639
|
...closingLines2(apps, changed, usesAccount)
|
|
3990
4640
|
]);
|
|
3991
4641
|
}
|
|
4642
|
+
async function lacksScope(api, token, fetchImpl) {
|
|
4643
|
+
try {
|
|
4644
|
+
const res = await requestJson({ api, path: "/api/agent/token", method: "GET", token }, fetchImpl);
|
|
4645
|
+
if (res.status !== 200 || typeof res.body !== "object" || res.body === null) return false;
|
|
4646
|
+
const scopes = res.body.scopes;
|
|
4647
|
+
if (!Array.isArray(scopes)) return false;
|
|
4648
|
+
return ACCOUNT_SCOPES_NEEDED.some((needed) => !scopes.includes(needed));
|
|
4649
|
+
} catch {
|
|
4650
|
+
return false;
|
|
4651
|
+
}
|
|
4652
|
+
}
|
|
3992
4653
|
async function revoke(api, token, fetchImpl) {
|
|
3993
4654
|
try {
|
|
3994
4655
|
const res = await requestJson({ api, path: "/api/agent/token", method: "DELETE", token }, fetchImpl);
|
|
@@ -4027,7 +4688,7 @@ async function runLogout(args, io, deps = defaultLoginDeps(process.env)) {
|
|
|
4027
4688
|
import { homedir as homedir4 } from "node:os";
|
|
4028
4689
|
|
|
4029
4690
|
// src/version.ts
|
|
4030
|
-
var VERSION = true ? "0.
|
|
4691
|
+
var VERSION = true ? "0.10.0" : "0.0.0-dev";
|
|
4031
4692
|
|
|
4032
4693
|
// src/mcp/account-session.ts
|
|
4033
4694
|
var NOT_SIGNED_IN_FOR = (root) => `Not signed in on this computer for ${printable(root)}. Ask the user to run npx designsource login in a terminal in that folder, then restart this app.`;
|
|
@@ -4142,6 +4803,9 @@ function getPrompt(name) {
|
|
|
4142
4803
|
return { description: "Integrate the design system into the current repository.", messages: [{ role: "user", content: { type: "text", text: INTEGRATE_TEXT } }] };
|
|
4143
4804
|
}
|
|
4144
4805
|
|
|
4806
|
+
// src/mcp/account-tools.ts
|
|
4807
|
+
import { randomUUID } from "node:crypto";
|
|
4808
|
+
|
|
4145
4809
|
// src/mcp/results.ts
|
|
4146
4810
|
var textResult = (text) => ({ content: [{ type: "text", text }] });
|
|
4147
4811
|
var errorResult = (text) => ({ content: [{ type: "text", text }], isError: true });
|
|
@@ -4278,6 +4942,63 @@ async function useDesignSystem(args, ctx) {
|
|
|
4278
4942
|
if (!account.link(id)) return errorResult(NOT_SIGNED_IN_FOR(account.folder));
|
|
4279
4943
|
return textResult(`This folder now uses "${found.name}" from ${email}'s account.`);
|
|
4280
4944
|
}
|
|
4945
|
+
var SCREEN_PROMPT_MAX = 500;
|
|
4946
|
+
var FUNDING_CODES = ["credits_required", "provider_key_required"];
|
|
4947
|
+
var SCREENS_NOT_SERVED_YET = "This DS source server cannot make screens yet.";
|
|
4948
|
+
var UNKNOWN_SCREEN = (slug, project) => `No screen named "${slug}" in ${project}. Call list_screens for the names.`;
|
|
4949
|
+
var isScreenName = (v) => typeof v === "string" && SCREEN_SLUG.test(v) && !RESERVED_SCREEN_SLUGS.includes(v);
|
|
4950
|
+
var generatePath = (projectId) => `/api/agent/projects/${encodeURIComponent(projectId)}/screens/generate`;
|
|
4951
|
+
var serverText = (body) => {
|
|
4952
|
+
const error = isPlainObject(body) ? body.error : void 0;
|
|
4953
|
+
const text = typeof error === "string" ? printable(error).trim() : "";
|
|
4954
|
+
return text || null;
|
|
4955
|
+
};
|
|
4956
|
+
var fundingRefusal = (body, api) => {
|
|
4957
|
+
if (!isPlainObject(body) || !FUNDING_CODES.includes(String(body.code))) return null;
|
|
4958
|
+
return errorResult(`${serverText(body) ?? "This account cannot pay for a screen right now."} ${FUNDING_HINT(api)}`);
|
|
4959
|
+
};
|
|
4960
|
+
var GENERATE_DESCRIPTION = "Make a new app screen for the design system this folder is linked to, from a sentence (a list, a detail page, settings, a form or a dashboard built from its components), or change an existing one by passing its name in screen. Pass data_model to shape the screen's records after the app's own (read from its Prisma schema or types). Spends the signed-in account's credits or its own AI key, so your client will ask the user first, and takes up to a couple of minutes. Never writes files: the answer names the screen and a link to see it; then call add_ui_kit with screens to write it into the app.";
|
|
4961
|
+
async function generateScreen(args, ctx) {
|
|
4962
|
+
if (!ctx.account) return errorResult(ctx.accountRefusal ?? GENERATE_NEEDS_LOGIN);
|
|
4963
|
+
const account = ctx.account;
|
|
4964
|
+
const { prompt, screen, data_model: dataModel } = args;
|
|
4965
|
+
if (typeof prompt !== "string" || !prompt.trim()) return errorResult('"prompt" must say what the screen should show.');
|
|
4966
|
+
if (prompt.trim().length > SCREEN_PROMPT_MAX) return errorResult(`"prompt" must be at most ${SCREEN_PROMPT_MAX} characters.`);
|
|
4967
|
+
if (screen !== void 0 && !isScreenName(screen)) return errorResult('"screen" must be a screen name from list_screens, or left out for a new screen.');
|
|
4968
|
+
if (dataModel !== void 0 && !isPlainObject(dataModel)) return errorResult('"data_model" must be an object (see its description), or left out.');
|
|
4969
|
+
if (account.projectId === null) return errorResult(NO_LINK);
|
|
4970
|
+
const projectId = account.projectId;
|
|
4971
|
+
const projects = await listProjects(account, ctx);
|
|
4972
|
+
if (!Array.isArray(projects)) return projects;
|
|
4973
|
+
const project = projects.find((p) => p.id === projectId);
|
|
4974
|
+
if (!project) return errorResult(LINKED_PROJECT_GONE);
|
|
4975
|
+
const body = { prompt, operationId: randomUUID() };
|
|
4976
|
+
if (screen !== void 0) body.screen = screen;
|
|
4977
|
+
if (dataModel !== void 0) body.dataModel = dataModel;
|
|
4978
|
+
const outcome = await postNdjson({ api: account.api, path: generatePath(projectId), token: account.token, body }, ctx.fetchImpl);
|
|
4979
|
+
if (outcome.kind === "refused") {
|
|
4980
|
+
const { status, body: refusal } = outcome;
|
|
4981
|
+
const code2 = isPlainObject(refusal) ? refusal.code : void 0;
|
|
4982
|
+
if (status === 403 && code2 === "agent_scope_missing") return errorResult(SCOPE_LOGIN_AGAIN);
|
|
4983
|
+
if (status === 404 && !(isPlainObject(refusal) && typeof refusal.error === "string")) return errorResult(SCREENS_NOT_SERVED_YET);
|
|
4984
|
+
if (status === 404) return errorResult(screen !== void 0 ? UNKNOWN_SCREEN(screen, project.name) : LINKED_PROJECT_GONE);
|
|
4985
|
+
return fundingRefusal(refusal, account.api) ?? serverError(status, refusal, account.api);
|
|
4986
|
+
}
|
|
4987
|
+
ctx.dropSnapshot?.();
|
|
4988
|
+
if (outcome.kind === "error") return fundingRefusal(outcome.event, account.api) ?? errorResult(serverText(outcome.event) ?? SCREEN_NOT_MADE);
|
|
4989
|
+
if (outcome.kind === "ended") return errorResult(SCREEN_NOT_MADE);
|
|
4990
|
+
const data = outcome.data;
|
|
4991
|
+
const made = isPlainObject(data) && isPlainObject(data.screen) ? data.screen : null;
|
|
4992
|
+
if (!made || !isScreenName(made.slug) || typeof made.title !== "string" || !isPlainObject(data) || typeof data.url !== "string") {
|
|
4993
|
+
return errorResult(UNEXPECTED2(account.api));
|
|
4994
|
+
}
|
|
4995
|
+
const verb = screen !== void 0 ? "Changed" : "Made";
|
|
4996
|
+
return textResult(
|
|
4997
|
+
`${verb} "${printable(made.title)}" (${made.slug}) in ${project.name}. See it: ${printable(data.url)}. Call add_ui_kit with screens: ["${made.slug}"] to write it into the app (needs Pro).`
|
|
4998
|
+
);
|
|
4999
|
+
}
|
|
5000
|
+
var SCREEN_FIELD_TYPES = ["text", "number", "money", "date", "status", "person", "email", "boolean"];
|
|
5001
|
+
var DATA_MODEL_DESCRIPTION = `Optional: the app's own records, so the screen's fields match them: {"records": [{"name": a PascalCase record name, "fields": [{"key": a camelCase field key, "label": the column heading (up to 32 characters), "type": ${quoted(SCREEN_FIELD_TYPES)}}]}]}, up to 3 records of up to 12 fields. Leave it out and the screen invents sample records.`;
|
|
4281
5002
|
var ACCOUNT_TOOLS = [
|
|
4282
5003
|
{
|
|
4283
5004
|
name: "list_design_systems",
|
|
@@ -4321,6 +5042,24 @@ var ACCOUNT_TOOLS = [
|
|
|
4321
5042
|
needsSnapshot: false,
|
|
4322
5043
|
accountTool: true,
|
|
4323
5044
|
run: (_s, _at, args, ctx) => useDesignSystem(args, ctx)
|
|
5045
|
+
},
|
|
5046
|
+
{
|
|
5047
|
+
name: "generate_screen",
|
|
5048
|
+
description: GENERATE_DESCRIPTION,
|
|
5049
|
+
inputSchema: {
|
|
5050
|
+
type: "object",
|
|
5051
|
+
properties: {
|
|
5052
|
+
prompt: { type: "string", description: "What the screen should show, or what to change in it, in a sentence or two (up to 500 characters)." },
|
|
5053
|
+
screen: { type: "string", description: "A screen name from list_screens, to change that screen. Leave it out to make a new one." },
|
|
5054
|
+
data_model: { type: "object", description: DATA_MODEL_DESCRIPTION }
|
|
5055
|
+
},
|
|
5056
|
+
required: ["prompt"],
|
|
5057
|
+
additionalProperties: false
|
|
5058
|
+
},
|
|
5059
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
|
|
5060
|
+
needsSnapshot: false,
|
|
5061
|
+
accountTool: true,
|
|
5062
|
+
run: (_s, _at, args, ctx) => generateScreen(args, ctx)
|
|
4324
5063
|
}
|
|
4325
5064
|
];
|
|
4326
5065
|
|
|
@@ -4368,6 +5107,67 @@ function optionalEnum(args, key, allowed) {
|
|
|
4368
5107
|
var MCP_EXEC_TIMEOUT_MS = 10 * 60 * 1e3;
|
|
4369
5108
|
var UNKNOWN_FOR_AGENT = (names) => `Unknown component(s): ${names.join(", ")}. Call list_components for the names.`;
|
|
4370
5109
|
var FOREIGN_FILES = (paths) => `These files exist and were not added by designsource: ${paths.join(", ")}. Ask the user whether to replace them, then call add_ui_kit again with replace_existing: true.`;
|
|
5110
|
+
function kitAccess(ctx) {
|
|
5111
|
+
if (ctx.token !== null) return { token: ctx.token, api: ctx.api };
|
|
5112
|
+
if (!ctx.account) return errorResult(ctx.missingToken ?? MCP_TOKEN_REQUIRED);
|
|
5113
|
+
const { token, api, projectId } = ctx.account;
|
|
5114
|
+
if (projectId === null) return errorResult(NO_LINK);
|
|
5115
|
+
return { token, api, kitPath: accountProjectPath(projectId, "kit"), messages: accountMessageForResponse };
|
|
5116
|
+
}
|
|
5117
|
+
var isResult2 = (v) => "content" in v;
|
|
5118
|
+
var isScreenName2 = (v) => typeof v === "string" && SCREEN_SLUG.test(v) && !RESERVED_SCREEN_SLUGS.includes(v);
|
|
5119
|
+
var SCREENS_NOT_LISTED = "This DS source server does not list screens yet.";
|
|
5120
|
+
var NO_SCREENS_LISTED = "This design system has no screens yet. Make one with generate_screen (after the user signs in with npx designsource login), or in the Screens view of the workbench.";
|
|
5121
|
+
var SCREEN_NAME_ARG = '"screen" must be a screen name from list_screens.';
|
|
5122
|
+
var SCREENS_ARG = '"screens" must be screen names from list_screens, or ["all"].';
|
|
5123
|
+
var SCREENS_NOT_SERVED_FOR_AGENT = "This DS source server does not send screens yet. Call add_ui_kit without screens.";
|
|
5124
|
+
function listScreens(snapshot) {
|
|
5125
|
+
if (!snapshot.screens) return errorResult(SCREENS_NOT_LISTED);
|
|
5126
|
+
if (snapshot.screens.length === 0) return textResult(NO_SCREENS_LISTED);
|
|
5127
|
+
return textResult(snapshot.screens.map((s) => `${s.slug} \u2014 ${printable(s.title)} (${s.kind})`).join("\n"));
|
|
5128
|
+
}
|
|
5129
|
+
function fenced(path, lang, text) {
|
|
5130
|
+
const longest = Math.max(0, ...(text.match(/`+/g) ?? []).map((run2) => run2.length));
|
|
5131
|
+
const fence = "`".repeat(Math.max(3, longest + 1));
|
|
5132
|
+
return `### ${path}
|
|
5133
|
+
${fence}${lang}
|
|
5134
|
+
${text}${text.endsWith("\n") ? "" : "\n"}${fence}`;
|
|
5135
|
+
}
|
|
5136
|
+
async function getScreenSource(args, ctx) {
|
|
5137
|
+
const slug = args.screen;
|
|
5138
|
+
if (!isScreenName2(slug)) return errorResult(SCREEN_NAME_ARG);
|
|
5139
|
+
const access = kitAccess(ctx);
|
|
5140
|
+
if (isResult2(access)) return access;
|
|
5141
|
+
const { kitPath, ...rest } = access;
|
|
5142
|
+
const manifest = await fetchKit({ ...rest, ...kitPath ? { path: kitPath } : {}, screens: [slug] }, ctx.fetchImpl);
|
|
5143
|
+
const index = manifest.screenIndex;
|
|
5144
|
+
if (index === void 0) return errorResult(SCREENS_NOT_LISTED);
|
|
5145
|
+
const entry = index.find((e) => e.slug === slug);
|
|
5146
|
+
if (!entry) return errorResult(UNKNOWN_SCREENS([slug], index, manifest.name));
|
|
5147
|
+
const screen = manifest.screens?.find((s) => s.slug === slug);
|
|
5148
|
+
if (!entry.available || !screen) return errorResult(SCREEN_UNAVAILABLE);
|
|
5149
|
+
const parts = screenPartsOf(screen, manifest);
|
|
5150
|
+
const partNames = parts.map((p) => p.name).sort();
|
|
5151
|
+
const components = [...new Set(parts.flatMap((p) => p.kitImports))].sort();
|
|
5152
|
+
const [tsx, data] = screen.files;
|
|
5153
|
+
return textResult(
|
|
5154
|
+
[
|
|
5155
|
+
`${slug} \u2014 ${printable(entry.title)} (${entry.kind}). Imports use the starter's @/components paths; add_ui_kit rewrites them to this app's aliases.`,
|
|
5156
|
+
fenced(`components/screens/${tsx.file}`, "tsx", tsx.contents),
|
|
5157
|
+
fenced(`components/screens/${data.file}`, "ts", data.contents),
|
|
5158
|
+
`Screen parts it imports (components/screens/parts/): ${partNames.join(", ") || "none"}`,
|
|
5159
|
+
`Kit components they import (components/ui/): ${components.join(", ") || "none"}`,
|
|
5160
|
+
`Call add_ui_kit with screens: ["${slug}"] to write it into the app.`
|
|
5161
|
+
].join("\n\n")
|
|
5162
|
+
);
|
|
5163
|
+
}
|
|
5164
|
+
function screensArg(v) {
|
|
5165
|
+
if (v === void 0) return { ok: true, value: void 0 };
|
|
5166
|
+
if (!Array.isArray(v) || !v.every((n) => typeof n === "string")) return { ok: false };
|
|
5167
|
+
if (v.includes("all")) return { ok: true, value: "all" };
|
|
5168
|
+
if (!v.every(isScreenName2)) return { ok: false };
|
|
5169
|
+
return { ok: true, value: v.length > 0 ? [...new Set(v)] : void 0 };
|
|
5170
|
+
}
|
|
4371
5171
|
async function addUiKit(args, ctx) {
|
|
4372
5172
|
const { components, replace_existing: replace, no_blocks: noBlocks } = args;
|
|
4373
5173
|
if (components !== void 0 && !(Array.isArray(components) && components.every((c) => typeof c === "string"))) {
|
|
@@ -4375,16 +5175,12 @@ async function addUiKit(args, ctx) {
|
|
|
4375
5175
|
}
|
|
4376
5176
|
if (replace !== void 0 && typeof replace !== "boolean") return errorResult('"replace_existing" must be true or false.');
|
|
4377
5177
|
if (noBlocks !== void 0 && typeof noBlocks !== "boolean") return errorResult('"no_blocks" must be true or false.');
|
|
4378
|
-
|
|
4379
|
-
if (
|
|
4380
|
-
|
|
4381
|
-
|
|
4382
|
-
|
|
4383
|
-
|
|
4384
|
-
if (ctx.account.projectId === null) return errorResult(NO_LINK);
|
|
4385
|
-
const { folder, token, api, projectId } = ctx.account;
|
|
4386
|
-
target = { root: folder, token, api, kitPath: accountProjectPath(projectId, "kit"), messages: accountMessageForResponse };
|
|
4387
|
-
} else return errorResult(ctx.missingToken ?? MCP_TOKEN_REQUIRED);
|
|
5178
|
+
const screens = screensArg(args.screens);
|
|
5179
|
+
if (!screens.ok) return errorResult(SCREENS_ARG);
|
|
5180
|
+
const access = kitAccess(ctx);
|
|
5181
|
+
if (isResult2(access)) return access;
|
|
5182
|
+
const root = ctx.token !== null ? resolveProjectFolder(ctx.cwd, ctx.projectFolders === null ? null : { folders: ctx.projectFolders }) : ctx.account.folder;
|
|
5183
|
+
if (root === null) return errorResult(NOT_SURE_WHICH_FOLDER);
|
|
4388
5184
|
const questions = {
|
|
4389
5185
|
pickComponents: async (all) => all,
|
|
4390
5186
|
confirmReplace: async (paths) => {
|
|
@@ -4397,7 +5193,16 @@ async function addUiKit(args, ctx) {
|
|
|
4397
5193
|
const exec = (cmd, cmdArgs, opts) => ctx.exec(cmd, cmdArgs, { ...opts, timeoutMs: MCP_EXEC_TIMEOUT_MS });
|
|
4398
5194
|
try {
|
|
4399
5195
|
const result = await runAdd(
|
|
4400
|
-
{
|
|
5196
|
+
{
|
|
5197
|
+
...access,
|
|
5198
|
+
root,
|
|
5199
|
+
components: components ?? [],
|
|
5200
|
+
skipInstall: false,
|
|
5201
|
+
blocks: noBlocks !== true,
|
|
5202
|
+
...screens.value !== void 0 ? { screens: screens.value } : {},
|
|
5203
|
+
// As a bare CLI rerun: a call naming neither components nor screens refreshes the screens an earlier run wrote.
|
|
5204
|
+
refreshScreens: true
|
|
5205
|
+
},
|
|
4401
5206
|
{ fetchImpl: ctx.fetchImpl, exec, questions, progress: (line) => progress.push(line) }
|
|
4402
5207
|
);
|
|
4403
5208
|
const written = result.added.filter((n) => n !== "preview-portal");
|
|
@@ -4411,7 +5216,7 @@ async function addUiKit(args, ctx) {
|
|
|
4411
5216
|
);
|
|
4412
5217
|
} catch (e) {
|
|
4413
5218
|
if (!(e instanceof CliError) && progress.length === 0) throw e;
|
|
4414
|
-
const message = e instanceof UnknownComponentsError ? UNKNOWN_FOR_AGENT(e.names) : e instanceof Error ? e.message : String(e);
|
|
5219
|
+
const message = e instanceof UnknownComponentsError ? UNKNOWN_FOR_AGENT(e.names) : e instanceof CliError && e.message === SCREENS_NOT_SERVED ? SCREENS_NOT_SERVED_FOR_AGENT : e instanceof Error ? e.message : String(e);
|
|
4415
5220
|
const tail = e instanceof StepError && e.outputTail ? ["Last output:", e.outputTail] : [];
|
|
4416
5221
|
return errorResult([...progress, message, ...tail].join("\n"));
|
|
4417
5222
|
}
|
|
@@ -4534,15 +5339,31 @@ ${blocks.sources[f] ?? ""}`);
|
|
|
4534
5339
|
${files.join("\n\n")}`);
|
|
4535
5340
|
}
|
|
4536
5341
|
},
|
|
5342
|
+
{
|
|
5343
|
+
name: "list_screens",
|
|
5344
|
+
description: "The app screens made for this design system in DS source (lists, details, settings, forms, dashboards built from the kit): one line each, name \u2014 title (kind). Follow with get_screen_source, or write them into the app with add_ui_kit and screens.",
|
|
5345
|
+
inputSchema: NO_INPUT,
|
|
5346
|
+
annotations: READ_ONLY,
|
|
5347
|
+
run: (snapshot) => listScreens(snapshot)
|
|
5348
|
+
},
|
|
5349
|
+
{
|
|
5350
|
+
name: "get_screen_source",
|
|
5351
|
+
description: "The React + Tailwind source of one screen (see list_screens): <name>.tsx and its sample data <name>.data.ts, then the screen parts and kit components it imports. To use it in a React app, call add_ui_kit with screens, which writes it with everything it imports; then mount it on a route.",
|
|
5352
|
+
inputSchema: { type: "object", properties: { screen: { type: "string", description: "A screen name from list_screens." } }, required: ["screen"], additionalProperties: false },
|
|
5353
|
+
annotations: READ_ONLY,
|
|
5354
|
+
needsSnapshot: false,
|
|
5355
|
+
run: (_snapshot, _at, args, ctx) => getScreenSource(args, ctx)
|
|
5356
|
+
},
|
|
4537
5357
|
{
|
|
4538
5358
|
name: "add_ui_kit",
|
|
4539
|
-
description:
|
|
5359
|
+
description: `Add this design system's UI kit to the React app in the current folder: the theme, the components and their libraries. Sets up Tailwind and shadcn when the app lacks them. A full run (no components and no screens named) also writes the /design-system section, every component, block and sample page in the project's theme, with its blocks unless no_blocks is true, and refreshes the screens an earlier run wrote. screens (names from list_screens, or ["all"]) writes those app screens with the parts and components they import; you mount each on a route. Changes files in the project, so your client will ask the user first. Never overwrites components or screens the user edited.`,
|
|
4540
5360
|
inputSchema: {
|
|
4541
5361
|
type: "object",
|
|
4542
5362
|
properties: {
|
|
4543
5363
|
components: { type: "array", items: { type: "string" }, description: "Component names such as button or dialog. Omit to add everything (or refresh what was added before)." },
|
|
4544
5364
|
replace_existing: { type: "boolean", description: "Replace component files that exist but were not added by designsource. Ask the user first." },
|
|
4545
|
-
no_blocks: { type: "boolean", description: "Add the /design-system section without its blocks and their libraries. Blocks an earlier run wrote are left in place." }
|
|
5365
|
+
no_blocks: { type: "boolean", description: "Add the /design-system section without its blocks and their libraries. Blocks an earlier run wrote are left in place." },
|
|
5366
|
+
screens: { type: "array", items: { type: "string" }, description: `Screen names from list_screens, or ["all"] for every screen. Each is written under the components folder's screens/ with the parts and kit components it imports.` }
|
|
4546
5367
|
},
|
|
4547
5368
|
additionalProperties: false
|
|
4548
5369
|
},
|
|
@@ -4634,20 +5455,24 @@ var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
|
4634
5455
|
var isStringRecord = (v) => isObject2(v) && Object.values(v).every((x) => typeof x === "string");
|
|
4635
5456
|
var isStringListRecord = (v) => isObject2(v) && Object.values(v).every((x) => Array.isArray(x) && x.every((s) => typeof s === "string"));
|
|
4636
5457
|
var isBlockEntry = (v) => isObject2(v) && typeof v.id === "string" && typeof v.title === "string" && typeof v.family === "string" && Array.isArray(v.components) && v.components.every((c) => typeof c === "string") && Array.isArray(v.files) && v.files.every((f) => typeof f === "string");
|
|
5458
|
+
var isScreenRow = (v) => isObject2(v) && typeof v.slug === "string" && SCREEN_SLUG.test(v.slug) && !RESERVED_SCREEN_SLUGS.includes(v.slug) && typeof v.title === "string" && typeof v.kind === "string" && SCREEN_KINDS.includes(v.kind) && typeof v.updatedAt === "string";
|
|
5459
|
+
var isScreenIndex = (v) => Array.isArray(v) && v.every(isScreenRow) && new Set(v.map((r) => r.slug)).size === v.length;
|
|
4637
5460
|
function validateSnapshot(json) {
|
|
4638
5461
|
if (!isObject2(json)) throw malformed4();
|
|
4639
5462
|
if (typeof json.version !== "number") throw malformed4();
|
|
4640
5463
|
if (json.version !== 1) throw new CliError(UPDATE_MESSAGE);
|
|
4641
|
-
const { project, canonical, cssVars, shadcnTheme, kit, mockup, blocks, guide } = json;
|
|
5464
|
+
const { project, canonical, cssVars, shadcnTheme, kit, mockup, blocks, screens, guide } = json;
|
|
4642
5465
|
if (!isObject2(project) || typeof project.name !== "string" || typeof project.radiusStrategy !== "string" || typeof project.tokenCount !== "number" || typeof project.hasMockup !== "boolean" || !isStringRecord(project.fonts)) throw malformed4();
|
|
4643
5466
|
if (!isObject2(canonical) || !Array.isArray(canonical.tokens) || !canonical.tokens.every(isObject2)) throw malformed4();
|
|
4644
5467
|
if (typeof cssVars !== "string" || typeof shadcnTheme !== "string" || typeof guide !== "string") throw malformed4();
|
|
4645
5468
|
if (!isObject2(kit) || !isStringRecord(kit.sources) || !isStringListRecord(kit.variables)) throw malformed4();
|
|
4646
5469
|
if (mockup !== null && !(isObject2(mockup) && isObject2(mockup.spec) && isStringRecord(mockup.renderer))) throw malformed4();
|
|
5470
|
+
const out = { ...json };
|
|
5471
|
+
if (screens !== void 0 && !isScreenIndex(screens)) out.screens = void 0;
|
|
4647
5472
|
const validBlocks = isObject2(blocks) && Array.isArray(blocks.index) && blocks.index.every(isBlockEntry) && isStringRecord(blocks.sources);
|
|
4648
|
-
if (!validBlocks)
|
|
4649
|
-
if (blocks.header !== void 0 && typeof blocks.header !== "string")
|
|
4650
|
-
return
|
|
5473
|
+
if (!validBlocks) out.blocks = void 0;
|
|
5474
|
+
else if (blocks.header !== void 0 && typeof blocks.header !== "string") out.blocks = { ...blocks, header: void 0 };
|
|
5475
|
+
return out;
|
|
4651
5476
|
}
|
|
4652
5477
|
async function fetchSnapshot(opts, fetchImpl = fetch) {
|
|
4653
5478
|
const { api, token, path = "/api/snapshot", messages } = opts;
|
|
@@ -4774,7 +5599,7 @@ ${resolved.message}`,
|
|
|
4774
5599
|
}
|
|
4775
5600
|
return res;
|
|
4776
5601
|
});
|
|
4777
|
-
return { token: null, projectFolders: null, api: current.api, cwd, account: current, fetchImpl, exec: spawnExec };
|
|
5602
|
+
return { token: null, projectFolders: null, api: current.api, cwd, account: current, fetchImpl, exec: spawnExec, dropSnapshot: () => cache.clear() };
|
|
4778
5603
|
};
|
|
4779
5604
|
const session = () => projectPath ? projectSession() : accountSession();
|
|
4780
5605
|
const cache = createSnapshotCache(async () => {
|