designsource 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +4 -2
  2. package/dist/index.js +1276 -209
  3. 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", "app", "design-system", "api", "site"];
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|site] [--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,9 @@ 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 and pages from DS source, by file name (repeatable, or comma-separated); all for every one;
1055
+ shell for a sidebar app shell listing the screens in the app; site for the menu and footer around
1056
+ the pages in the app
1031
1057
  --token the project token (workbench \u2192 Project settings); or DS_SYNC_TOKEN
1032
1058
  --api API origin (default ${DEFAULT_API_ORIGIN})
1033
1059
  `;
@@ -1148,10 +1174,23 @@ function switchOf(arg, usage) {
1148
1174
  }
1149
1175
  var unknownOption = (arg, usage) => new ArgsError(`Unknown option ${arg.name}`, usage);
1150
1176
  var ADD_SWITCHES = /* @__PURE__ */ new Map([["yes", "yes"], ["all", "all"], ["force", "force"], ["skip-install", "skipInstall"], ["no-blocks", "noBlocks"]]);
1177
+ var SCREEN_NAME_MESSAGE = "--screen takes screen names from DS source (letters, digits and dashes), or all.";
1178
+ function screensIn(values, usage) {
1179
+ const words = values.flatMap((v) => v.split(",").map((w) => w.trim()));
1180
+ if (words.some((n) => n === "")) throw new ArgsError(SCREEN_NAME_MESSAGE, usage);
1181
+ const shell = { ...words.includes("shell") ? { shell: true } : {}, ...words.includes("site") ? { site: true } : {} };
1182
+ const names = words.filter((n) => n !== "shell" && n !== "site");
1183
+ if (names.includes("all")) return { screens: "all", ...shell };
1184
+ for (const n of names) {
1185
+ if (!SCREEN_SLUG.test(n) || RESERVED_SCREEN_SLUGS.includes(n)) throw new ArgsError(SCREEN_NAME_MESSAGE, usage);
1186
+ }
1187
+ return { ...names.length > 0 ? { screens: [...new Set(names)] } : {}, ...shell };
1188
+ }
1151
1189
  function parseAdd(argv, env) {
1152
1190
  const args = { components: [], api: DEFAULT_API_ORIGIN, yes: false, all: false, force: false, skipInstall: false, noBlocks: false };
1153
1191
  if (env.DS_SYNC_TOKEN) args.token = env.DS_SYNC_TOKEN;
1154
- for (const arg of scan(argv, ["token", "api"], [...ADD_SWITCHES.keys()])) {
1192
+ const screenValues = [];
1193
+ for (const arg of scan(argv, ["token", "api", "screen"], [...ADD_SWITCHES.keys()])) {
1155
1194
  if (arg.kind === "help") return { kind: "help", verb: "add" };
1156
1195
  if (arg.kind === "positional") {
1157
1196
  args.components.push(arg.value);
@@ -1161,11 +1200,13 @@ function parseAdd(argv, env) {
1161
1200
  if (field) args[field] = switchOf(arg, ADD_USAGE);
1162
1201
  else if (arg.known === null) throw unknownOption(arg, ADD_USAGE);
1163
1202
  else if (arg.key === "token") args.token = valueOf(arg, ADD_USAGE);
1203
+ else if (arg.key === "screen") screenValues.push(valueOf(arg, ADD_USAGE));
1164
1204
  else {
1165
1205
  args.api = parseApiOrigin(valueOf(arg, ADD_USAGE), ADD_USAGE);
1166
1206
  args.apiGiven = true;
1167
1207
  }
1168
1208
  }
1209
+ if (screenValues.length) Object.assign(args, screensIn(screenValues, ADD_USAGE));
1169
1210
  return { kind: "add", args };
1170
1211
  }
1171
1212
  function appsIn(value, usage = CONNECT_USAGE) {
@@ -1244,7 +1285,8 @@ function parseVerb(verb, argv, env) {
1244
1285
  const usage = usageFor(verb);
1245
1286
  const args = baseArgs(env);
1246
1287
  const strings = verb === "integrate" ? ["framework", "token", "api"] : ["token", "api"];
1247
- for (const arg of scan(argv, strings, ["force"])) {
1288
+ const booleans = verb === "create" ? ["force", "no-screens"] : ["force"];
1289
+ for (const arg of scan(argv, strings, booleans)) {
1248
1290
  if (arg.kind === "help") return { kind: "help", verb };
1249
1291
  if (arg.kind === "positional") {
1250
1292
  if (args.folder !== void 0) throw new ArgsError("Expected one folder argument", usage);
@@ -1253,6 +1295,7 @@ function parseVerb(verb, argv, env) {
1253
1295
  }
1254
1296
  if (arg.known === null) throw unknownOption(arg, usage);
1255
1297
  if (arg.key === "force") args.force = switchOf(arg, usage);
1298
+ else if (arg.key === "no-screens") args.noScreens = switchOf(arg, usage);
1256
1299
  else if (arg.key === "framework") {
1257
1300
  const value = valueOf(arg, usage);
1258
1301
  if (!isIntegrateFramework(value)) throw new ArgsError(`Unknown framework "${value}" \u2014 one of ${INTEGRATE_FRAMEWORKS.join(", ")}`, usage);
@@ -1457,12 +1500,338 @@ function planFiles(root, t, components, manifest) {
1457
1500
  // src/add/section.ts
1458
1501
  import { existsSync as existsSync6, readdirSync as readdirSync2, readFileSync as readFileSync6 } from "node:fs";
1459
1502
  import { join as join4 } from "node:path";
1503
+
1504
+ // src/add/screen-gen.ts
1505
+ var SCREEN_KINDS = ["list", "detail", "settings", "form", "dashboard"];
1506
+ var PAGE_KINDS = ["home", "pricing", "waitlist"];
1507
+ function isPageKind(kind) {
1508
+ return PAGE_KINDS.includes(kind);
1509
+ }
1510
+ var isAppScreen = (s) => !isPageKind(s.kind);
1511
+ var SCREEN_KIND_ICON_NAMES = {
1512
+ list: "ListDetailsIcon",
1513
+ detail: "UserIcon",
1514
+ settings: "SettingsIcon",
1515
+ form: "FileTextIcon",
1516
+ dashboard: "DashboardIcon"
1517
+ };
1518
+ function jsonLiteral(value, indent) {
1519
+ return JSON.stringify(value, null, indent).replace(/[\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`).replace(/<\//g, "<\\/");
1520
+ }
1521
+ function screenComponentName(slug) {
1522
+ return slug.split("-").filter(Boolean).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("") + "Screen";
1523
+ }
1524
+ function checkShellScreens(screens) {
1525
+ const seen = /* @__PURE__ */ new Set();
1526
+ for (const s of screens) {
1527
+ if (typeof s.slug !== "string" || !SCREEN_SLUG.test(s.slug)) throw new Error("Invalid screen slug");
1528
+ if (RESERVED_SCREEN_SLUGS.includes(s.slug)) throw new Error("Reserved screen slug");
1529
+ if (seen.has(s.slug)) throw new Error("Duplicate screen slug");
1530
+ seen.add(s.slug);
1531
+ if (typeof s.kind !== "string" || !SCREEN_KINDS.includes(s.kind) && !isPageKind(s.kind)) throw new Error("Unknown screen kind");
1532
+ if (typeof s.title !== "string") throw new Error("Invalid screen title");
1533
+ }
1534
+ }
1535
+ function assembleAppShell(input) {
1536
+ checkShellScreens(input.screens);
1537
+ if (typeof input.name !== "string") throw new Error("Invalid app name");
1538
+ if (input.hrefFor !== "app" && input.hrefFor !== "root") throw new Error("Invalid hrefFor");
1539
+ const prefix = input.hrefFor === "app" ? "/app/" : "/";
1540
+ const links = input.screens.filter(isAppScreen).map((s) => ({ href: `${prefix}${s.slug}`, title: s.title, kind: s.kind }));
1541
+ const icons = [...new Set(SCREEN_KINDS.map((k) => SCREEN_KIND_ICON_NAMES[k]))].sort();
1542
+ const kindIcons = SCREEN_KINDS.map((k) => ` ${k}: ${SCREEN_KIND_ICON_NAMES[k]},`);
1543
+ return [
1544
+ "'use client'",
1545
+ "",
1546
+ "import { useEffect, useState, type ReactNode } from 'react'",
1547
+ `import { ${icons.join(", ")}, type IconComponent } from '@/components/ui/icons'`,
1548
+ "import {",
1549
+ " Sidebar,",
1550
+ " SidebarContent,",
1551
+ " SidebarGroup,",
1552
+ " SidebarGroupContent,",
1553
+ " SidebarHeader,",
1554
+ " SidebarInset,",
1555
+ " SidebarMenu,",
1556
+ " SidebarMenuButton,",
1557
+ " SidebarMenuItem,",
1558
+ " SidebarProvider,",
1559
+ " SidebarTrigger,",
1560
+ "} from '@/components/ui/sidebar'",
1561
+ "",
1562
+ `type ScreenKind = ${SCREEN_KINDS.map((k) => `'${k}'`).join(" | ")}`,
1563
+ "type ShellLink = { href: string; title: string; kind: ScreenKind }",
1564
+ "",
1565
+ `const NAME: string = ${jsonLiteral(input.name)}`,
1566
+ "",
1567
+ `const SCREENS: ShellLink[] = ${jsonLiteral(links, 2)}`,
1568
+ "",
1569
+ "const KIND_ICONS: Record<ScreenKind, IconComponent> = {",
1570
+ ...kindIcons,
1571
+ "}",
1572
+ "",
1573
+ "/** The current path, read after mount so the first client render matches the server. */",
1574
+ "function useCurrentPath(): string | null {",
1575
+ " const [path, setPath] = useState<string | null>(null)",
1576
+ " useEffect(() => {",
1577
+ " const read = () => setPath(window.location.pathname.replace(/\\/+$/, '') || '/')",
1578
+ " read()",
1579
+ " window.addEventListener('popstate', read)",
1580
+ " return () => window.removeEventListener('popstate', read)",
1581
+ " }, [])",
1582
+ " return path",
1583
+ "}",
1584
+ "",
1585
+ "export function AppShell({ children }: { children: ReactNode }) {",
1586
+ " const path = useCurrentPath()",
1587
+ " return (",
1588
+ ' <div className="@container/stage">',
1589
+ " <SidebarProvider>",
1590
+ " <Sidebar>",
1591
+ " <SidebarHeader>",
1592
+ ' <div className="truncate px-2 py-1.5 text-sm font-semibold">{NAME}</div>',
1593
+ " </SidebarHeader>",
1594
+ " <SidebarContent>",
1595
+ " <SidebarGroup>",
1596
+ " <SidebarGroupContent>",
1597
+ " <SidebarMenu>",
1598
+ " {SCREENS.map((screen) => {",
1599
+ " const Icon = KIND_ICONS[screen.kind]",
1600
+ " const active = path === screen.href",
1601
+ " return (",
1602
+ " <SidebarMenuItem key={screen.href}>",
1603
+ " <SidebarMenuButton asChild isActive={active} tooltip={screen.title}>",
1604
+ " <a href={screen.href} aria-current={active ? 'page' : undefined}>",
1605
+ " <Icon />",
1606
+ " <span>{screen.title}</span>",
1607
+ " </a>",
1608
+ " </SidebarMenuButton>",
1609
+ " </SidebarMenuItem>",
1610
+ " )",
1611
+ " })}",
1612
+ " </SidebarMenu>",
1613
+ " </SidebarGroupContent>",
1614
+ " </SidebarGroup>",
1615
+ " </SidebarContent>",
1616
+ " </Sidebar>",
1617
+ " <SidebarInset>",
1618
+ ' <header className="flex h-12 shrink-0 items-center gap-2 border-b px-4 @[40rem]/stage:px-6">',
1619
+ ' <SidebarTrigger className="-ml-1" />',
1620
+ " </header>",
1621
+ ' <div className="flex flex-1 flex-col">{children}</div>',
1622
+ " </SidebarInset>",
1623
+ " </SidebarProvider>",
1624
+ " </div>",
1625
+ " )",
1626
+ "}",
1627
+ "",
1628
+ "AppShell.displayName = 'AppShell'",
1629
+ ""
1630
+ ].join("\n");
1631
+ }
1632
+ var DEFAULT_SCREENS_IMPORT = "@/components/screens";
1633
+ var SCREENS_IMPORT = /^[A-Za-z0-9@~#_.-]+(?:\/[A-Za-z0-9@~#_.-]+)*$/;
1634
+ var HEAD = [
1635
+ `export type SectionScreenKind = ${[...SCREEN_KINDS, ...PAGE_KINDS].map((k) => `'${k}'`).join(" | ")}`,
1636
+ "export type SectionScreenEntry = { slug: string; title: string; kind: SectionScreenKind }"
1637
+ ];
1638
+ function assembleScreenRegistry(input) {
1639
+ checkShellScreens(input.screens);
1640
+ const screensImport = input.screensImport ?? DEFAULT_SCREENS_IMPORT;
1641
+ if (typeof screensImport !== "string" || !SCREENS_IMPORT.test(screensImport)) throw new Error("Invalid screensImport");
1642
+ if (typeof input.name !== "string") throw new Error("Invalid site name");
1643
+ if (!Number.isInteger(input.year)) throw new Error("Invalid year");
1644
+ if (input.action !== void 0 && typeof input.action !== "string") throw new Error("Invalid action label");
1645
+ const entries = input.screens.map((s) => ({ slug: s.slug, title: s.title, kind: s.kind }));
1646
+ const pages = entries.flatMap((s) => isPageKind(s.kind) ? [{ slug: s.slug, title: s.title, kind: s.kind }] : []);
1647
+ const site = siteFrameProps({ name: input.name, pages, year: input.year, fallbackActionLabel: input.action });
1648
+ if (entries.length === 0) {
1649
+ return [
1650
+ ...HEAD,
1651
+ "",
1652
+ "export const SECTION_SCREENS: SectionScreenEntry[] = []",
1653
+ "",
1654
+ "/** No screens yet: every slug renders nothing, and the view around this says what is missing. */",
1655
+ // A typed const rather than a function with an unused parameter, which a stock Next lint config warns about.
1656
+ "export const SectionScreen: ((props: { slug: string }) => null) & { displayName?: string } = () => null",
1657
+ "",
1658
+ "SectionScreen.displayName = 'SectionScreen'",
1659
+ ""
1660
+ ].join("\n");
1661
+ }
1662
+ const views = entries.map(
1663
+ (s) => ` ${jsonLiteral(s.slug)}: lazy(() => import(${jsonLiteral(`${screensImport}/${s.slug}`)}).then((m) => ({ default: m.${screenComponentName(s.slug)} }))),`
1664
+ );
1665
+ if (pages.length === 0) {
1666
+ return [
1667
+ "import { lazy, Suspense, type ComponentType } from 'react'",
1668
+ "",
1669
+ ...HEAD,
1670
+ "",
1671
+ `export const SECTION_SCREENS: SectionScreenEntry[] = ${jsonLiteral(entries, 2)}`,
1672
+ "",
1673
+ "const VIEWS: Record<string, ComponentType> = {",
1674
+ ...views,
1675
+ "}",
1676
+ "",
1677
+ "export function SectionScreen({ slug }: { slug: string }) {",
1678
+ " const View = Object.prototype.hasOwnProperty.call(VIEWS, slug) ? VIEWS[slug] : undefined",
1679
+ " if (!View) return null",
1680
+ " return (",
1681
+ " <Suspense fallback={null}>",
1682
+ " <View />",
1683
+ " </Suspense>",
1684
+ " )",
1685
+ "}",
1686
+ "",
1687
+ "SectionScreen.displayName = 'SectionScreen'",
1688
+ ""
1689
+ ].join("\n");
1690
+ }
1691
+ return [
1692
+ "import { lazy, Suspense, type ComponentProps, type ComponentType } from 'react'",
1693
+ `import { SiteFrame, SiteHeader, SiteFooter } from '${screensImport}/parts/site-frame'`,
1694
+ `import { SiteLinksProvider } from '${screensImport}/parts/site-links'`,
1695
+ "",
1696
+ ...HEAD,
1697
+ "",
1698
+ `export const SECTION_SCREENS: SectionScreenEntry[] = ${jsonLiteral(entries, 2)}`,
1699
+ "",
1700
+ "const VIEWS: Record<string, ComponentType> = {",
1701
+ ...views,
1702
+ "}",
1703
+ "",
1704
+ "/** The marketing pages: drawn inside the site menu and footer, their links inert, since the section is a showcase. */",
1705
+ `const PAGES: ReadonlySet<string> = new Set(${jsonLiteral(pages.map((p) => p.slug))})`,
1706
+ "",
1707
+ "type SiteProps = {",
1708
+ " hrefs: ComponentProps<typeof SiteLinksProvider>['value']['hrefs']",
1709
+ " header: ComponentProps<typeof SiteHeader>",
1710
+ " footer: ComponentProps<typeof SiteFooter>",
1711
+ "}",
1712
+ "",
1713
+ `const SITE: SiteProps = ${jsonLiteral(site, 2)}`,
1714
+ "",
1715
+ "export function SectionScreen({ slug }: { slug: string }) {",
1716
+ " const View = Object.prototype.hasOwnProperty.call(VIEWS, slug) ? VIEWS[slug] : undefined",
1717
+ " if (!View) return null",
1718
+ " return (",
1719
+ " <Suspense fallback={null}>",
1720
+ " {PAGES.has(slug) ? (",
1721
+ " <SiteLinksProvider value={{ hrefs: SITE.hrefs, inert: true }}>",
1722
+ " <SiteFrame>",
1723
+ " <SiteHeader {...SITE.header} />",
1724
+ " <View />",
1725
+ " <SiteFooter {...SITE.footer} />",
1726
+ " </SiteFrame>",
1727
+ " </SiteLinksProvider>",
1728
+ " ) : (",
1729
+ " <View />",
1730
+ " )}",
1731
+ " </Suspense>",
1732
+ " )",
1733
+ "}",
1734
+ "",
1735
+ "SectionScreen.displayName = 'SectionScreen'",
1736
+ ""
1737
+ ].join("\n");
1738
+ }
1739
+ function checkSitePages(pages) {
1740
+ const kinds = /* @__PURE__ */ new Set();
1741
+ for (const p of pages) {
1742
+ if (typeof p.slug !== "string" || !SCREEN_SLUG.test(p.slug)) throw new Error("Invalid page slug");
1743
+ if (RESERVED_SCREEN_SLUGS.includes(p.slug)) throw new Error("Reserved page slug");
1744
+ if (typeof p.kind !== "string" || !isPageKind(p.kind)) throw new Error("Unknown page kind");
1745
+ if (kinds.has(p.kind)) throw new Error("Duplicate page kind");
1746
+ kinds.add(p.kind);
1747
+ if (typeof p.title !== "string") throw new Error("Invalid page title");
1748
+ }
1749
+ }
1750
+ var inKindOrder = (pages) => PAGE_KINDS.flatMap((k) => pages.filter((p) => p.kind === k));
1751
+ function siteFrameProps(input) {
1752
+ checkSitePages(input.pages);
1753
+ const ordered = inKindOrder(input.pages);
1754
+ const hrefs = {};
1755
+ for (const p of ordered) hrefs[p.kind] = p.kind === "home" ? "/" : `/${p.slug}`;
1756
+ const action = ordered.some((p) => p.kind === "waitlist") ? { label: "Join the waitlist", variant: "default", to: "waitlist" } : { label: input.fallbackActionLabel ?? "Get started", variant: "default" };
1757
+ return {
1758
+ hrefs,
1759
+ header: {
1760
+ name: input.name,
1761
+ links: ordered.filter((p) => p.kind !== "home" && p.kind !== "waitlist").map((p) => ({ label: p.title, to: p.kind })),
1762
+ action
1763
+ },
1764
+ footer: { name: input.name, links: ordered.map((p) => ({ label: p.title, to: p.kind })), year: input.year }
1765
+ };
1766
+ }
1767
+ function assembleSiteShell(input) {
1768
+ checkSitePages(input.pages);
1769
+ if (typeof input.name !== "string") throw new Error("Invalid site name");
1770
+ if (!Number.isInteger(input.year)) throw new Error("Invalid year");
1771
+ if (input.fallbackActionLabel !== void 0 && typeof input.fallbackActionLabel !== "string") throw new Error("Invalid action label");
1772
+ const { hrefs, header, footer } = siteFrameProps({
1773
+ name: input.name,
1774
+ pages: input.pages,
1775
+ year: input.year,
1776
+ fallbackActionLabel: input.fallbackActionLabel
1777
+ });
1778
+ return [
1779
+ "'use client'",
1780
+ "",
1781
+ "import type { ComponentProps } from 'react'",
1782
+ "import { SiteFrame, SiteHeader, SiteFooter } from '@/components/screens/parts/site-frame'",
1783
+ "import { SiteLinksProvider } from '@/components/screens/parts/site-links'",
1784
+ "",
1785
+ `const hrefs: ComponentProps<typeof SiteLinksProvider>['value']['hrefs'] = ${jsonLiteral(hrefs, 2)}`,
1786
+ "",
1787
+ `const header: ComponentProps<typeof SiteHeader> = ${jsonLiteral(header, 2)}`,
1788
+ "",
1789
+ `const footer: ComponentProps<typeof SiteFooter> = ${jsonLiteral(footer, 2)}`,
1790
+ "",
1791
+ "export function SiteShell({ children }: { children: React.ReactNode }) {",
1792
+ " return (",
1793
+ " <SiteLinksProvider value={{ hrefs }}>",
1794
+ " <SiteFrame>",
1795
+ " <SiteHeader {...header} />",
1796
+ " {children}",
1797
+ " <SiteFooter {...footer} />",
1798
+ " </SiteFrame>",
1799
+ " </SiteLinksProvider>",
1800
+ " )",
1801
+ "}",
1802
+ "",
1803
+ "SiteShell.displayName = 'SiteShell'",
1804
+ ""
1805
+ ].join("\n");
1806
+ }
1807
+
1808
+ // src/add/section.ts
1460
1809
  var SECTION_NEEDS_FULL_KIT = "The /design-system section comes with the full kit: run designsource add --all.";
1461
1810
  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
1811
  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
1812
  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
1813
  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
1814
  var OWN_DESIGN_SYSTEM_ROUTE = (path) => `Skipped the /design-system section: this app already has its own /design-system route (${path}).`;
1815
+ var REGISTRY_KEY = "section/section-screens.tsx";
1816
+ var REGISTRY_STAMP = "section:screens";
1817
+ var sectionKnowsScreens = (manifest) => manifest.section?.files.some((f) => f.key === REGISTRY_KEY) ?? false;
1818
+ function sectionReadsScreens(root, t) {
1819
+ if (t.componentsDir === null) return false;
1820
+ try {
1821
+ const routes = readFileSync6(resolveInside(root, join22(t.componentsDir, "design-system/section-routes.ts")), "utf8");
1822
+ return /from ['"]\.\/section-screens['"]/.test(routes);
1823
+ } catch {
1824
+ return false;
1825
+ }
1826
+ }
1827
+ var registryPath = (componentsDir) => join22(componentsDir, "design-system/section-screens.tsx");
1828
+ function registrySite(manifest, year = (/* @__PURE__ */ new Date()).getUTCFullYear()) {
1829
+ const action = manifest.screenIndex?.find((e) => e.kind === "home")?.action;
1830
+ return { name: manifest.name, year, ...typeof action === "string" ? { action } : {} };
1831
+ }
1832
+ function registryFile(componentsDir, t, screens, site) {
1833
+ return stamped(registryPath(componentsDir), REGISTRY_STAMP, rewriteForApp(assembleScreenRegistry({ screens, ...site }), t));
1834
+ }
1466
1835
  function shownBlockGroups(groups, blocks, keptBlockIds = []) {
1467
1836
  if (blocks === "write") return groups;
1468
1837
  if (blocks === "skip") return [];
@@ -1511,12 +1880,19 @@ function planSectionFiles(input) {
1511
1880
  const files = [];
1512
1881
  for (const f of section.files) {
1513
1882
  if (f.block && blocks !== "write") continue;
1883
+ if (f.key === REGISTRY_KEY) continue;
1514
1884
  const { path, name } = placeManifestFile(f.key, componentsDir, t);
1515
1885
  let contents = rewriteForApp(f.contents, t);
1516
1886
  if (f.key === "section/section-views.tsx" && blocks === "skip") contents = pointAtStub(contents, t.componentsAlias);
1517
1887
  files.push(stamped(path, name, contents));
1518
1888
  }
1519
1889
  if (blocks === "skip") files.push(stamped(ds("block-view.tsx"), "section:block-view", NO_BLOCKS_VIEW));
1890
+ const screens = sectionKnowsScreens(manifest);
1891
+ if (screens && input.screens !== null) files.push(registryFile(componentsDir, t, input.screens, registrySite(manifest)));
1892
+ else if (screens && !input.registryOnDisk) {
1893
+ const fallback = section.files.find((f) => f.key === REGISTRY_KEY);
1894
+ files.push(stamped(registryPath(componentsDir), REGISTRY_STAMP, rewriteForApp(fallback.contents, t)));
1895
+ }
1520
1896
  const hasMockup = section.mockupSpec !== null;
1521
1897
  const darkMarker = vite ? { kind: "class", name: "dark" } : input.darkMarker;
1522
1898
  const config = {
@@ -1530,7 +1906,7 @@ function planSectionFiles(input) {
1530
1906
  files.push(stamped(ds("section-config.ts"), "section:config", cliSectionConfig(config)));
1531
1907
  if (hasMockup) files.push(stamped(ds("page.json"), "section:page", `${JSON.stringify(section.mockupSpec, null, 2)}
1532
1908
  `));
1533
- files.push(stamped(ds("section-routes.ts"), "section:routes", vite ? viteSectionRoutes(hasMockup, t) : sectionRoutes(hasMockup, t)));
1909
+ files.push(stamped(ds("section-routes.ts"), "section:routes", vite ? viteSectionRoutes(hasMockup, screens, t) : sectionRoutes(hasMockup, screens, t)));
1534
1910
  if (vite) {
1535
1911
  const entry = (file) => join22(input.srcDir, `design-system/${file}`);
1536
1912
  files.push(stamped("design-system.html", "section:page-html", vitePage(manifest.name, entry("main.tsx"))));
@@ -1541,7 +1917,7 @@ function planSectionFiles(input) {
1541
1917
  files.push(stamped(ds("section-theme.css"), "section:theme", section.themeCss));
1542
1918
  files.push(stamped(ds("section-page.tsx"), "section:section-page", NEXT_SECTION_PAGE));
1543
1919
  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)));
1920
+ files.push(stamped(`${input.appDir}/design-system/[[...path]]/page.tsx`, "section:route:page", nextPage(t, screens)));
1545
1921
  return files;
1546
1922
  }
1547
1923
  var NO_BLOCKS_VIEW = `// This project was added without blocks (designsource add --no-blocks): the section has no Blocks views.
@@ -1562,21 +1938,22 @@ export const MOCKUP_SPEC: StoredMockupSpec | null = mockupSpecShapeSchema.parse(
1562
1938
  export const MOCKUP_SPEC: StoredMockupSpec | null = null
1563
1939
  `;
1564
1940
  }
1565
- var ROUTES_IMPORTS = `import { SECTION_CONFIG } from './section-config'
1941
+ var routesImports = (screens) => `import { SECTION_CONFIG } from './section-config'
1566
1942
  import { parseSectionPath, type SectionFeatures, type SectionRoute, sectionPath } from './section-nav'
1567
- `;
1568
- var FEATURES = `export const SECTION_FEATURES: SectionFeatures = {
1943
+ ${screens ? `import { SECTION_SCREENS } from './section-screens'
1944
+ ` : ""}`;
1945
+ var features = (screens) => `export const SECTION_FEATURES: SectionFeatures = {
1569
1946
  hasMockup: SECTION_CONFIG.hasMockup,
1570
1947
  hasBlocks: SECTION_CONFIG.hasBlocks,
1571
1948
  blockIds: SECTION_CONFIG.blockGroups.flatMap((group) => group.blocks.map((block) => block.id)),
1572
- }
1949
+ ${screens ? " screenSlugs: SECTION_SCREENS.map((screen) => screen.slug),\n" : ""}}
1573
1950
  `;
1574
- function sectionRoutes(hasMockup, t) {
1575
- return `${ROUTES_IMPORTS}${mockupModule(hasMockup, t)}
1951
+ function sectionRoutes(hasMockup, screens, t) {
1952
+ return `${routesImports(screens)}${mockupModule(hasMockup, t)}
1576
1953
  /** Where the section lives. */
1577
1954
  export const SECTION_BASE = '/design-system'
1578
1955
 
1579
- ${FEATURES}
1956
+ ${features(screens)}
1580
1957
  /** A \`sectionPath()\` result as an href. */
1581
1958
  export const sectionHref = (path: string) => \`\${SECTION_BASE}\${path}\`
1582
1959
 
@@ -1586,9 +1963,9 @@ export const hrefFor = (route: SectionRoute) => sectionHref(sectionPath(route))
1586
1963
  export const routeFor = (pathname: string) => parseSectionPath(pathname.slice(SECTION_BASE.length), SECTION_FEATURES)
1587
1964
  `;
1588
1965
  }
1589
- function viteSectionRoutes(hasMockup, t) {
1590
- return `${ROUTES_IMPORTS}${mockupModule(hasMockup, t)}
1591
- ${FEATURES}
1966
+ function viteSectionRoutes(hasMockup, screens, t) {
1967
+ return `${routesImports(screens)}${mockupModule(hasMockup, t)}
1968
+ ${features(screens)}
1592
1969
  /** A \`sectionPath()\` result as an href: the page's hash. */
1593
1970
  export const sectionHref = (path: string) => \`#\${path}\`
1594
1971
 
@@ -1762,13 +2139,14 @@ function SectionLayout({ children }: { children: ReactNode }) {
1762
2139
  SectionLayout.displayName = 'SectionLayout'
1763
2140
  `;
1764
2141
  }
1765
- function nextPage(t) {
2142
+ function nextPage(t, screens) {
1766
2143
  const c = t.componentsAlias;
1767
2144
  return `import { componentSlug, GALLERY_COMPONENTS } from '${c}/design-system/gallery-groups'
1768
2145
  import { NAV_ITEMS } from '${c}/design-system/section-nav'
1769
2146
  import { SectionPage } from '${c}/design-system/section-page'
1770
2147
  import { SECTION_FEATURES } from '${c}/design-system/section-routes'
1771
-
2148
+ ${screens ? `import { SECTION_SCREENS } from '${c}/design-system/section-screens'
2149
+ ` : ""}
1772
2150
  export const metadata = { title: 'Design system' }
1773
2151
 
1774
2152
  // Every route of the section is prerendered; anything else renders the section's own "not found" view.
@@ -1779,7 +2157,7 @@ export function generateStaticParams() {
1779
2157
  ...views,
1780
2158
  ...GALLERY_COMPONENTS.map((title) => \`components/\${componentSlug(title)}\`),
1781
2159
  ...SECTION_FEATURES.blockIds.map((id) => \`blocks/\${id}\`),
1782
- ]
2160
+ ${screens ? " ...SECTION_SCREENS.map((screen) => `screens/${screen.slug}`),\n" : ""} ]
1783
2161
  return routes.map((route) => ({ path: route === '' ? [] : route.split('/') }))
1784
2162
  }
1785
2163
 
@@ -1874,7 +2252,7 @@ function sectionPresent(root, t) {
1874
2252
  }
1875
2253
 
1876
2254
  // src/add/run-add.ts
1877
- import { existsSync as existsSync8, readFileSync as readFileSync8, statSync as statSync2 } from "node:fs";
2255
+ import { existsSync as existsSync9, readFileSync as readFileSync9, statSync as statSync2 } from "node:fs";
1878
2256
  import { join as join5 } from "node:path";
1879
2257
 
1880
2258
  // src/write.ts
@@ -2038,36 +2416,244 @@ async function requestJson(opts, fetchImpl = fetch) {
2038
2416
  }
2039
2417
  return { status: res.status, body };
2040
2418
  }
2419
+ var STREAM_TIMEOUT_MS = 3e5;
2420
+ var STREAM_LINE_MAX = 1024 * 1024;
2421
+ var isEvent = (v) => typeof v === "object" && v !== null && !Array.isArray(v) && typeof v.type === "string";
2422
+ async function postNdjson(opts, fetchImpl = fetch) {
2423
+ const url = new URL(opts.path, `${opts.api}/`);
2424
+ const controller = new AbortController();
2425
+ const timer = setTimeout(() => controller.abort(new DOMException("The operation timed out.", "TimeoutError")), opts.timeoutMs ?? STREAM_TIMEOUT_MS);
2426
+ try {
2427
+ let res;
2428
+ try {
2429
+ res = await fetchImpl(url.toString(), {
2430
+ method: "POST",
2431
+ headers: { Accept: "application/x-ndjson", "Content-Type": "application/json", Authorization: `Bearer ${opts.token}` },
2432
+ body: JSON.stringify(opts.body),
2433
+ signal: controller.signal
2434
+ });
2435
+ } catch {
2436
+ throw new ApiError(UNREACHABLE(opts.api), null);
2437
+ }
2438
+ if (!res.ok) {
2439
+ let body = null;
2440
+ try {
2441
+ body = await res.json();
2442
+ } catch {
2443
+ }
2444
+ return { kind: "refused", status: res.status, body };
2445
+ }
2446
+ if (!res.body) return { kind: "ended" };
2447
+ const reader = res.body.getReader();
2448
+ const decoder = new TextDecoder();
2449
+ let buffer = "";
2450
+ const take = (line) => {
2451
+ let event;
2452
+ try {
2453
+ event = JSON.parse(line);
2454
+ } catch {
2455
+ return null;
2456
+ }
2457
+ if (!isEvent(event)) return null;
2458
+ if (event.type === "result") return { kind: "result", data: event.data };
2459
+ if (event.type === "error") return { kind: "error", event };
2460
+ return null;
2461
+ };
2462
+ try {
2463
+ for (; ; ) {
2464
+ const { done, value } = await reader.read();
2465
+ buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });
2466
+ let nl;
2467
+ while ((nl = buffer.indexOf("\n")) !== -1) {
2468
+ if (nl > STREAM_LINE_MAX) break;
2469
+ const line = buffer.slice(0, nl).trim();
2470
+ buffer = buffer.slice(nl + 1);
2471
+ const outcome = line ? take(line) : null;
2472
+ if (outcome) {
2473
+ void reader.cancel().catch(() => {
2474
+ });
2475
+ return outcome;
2476
+ }
2477
+ }
2478
+ if (nl > STREAM_LINE_MAX || nl === -1 && buffer.length > STREAM_LINE_MAX) {
2479
+ void reader.cancel().catch(() => {
2480
+ });
2481
+ return { kind: "ended" };
2482
+ }
2483
+ if (done) return buffer.trim() && take(buffer.trim()) || { kind: "ended" };
2484
+ }
2485
+ } catch {
2486
+ return { kind: "ended" };
2487
+ }
2488
+ } finally {
2489
+ clearTimeout(timer);
2490
+ }
2491
+ }
2492
+
2493
+ // src/connect/open-browser.ts
2494
+ import { spawn as spawn2 } from "node:child_process";
2495
+ var launchDetached = (cmd, args) => new Promise((resolve8) => {
2496
+ try {
2497
+ const child = spawn2(cmd, args, {
2498
+ shell: false,
2499
+ stdio: "ignore",
2500
+ detached: true,
2501
+ windowsHide: true
2502
+ });
2503
+ child.once("error", () => resolve8(false));
2504
+ child.once("spawn", () => {
2505
+ child.unref();
2506
+ resolve8(true);
2507
+ });
2508
+ } catch {
2509
+ resolve8(false);
2510
+ }
2511
+ });
2512
+ function deviceUrl(api) {
2513
+ return new URL("/device", api).toString();
2514
+ }
2515
+ async function openBrowser(url, platform, launch = launchDetached) {
2516
+ let protocol;
2517
+ try {
2518
+ protocol = new URL(url).protocol;
2519
+ } catch {
2520
+ return false;
2521
+ }
2522
+ if (protocol !== "http:" && protocol !== "https:") return false;
2523
+ if (platform === "darwin") return launch("open", [url]);
2524
+ if (platform === "win32") return launch("rundll32", ["url.dll,FileProtocolHandler", url]);
2525
+ return launch("xdg-open", [url]);
2526
+ }
2527
+
2528
+ // src/connect/device-login.ts
2529
+ var DENIED_MESSAGE = "Sign-in was denied in the browser.";
2530
+ var EXPIRED_MESSAGE = "The code expired. Run npx designsource login again.";
2531
+ var UNEXPECTED = "Unexpected answer from the API. Run npx designsource login again.";
2532
+ var DEVICE_MAX_WAIT_MS = 6e5;
2533
+ var SLOW_DOWN_MS = 5e3;
2534
+ var DEFAULT_INTERVAL_MS = 5e3;
2535
+ var MIN_INTERVAL_MS = 1e3;
2536
+ var MAX_INTERVAL_MS = 6e4;
2537
+ var ACCOUNT_TOKEN = /^dsa_[A-Za-z0-9_-]{43}$/;
2538
+ var USER_CODE = /^[BCDFGHJKLMNPQRSTVWXZ23456789]{4}-[BCDFGHJKLMNPQRSTVWXZ23456789]{4}$/;
2539
+ var DEVICE_CODE = /^[A-Za-z0-9_-]{20,128}$/;
2540
+ var CLIENT_NAME_MAX = 60;
2541
+ var EMAIL_MAX = 254;
2542
+ function printable(text) {
2543
+ return text.replace(/[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u202a-\u202e\u2028\u2029\u2060-\u2069\ufeff]/g, "");
2544
+ }
2545
+ var NO_ACCOUNT_YET = "No account yet? Sign up on that page; it's free.";
2546
+ function clientName(hostname2) {
2547
+ const host = hostname2.replace(/[^A-Za-z0-9 '._-]/g, "-") || "this computer";
2548
+ return `designsource on ${host}`.slice(0, CLIENT_NAME_MAX).trimEnd();
2549
+ }
2550
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2551
+ var errorCode = (body) => isRecord(body) && typeof body.error === "string" ? body.error : null;
2552
+ function seconds(value, fallback, min, max) {
2553
+ const ms = typeof value === "number" && Number.isFinite(value) ? value * 1e3 : fallback;
2554
+ return Math.min(max, Math.max(min, ms));
2555
+ }
2556
+ async function deviceLogin(opts) {
2557
+ const { api, fetchImpl, sleep, now, show, open } = opts;
2558
+ const started = now();
2559
+ const code2 = await requestJson({ api, path: "/api/device/code", method: "POST", body: { clientName: opts.clientName } }, fetchImpl);
2560
+ if (code2.status === 429) throw new CliError("Too many sign-in attempts from this network. Wait a while and run npx designsource login again.");
2561
+ if (code2.status !== 200) throw new CliError(`${api} answered ${code2.status}.`);
2562
+ const body = code2.body;
2563
+ if (!isRecord(body) || typeof body.deviceCode !== "string" || !DEVICE_CODE.test(body.deviceCode) || typeof body.userCode !== "string" || !USER_CODE.test(body.userCode)) {
2564
+ throw new CliError(UNEXPECTED);
2565
+ }
2566
+ const deviceCode = body.deviceCode;
2567
+ let interval = seconds(body.interval, DEFAULT_INTERVAL_MS, MIN_INTERVAL_MS, MAX_INTERVAL_MS);
2568
+ const deadline = started + seconds(body.expiresIn, DEVICE_MAX_WAIT_MS, 0, DEVICE_MAX_WAIT_MS);
2569
+ const page = deviceUrl(api);
2570
+ show(`Open ${page} and enter ${body.userCode}`);
2571
+ show(NO_ACCOUNT_YET);
2572
+ await open(page);
2573
+ show("Waiting for you to approve it in the browser\u2026 (Ctrl+C to stop)");
2574
+ for (; ; ) {
2575
+ if (now() + interval > deadline) throw new CliError(EXPIRED_MESSAGE);
2576
+ await sleep(interval);
2577
+ const poll = await requestJson({ api, path: "/api/device/token", method: "POST", body: { deviceCode } }, fetchImpl);
2578
+ if (poll.status === 200) return accepted(poll.body);
2579
+ const error = poll.status === 400 ? errorCode(poll.body) : null;
2580
+ if (error === "authorization_pending") continue;
2581
+ if (error === "slow_down") {
2582
+ interval = Math.min(MAX_INTERVAL_MS, interval + SLOW_DOWN_MS);
2583
+ continue;
2584
+ }
2585
+ if (error === "access_denied") throw new CliError(DENIED_MESSAGE);
2586
+ if (error === "expired_token") throw new CliError(EXPIRED_MESSAGE);
2587
+ if (poll.status >= 500 || poll.status === 429) continue;
2588
+ throw new CliError(UNEXPECTED);
2589
+ }
2590
+ }
2591
+ function accepted(body) {
2592
+ if (!isRecord(body) || typeof body.accessToken !== "string" || !ACCOUNT_TOKEN.test(body.accessToken)) throw new CliError("Unexpected account token from the API.");
2593
+ const account = body.account;
2594
+ if (!isRecord(account) || typeof account.email !== "string") throw new CliError(UNEXPECTED);
2595
+ const email = printable(account.email).slice(0, EMAIL_MAX);
2596
+ if (email === "") throw new CliError(UNEXPECTED);
2597
+ return { token: body.accessToken, email };
2598
+ }
2041
2599
 
2042
2600
  // src/add/kit-manifest.ts
2043
2601
  var malformed = () => new CliError("Unexpected response from the API \u2014 not a kit manifest.");
2044
- var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2602
+ var isRecord2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2045
2603
  var isStrings = (v) => Array.isArray(v) && v.every((s) => typeof s === "string");
2046
- var isStringMap = (v) => isRecord(v) && Object.values(v).every((s) => typeof s === "string");
2047
- var isSectionFile = (f) => isRecord(f) && typeof f.key === "string" && typeof f.contents === "string" && isStrings(f.kitImports) && isStrings(f.packages) && typeof f.block === "boolean";
2048
- var isBlockGroup = (g) => isRecord(g) && typeof g.family === "string" && typeof g.label === "string" && Array.isArray(g.blocks) && g.blocks.every((b) => isRecord(b) && typeof b.id === "string" && typeof b.title === "string");
2604
+ var isStringMap = (v) => isRecord2(v) && Object.values(v).every((s) => typeof s === "string");
2605
+ var isSectionFile = (f) => isRecord2(f) && typeof f.key === "string" && typeof f.contents === "string" && isStrings(f.kitImports) && isStrings(f.packages) && typeof f.block === "boolean";
2606
+ var isBlockGroup = (g) => isRecord2(g) && typeof g.family === "string" && typeof g.label === "string" && Array.isArray(g.blocks) && g.blocks.every((b) => isRecord2(b) && typeof b.id === "string" && typeof b.title === "string");
2049
2607
  function validateSection(s) {
2050
- if (!isRecord(s) || !Array.isArray(s.files) || !s.files.every(isSectionFile)) throw malformed();
2608
+ if (!isRecord2(s) || !Array.isArray(s.files) || !s.files.every(isSectionFile)) throw malformed();
2051
2609
  if (typeof s.themeCss !== "string" || !Array.isArray(s.blockGroups) || !s.blockGroups.every(isBlockGroup)) throw malformed();
2052
2610
  if (!isStringMap(s.packages) || !isStringMap(s.blockPackages)) throw malformed();
2053
2611
  return { files: s.files, themeCss: s.themeCss, blockGroups: s.blockGroups, packages: s.packages, blockPackages: s.blockPackages, mockupSpec: s.mockupSpec ?? null };
2054
2612
  }
2613
+ var isScreen = (s) => {
2614
+ if (!isRecord2(s) || typeof s.slug !== "string" || !SCREEN_SLUG.test(s.slug) || typeof s.title !== "string") return false;
2615
+ if (typeof s.component !== "string" || !SCREEN_COMPONENT.test(s.component) || !isStrings(s.parts)) return false;
2616
+ if (!Array.isArray(s.files) || s.files.length !== 2) return false;
2617
+ if (!s.files.every((f) => isRecord2(f) && typeof f.file === "string" && typeof f.contents === "string")) return false;
2618
+ return s.files[0].file === `${s.slug}.tsx` && s.files[1].file === `${s.slug}.data.ts`;
2619
+ };
2620
+ var isScreenPart = (p) => isRecord2(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);
2621
+ var isScreenEntry = (e) => isRecord2(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) || isPageKind(e.kind))) && (e.action === void 0 || typeof e.action === "string" && e.action.length <= 60 && printable(e.action) === e.action);
2055
2622
  function validateKitManifest(json) {
2056
- if (!isRecord(json)) throw malformed();
2623
+ if (!isRecord2(json)) throw malformed();
2057
2624
  if (typeof json.version !== "number") throw malformed();
2058
2625
  if (json.version !== 1) throw new CliError(UPDATE_MESSAGE);
2059
2626
  if (json.kind !== "kit" || typeof json.name !== "string" || typeof json.utils !== "string") throw malformed();
2060
2627
  const { theme } = json;
2061
- if (!isRecord(theme) || typeof theme.css !== "string" || !isStrings(theme.fontImports)) throw malformed();
2628
+ if (!isRecord2(theme) || typeof theme.css !== "string" || !isStrings(theme.fontImports)) throw malformed();
2062
2629
  if (!Array.isArray(json.components)) throw malformed();
2063
2630
  for (const c of json.components) {
2064
- if (!isRecord(c)) throw malformed();
2631
+ if (!isRecord2(c)) throw malformed();
2065
2632
  if (typeof c.name !== "string" || typeof c.file !== "string" || typeof c.contents !== "string") throw malformed();
2066
2633
  if (!isStrings(c.kitImports) || !isStrings(c.packages)) throw malformed();
2067
2634
  }
2068
2635
  if (!isStrings(json.utilsPackages)) throw malformed();
2069
2636
  if (!isStringMap(json.packages) || !isStringMap(json.devPackages)) throw malformed();
2070
2637
  const section = json.section === void 0 ? void 0 : validateSection(json.section);
2638
+ const { screens, screenParts, screenIndex } = json;
2639
+ if (screens !== void 0 && !(Array.isArray(screens) && screens.every(isScreen))) throw malformed();
2640
+ if (screenParts !== void 0 && !(Array.isArray(screenParts) && screenParts.every(isScreenPart))) throw malformed();
2641
+ if (screenIndex !== void 0 && !(Array.isArray(screenIndex) && screenIndex.every(isScreenEntry))) throw malformed();
2642
+ if (screens !== void 0) {
2643
+ const slugs = /* @__PURE__ */ new Set();
2644
+ for (const s of screens) {
2645
+ if (RESERVED_SCREEN_SLUGS.includes(s.slug) || slugs.has(s.slug)) throw malformed();
2646
+ slugs.add(s.slug);
2647
+ }
2648
+ }
2649
+ if (screenParts !== void 0) {
2650
+ const names = /* @__PURE__ */ new Set();
2651
+ for (const p of screenParts) {
2652
+ if (names.has(p.name)) throw malformed();
2653
+ names.add(p.name);
2654
+ }
2655
+ for (const s of screens ?? []) if (s.parts.some((n) => !names.has(n))) throw malformed();
2656
+ } else if ((screens ?? []).some((s) => s.parts.length > 0)) throw malformed();
2071
2657
  return {
2072
2658
  version: 1,
2073
2659
  kind: "kit",
@@ -2078,13 +2664,19 @@ function validateKitManifest(json) {
2078
2664
  utilsPackages: json.utilsPackages,
2079
2665
  packages: json.packages,
2080
2666
  devPackages: json.devPackages,
2081
- ...section ? { section } : {}
2667
+ ...section ? { section } : {},
2668
+ ...screens !== void 0 ? { screens } : {},
2669
+ ...screenParts !== void 0 ? { screenParts } : {},
2670
+ ...screenIndex !== void 0 ? { screenIndex: screenIndex.map((e) => ({ slug: e.slug, title: e.title, available: e.available, kind: e.kind ?? "list", ...typeof e.action === "string" ? { action: e.action } : {} })) } : {}
2082
2671
  };
2083
2672
  }
2084
2673
 
2085
2674
  // src/add/fetch-kit.ts
2086
2675
  async function fetchKit(opts, fetchImpl = fetch) {
2087
- const { api, token, path = "/api/kit", messages } = opts;
2676
+ const { api, token, screens, messages } = opts;
2677
+ const asAll = screens === "all" || Array.isArray(screens) && (screens.includes("all") || new Set(screens).size > SCREENS_QUERY_MAX);
2678
+ const query = screens === void 0 || Array.isArray(screens) && screens.length === 0 ? "" : `?screens=${encodeURIComponent(asAll ? "all" : screens.join(","))}`;
2679
+ const path = `${opts.path ?? "/api/kit"}${query}${query === "" ? "?" : "&"}pages=1`;
2088
2680
  return validateKitManifest(await getJson({ api, token, path, ...messages ? { messages } : {} }, fetchImpl));
2089
2681
  }
2090
2682
 
@@ -2150,6 +2742,196 @@ function planPackages(components, manifest, appDeps, extra = {}) {
2150
2742
  return { install, conflicts: [...conflictOf.values()], skipped, components: kept, extraConflicts };
2151
2743
  }
2152
2744
 
2745
+ // src/add/screens.ts
2746
+ import { existsSync as existsSync8, readdirSync as readdirSync4, readFileSync as readFileSync8 } from "node:fs";
2747
+ 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.`;
2748
+ 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.`;
2749
+ 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.`;
2750
+ 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.`;
2751
+ 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.`;
2752
+ var SITE_PART_EDITED = (part) => `Skipped the site menu: you edited screens/parts/${part} and the kit's version has changed since. Run again with --force to replace it.`;
2753
+ var SITE_PART_EDITED_FOR_AGENT = (part) => `Skipped the site menu: 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.`;
2754
+ var SHELL_FILE = "app-shell.tsx";
2755
+ var SHELL_STAMP = "screen:shell";
2756
+ var SITE_FILE = "site-shell.tsx";
2757
+ var SITE_STAMP = "screen:site";
2758
+ var SITE_PART_NAMES = ["site-frame", "site-links"];
2759
+ function stampAt(root, path) {
2760
+ const abs = resolveInside(root, path);
2761
+ if (!existsSync8(abs)) return null;
2762
+ try {
2763
+ return readStamp(readFileSync8(abs, "utf8"));
2764
+ } catch {
2765
+ return null;
2766
+ }
2767
+ }
2768
+ var stampsIn = (root, dir, ext) => {
2769
+ let names;
2770
+ try {
2771
+ names = readdirSync4(resolveInside(root, dir), { withFileTypes: true }).filter((e) => e.isFile() && ext.test(e.name)).map((e) => e.name).sort();
2772
+ } catch {
2773
+ return [];
2774
+ }
2775
+ const found = [];
2776
+ for (const n of names) {
2777
+ const path = `${dir}/${n}`;
2778
+ let text;
2779
+ try {
2780
+ text = readFileSync8(resolveInside(root, path), "utf8");
2781
+ } catch {
2782
+ continue;
2783
+ }
2784
+ const stamp2 = readStamp(text);
2785
+ if (stamp2) found.push({ path, ...stamp2 });
2786
+ }
2787
+ return found;
2788
+ };
2789
+ function screensOnDisk(root, t) {
2790
+ const out = { slugs: [], parts: /* @__PURE__ */ new Map(), shell: false, site: false };
2791
+ if (t.componentsDir === null) return out;
2792
+ const dir = `${t.componentsDir}/screens`;
2793
+ for (const s of stampsIn(root, dir, /\.tsx$/)) {
2794
+ if (s.name === SHELL_STAMP) out.shell ||= s.path === `${dir}/${SHELL_FILE}`;
2795
+ else if (s.name === SITE_STAMP) out.site ||= s.path === `${dir}/${SITE_FILE}`;
2796
+ else if (s.name.startsWith("screen:") && !s.name.endsWith(".data")) out.slugs.push(s.name.slice("screen:".length));
2797
+ }
2798
+ for (const p of stampsIn(root, `${dir}/parts`, /\.tsx?$/)) {
2799
+ if (p.name.startsWith("screen-part:")) out.parts.set(p.name.slice("screen-part:".length), { path: p.path, hash: p.hash, edited: p.edited });
2800
+ }
2801
+ return out;
2802
+ }
2803
+ function closureOf(names, byName) {
2804
+ const seen = /* @__PURE__ */ new Map();
2805
+ const visit = (name) => {
2806
+ if (seen.has(name)) return;
2807
+ const part = byName.get(name);
2808
+ if (!part) throw new CliError("Unexpected response from the API \u2014 not a kit manifest.");
2809
+ seen.set(name, part);
2810
+ for (const n of part.partImports) visit(n);
2811
+ };
2812
+ names.forEach(visit);
2813
+ return [...seen.values()];
2814
+ }
2815
+ function sitePartsOf(manifest) {
2816
+ const byName = new Map((manifest.screenParts ?? []).map((p) => [p.name, p]));
2817
+ return byName.has("site-frame") ? closureOf(SITE_PART_NAMES.filter((n) => byName.has(n)), byName) : [];
2818
+ }
2819
+ function screenPartsOf(screen, manifest) {
2820
+ return closureOf(screen.parts, new Map((manifest.screenParts ?? []).map((p) => [p.name, p])));
2821
+ }
2822
+ function planScreenFiles(a) {
2823
+ const { root, targets: t, manifest, wanted, force = false } = a;
2824
+ if (t.componentsDir === null) throw new CliError(SCREENS_NEED_COMPONENTS_DIR(t.componentsAlias));
2825
+ const dir = `${t.componentsDir}/screens`;
2826
+ const byName = new Map((manifest.screenParts ?? []).map((p) => [p.name, p]));
2827
+ const disk = screensOnDisk(root, t);
2828
+ const plan = { write: [], edited: [], foreign: [], skipped: [], gone: [], kitComponents: [], added: [], siteParts: [], siteSkipped: null };
2829
+ const rewritten = (p) => rewriteForApp(p.contents, t);
2830
+ const editedAndChanged = (p) => {
2831
+ const on = disk.parts.get(p.name);
2832
+ return on !== void 0 && on.edited && on.hash !== hashOf(rewritten(p));
2833
+ };
2834
+ const written = [];
2835
+ const kindOf = new Map((manifest.screenIndex ?? []).map((e) => [e.slug, e.kind]));
2836
+ for (const screen of (manifest.screens ?? []).filter((s) => wanted.includes(s.slug))) {
2837
+ const page = isPageKind(kindOf.get(screen.slug) ?? "");
2838
+ const withFrame = page && byName.has("site-frame");
2839
+ const parts = closureOf(withFrame ? [...screen.parts, "site-frame"] : screen.parts, byName);
2840
+ const blocker = force ? void 0 : parts.find(editedAndChanged);
2841
+ if (blocker) {
2842
+ plan.skipped.push({ slug: screen.slug, reason: SCREEN_PART_EDITED(screen.slug, blocker.file), agentReason: SCREEN_PART_EDITED_FOR_AGENT(screen.slug, blocker.file) });
2843
+ continue;
2844
+ }
2845
+ const files = screen.files.map((f) => {
2846
+ const path = `${dir}/${f.file}`;
2847
+ const stamp2 = stampAt(root, path);
2848
+ const kitChanged = stamp2 !== null && stamp2.hash !== hashOf(rewriteForApp(f.contents, t));
2849
+ return { ...f, path, edited: stamp2?.edited ?? false, kitChanged, current: stamp2 !== null && !stamp2.edited && !kitChanged };
2850
+ });
2851
+ const [a2, b] = files;
2852
+ const pairBlocker = force ? void 0 : a2.edited && b.kitChanged ? a2 : b.edited && a2.kitChanged ? b : void 0;
2853
+ if (pairBlocker) {
2854
+ plan.skipped.push({ slug: screen.slug, reason: SCREEN_PAIR_EDITED(screen.slug, pairBlocker.path), agentReason: SCREEN_PAIR_EDITED_FOR_AGENT(screen.slug, pairBlocker.path) });
2855
+ continue;
2856
+ }
2857
+ const kept = force ? files : files.filter((f, i) => !(f.current && files[1 - i].edited));
2858
+ written.push({ slug: screen.slug, component: screen.component, page, parts, files: kept });
2859
+ }
2860
+ const push = (path, name, contents, component, screen) => {
2861
+ const abs = resolveInside(root, path);
2862
+ plan.write.push({ path, contents: stampContents(name, rewriteForApp(contents, t)), component, ...screen !== void 0 ? { screen } : {} });
2863
+ const status = existingFileStatus(abs);
2864
+ if (status === "foreign") plan.foreign.push(path);
2865
+ else if (status === "edited") plan.edited.push(path);
2866
+ };
2867
+ const partsDone = /* @__PURE__ */ new Set();
2868
+ const pushPart = (p) => {
2869
+ if (partsDone.has(p.name)) return;
2870
+ partsDone.add(p.name);
2871
+ const on = disk.parts.get(p.name);
2872
+ if (force || !(on && on.edited)) push(`${dir}/parts/${p.file}`, `screen-part:${p.name}`, p.contents, p.name);
2873
+ };
2874
+ for (const s of written) {
2875
+ for (const f of s.files) {
2876
+ const name = f.file.endsWith(".data.ts") ? `screen:${s.slug}.data` : `screen:${s.slug}`;
2877
+ push(`${dir}/${f.file}`, name, f.contents, s.slug, s.slug);
2878
+ }
2879
+ plan.added.push({ slug: s.slug, component: s.component, importPath: `${t.componentsAlias}/screens/${s.slug}`, ...s.page ? { page: true } : {} });
2880
+ s.parts.forEach(pushPart);
2881
+ }
2882
+ if (a.site) {
2883
+ const parts = sitePartsOf(manifest);
2884
+ const blocker = force ? void 0 : parts.find(editedAndChanged);
2885
+ if (blocker) plan.siteSkipped = { reason: SITE_PART_EDITED(blocker.file), agentReason: SITE_PART_EDITED_FOR_AGENT(blocker.file) };
2886
+ else {
2887
+ plan.siteParts = parts;
2888
+ parts.forEach(pushPart);
2889
+ }
2890
+ }
2891
+ const kitComponents = /* @__PURE__ */ new Set();
2892
+ for (const p of [...written.flatMap((s) => s.parts), ...plan.siteParts]) for (const k of p.kitImports) kitComponents.add(k);
2893
+ plan.kitComponents = [...kitComponents].sort();
2894
+ const inIndex = new Set((manifest.screenIndex ?? []).map((e) => e.slug));
2895
+ plan.gone = manifest.screenIndex === void 0 ? [] : disk.slugs.filter((s) => !inIndex.has(s));
2896
+ return plan;
2897
+ }
2898
+ function shellScreensFor(slugs, index) {
2899
+ const bySlug = new Map((index ?? []).map((e) => [e.slug, e]));
2900
+ const valid = [...new Set(slugs)].filter((s) => SCREEN_SLUG.test(s) && !RESERVED_SCREEN_SLUGS.includes(s));
2901
+ return valid.sort((a, b) => a < b ? -1 : a > b ? 1 : 0).map((slug) => {
2902
+ const e = bySlug.get(slug);
2903
+ return e ? { slug, title: e.title, kind: e.kind } : { slug, title: slug, kind: "list" };
2904
+ });
2905
+ }
2906
+ function planShellFile(a) {
2907
+ const { targets: t } = a;
2908
+ if (t.componentsDir === null) throw new CliError(SCREENS_NEED_COMPONENTS_DIR(t.componentsAlias));
2909
+ const path = `${t.componentsDir}/screens/${SHELL_FILE}`;
2910
+ const contents = stampContents(SHELL_STAMP, rewriteForApp(assembleAppShell({ name: a.name, screens: a.screens, hrefFor: "root" }), t));
2911
+ return { path, contents, status: existingFileStatus(resolveInside(a.root, path)), importPath: `${t.componentsAlias}/screens/app-shell` };
2912
+ }
2913
+ function sitePagesFor(slugs, index) {
2914
+ const bySlug = new Map((index ?? []).map((e) => [e.slug, e]));
2915
+ const kinds = /* @__PURE__ */ new Set();
2916
+ const pages = [];
2917
+ const valid = [...new Set(slugs)].filter((s) => SCREEN_SLUG.test(s) && !RESERVED_SCREEN_SLUGS.includes(s));
2918
+ for (const slug of valid.sort((a, b) => a < b ? -1 : a > b ? 1 : 0)) {
2919
+ const e = bySlug.get(slug);
2920
+ if (!e || !isPageKind(e.kind) || kinds.has(e.kind)) continue;
2921
+ kinds.add(e.kind);
2922
+ pages.push({ slug, title: e.title, kind: e.kind });
2923
+ }
2924
+ return pages;
2925
+ }
2926
+ function planSiteFile(a) {
2927
+ const { targets: t } = a;
2928
+ if (t.componentsDir === null) throw new CliError(SCREENS_NEED_COMPONENTS_DIR(t.componentsAlias));
2929
+ const path = `${t.componentsDir}/screens/${SITE_FILE}`;
2930
+ const source = assembleSiteShell({ name: a.name, pages: a.pages, year: a.year, ...a.action !== void 0 ? { fallbackActionLabel: a.action } : {} });
2931
+ const contents = stampContents(SITE_STAMP, rewriteForApp(source, t));
2932
+ return { path, contents, status: existingFileStatus(resolveInside(a.root, path)), importPath: `${t.componentsAlias}/screens/site-shell` };
2933
+ }
2934
+
2153
2935
  // src/add/css-blocks.ts
2154
2936
  var isSpace = (c) => c === " " || c === " " || c === "\n" || c === "\r" || c === "\f";
2155
2937
  function commentEnd(css, at) {
@@ -2490,6 +3272,37 @@ var REPLACE_DECLINED = "Nothing was changed. Run again and answer yes to replace
2490
3272
  var REPLACE_NEEDS_FORCE = (paths) => `These files exist and were not added by designsource: ${paths.join(", ")}. Pass --force to replace them.`;
2491
3273
  var UNKNOWN_COMPONENTS = (names) => `Unknown component(s): ${names.join(", ")}. Run without names to pick from the list.`;
2492
3274
  var SECTION_CONFLICT = (reason) => `Skipped the /design-system section: ${reason}.`;
3275
+ var SCREEN_UNAVAILABLE = "This screen's current version can't be built. Pick another version in DS source.";
3276
+ var SCREENS_NOT_SERVED = "This DS source server does not send screens yet. Try again later, or run add without --screen.";
3277
+ var SHELL_EMPTY = "The app shell lists no screens yet: each one you add with designsource add --screen joins its menu.";
3278
+ 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.";
3279
+ var SHELL_COMPONENTS = ["sidebar", "icons"];
3280
+ var SHELL_SKIPPED = (reason) => `Skipped the app shell: ${reason}.`;
3281
+ var SITE_SKIPPED = (reason) => `Skipped the site menu: ${reason}.`;
3282
+ var SHELL_NOT_IN_KIT = (name) => `the kit from this DS source server has no ${name}`;
3283
+ var NO_SCREENS_YET = (project) => `${printable(project)} has no screens yet. Make one in the Screens view of the workbench.`;
3284
+ var NO_PAGES_YET = (project) => `${printable(project)} has no pages yet. Make one with Ask AI on the Screens view in DS source, then run this again.`;
3285
+ var NO_PAGES_PULLED = (project, page) => `None of ${printable(project)}'s pages is in this app yet, and the site menu links only the pages here. ${page === null ? "None of them can be built now: pick another version of one in DS source, then run this again." : `Pull a page with it: npx designsource add --screen ${printable(page)},site`}`;
3286
+ var PAGE_SKIPPED_NO_SITE = (skipLine) => `${skipLine} The site menu links only the pages in this app, so it was not written either.`;
3287
+ var screenSkipText = (slug, reason) => reason.startsWith("Skipped screen ") ? reason : `Skipped screen "${slug}": ${reason}`;
3288
+ var NoPagesPulledError = class extends CliError {
3289
+ constructor(project, page, skip) {
3290
+ super(skip ? PAGE_SKIPPED_NO_SITE(screenSkipText(skip.slug, skip.reason)) : NO_PAGES_PULLED(project, page));
3291
+ this.project = project;
3292
+ this.page = page;
3293
+ this.skip = skip;
3294
+ }
3295
+ project;
3296
+ page;
3297
+ skip;
3298
+ };
3299
+ var UNKNOWN_SCREENS_SHOWN = 10;
3300
+ var UNKNOWN_SCREENS = (names, index, project) => {
3301
+ const head = `No screen${names.length === 1 ? "" : "s"} named ${names.map((n) => `"${printable(n)}"`).join(", ")} in ${printable(project)}.`;
3302
+ if (index.length === 0) return `${head} It has no screens yet.`;
3303
+ const shown = index.slice(0, UNKNOWN_SCREENS_SHOWN).map((e) => `${e.slug} (${printable(e.title)})`);
3304
+ return `${head} Its screens: ${[...shown, ...index.length > UNKNOWN_SCREENS_SHOWN ? ["\u2026"] : []].join(", ")}.`;
3305
+ };
2493
3306
  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
3307
  var INSTALL_FAILED = (command) => `Installing libraries failed. The files were written; run this to finish: ${command}`;
2495
3308
  var UnknownComponentsError = class extends CliError {
@@ -2522,7 +3335,7 @@ function defaultTargets(root, info) {
2522
3335
  const cssFile = findGlobalStylesheet(info);
2523
3336
  if (readPaths(root)?.paths["@/*"]) return resolveTargets(root, { tailwind: { css: cssFile }, aliases: ALIASES });
2524
3337
  const src = join5(root, "src");
2525
- const prefix = existsSync8(src) && statSync2(src).isDirectory() ? "src/" : "";
3338
+ const prefix = existsSync9(src) && statSync2(src).isDirectory() ? "src/" : "";
2526
3339
  const utilsFile = `${prefix}lib/utils.ts`;
2527
3340
  return {
2528
3341
  uiDir: `${prefix}components/ui`,
@@ -2541,7 +3354,7 @@ function assertSameTargets(planned, actual) {
2541
3354
  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
3355
  }
2543
3356
  }
2544
- async function chooseComponents(input, manifest, before, sectionOnDisk, questions) {
3357
+ async function chooseComponents(input, manifest, before, sectionOnDisk, questions, screens) {
2545
3358
  const known = new Set(manifest.components.map((c) => c.name));
2546
3359
  const offered = manifest.components.map((c) => c.name).filter((n) => n !== PORTAL);
2547
3360
  const checked = (names) => {
@@ -2549,11 +3362,68 @@ async function chooseComponents(input, manifest, before, sectionOnDisk, question
2549
3362
  if (unknown.length > 0) throw new UnknownComponentsError(unknown);
2550
3363
  return [...new Set(names)];
2551
3364
  };
2552
- if (input.components.length > 0) return checked(input.components);
2553
- if (input.all || sectionOnDisk) return offered;
3365
+ const withScreens = (names) => [.../* @__PURE__ */ new Set([...names, ...screens.components.filter((n) => known.has(n))])];
2554
3366
  const earlier = before.filter((n) => known.has(n));
2555
- if (earlier.length > 0) return earlier;
2556
- return checked(await questions.pickComponents(offered));
3367
+ if (input.components.length > 0) return withScreens(checked(input.components));
3368
+ if (input.all || sectionOnDisk) return offered;
3369
+ if (screens.only || earlier.length > 0) return withScreens(earlier);
3370
+ return withScreens(checked(await questions.pickComponents(offered)));
3371
+ }
3372
+ function screensQuery(input, disk) {
3373
+ if (input.screens !== void 0) return input.screens === "all" || input.screens.length > 0 ? input.screens : void 0;
3374
+ if (!input.shell && !input.site && (!input.refreshScreens || input.components.length > 0)) return void 0;
3375
+ const slugs = disk.slugs.filter((s) => SCREEN_SLUG.test(s) && !RESERVED_SCREEN_SLUGS.includes(s));
3376
+ if (slugs.length > 0) return slugs;
3377
+ return input.site ? "all" : void 0;
3378
+ }
3379
+ function screenConflict(slug, manifest, appDeps) {
3380
+ const screen = manifest.screens?.find((s) => s.slug === slug);
3381
+ return screen ? partsConflict(screenPartsOf(screen, manifest), manifest, appDeps) : null;
3382
+ }
3383
+ function partsConflict(parts, manifest, appDeps) {
3384
+ const byName = new Map(manifest.components.map((c) => [c.name, c]));
3385
+ const components = componentClosure(parts.flatMap((p) => p.kitImports).filter((n) => byName.has(n)), manifest);
3386
+ for (const pkg of [...parts.flatMap((p) => p.packages), ...components.flatMap((n) => byName.get(n)?.packages ?? [])]) {
3387
+ const have = appDeps[pkg];
3388
+ const need = manifest.packages[pkg];
3389
+ if (have === void 0 || need === void 0) continue;
3390
+ const conflict = conflictBetween(pkg, have, need);
3391
+ if (conflict) return reasonFor(conflict);
3392
+ }
3393
+ return null;
3394
+ }
3395
+ function screenInstalls(slugs, manifest, appDeps) {
3396
+ const screens = (manifest.screens ?? []).filter((s) => slugs.includes(s.slug));
3397
+ return partInstalls(screens.flatMap((s) => screenPartsOf(s, manifest)), manifest, appDeps);
3398
+ }
3399
+ function partInstalls(parts, manifest, appDeps) {
3400
+ const install = {};
3401
+ for (const pkg of parts.flatMap((p) => p.packages)) {
3402
+ const need = manifest.packages[pkg];
3403
+ if (need !== void 0 && appDeps[pkg] === void 0) install[pkg] = need;
3404
+ }
3405
+ return install;
3406
+ }
3407
+ function selectScreens(query, explicit, manifest, appDeps) {
3408
+ const index = manifest.screenIndex;
3409
+ if (index === void 0) {
3410
+ if (explicit) throw new CliError(SCREENS_NOT_SERVED);
3411
+ return { wanted: [], skipped: [] };
3412
+ }
3413
+ const bySlug = new Map(index.map((e) => [e.slug, e]));
3414
+ if (explicit && query === "all" && index.length === 0) throw new CliError(NO_SCREENS_YET(manifest.name));
3415
+ if (explicit && query !== "all") {
3416
+ const unknown = query.filter((n) => !bySlug.has(n));
3417
+ if (unknown.length > 0) throw new CliError(UNKNOWN_SCREENS(unknown, index, manifest.name));
3418
+ }
3419
+ const asked = query === "all" ? index.map((e) => e.slug) : [...new Set(query)].filter((n) => bySlug.has(n));
3420
+ const selection = { wanted: [], skipped: [] };
3421
+ for (const slug of asked) {
3422
+ const reason = bySlug.get(slug).available ? screenConflict(slug, manifest, appDeps) : SCREEN_UNAVAILABLE;
3423
+ if (reason) selection.skipped.push({ slug, reason });
3424
+ else selection.wanted.push(slug);
3425
+ }
3426
+ return selection;
2557
3427
  }
2558
3428
  var SECTION_FRAMEWORKS = ["next", "vite"];
2559
3429
  function sectionDecision(input) {
@@ -2565,7 +3435,7 @@ function sectionDecision(input) {
2565
3435
  const blocks = !input.present ? input.blocksWanted ? "write" : "skip" : input.blocksOnDisk ? input.blocksWanted ? "write" : "keep" : "skip";
2566
3436
  return { write: true, blocks, note: null };
2567
3437
  }
2568
- function planSection(root, input, info, t, manifest, chosen, onDisk) {
3438
+ function planSection(root, input, info, t, manifest, chosen, onDisk, screens) {
2569
3439
  const none = (note) => ({ decision: { write: false, blocks: "skip", note }, files: () => [], paths: [], packages: {}, blockCount: 0 });
2570
3440
  const section = manifest.section;
2571
3441
  if (!section) return none(null);
@@ -2579,8 +3449,9 @@ function planSection(root, input, info, t, manifest, chosen, onDisk) {
2579
3449
  if (t.componentsDir === null) return none(NO_COMPONENTS_DIR(t.componentsAlias));
2580
3450
  if (!t.libAlias) return none(NO_LIB_ALIAS(t.utilsAlias));
2581
3451
  const framework = info.framework === "vite" ? "vite" : "next";
2582
- const srcDir = existsSync8(join5(root, "src")) ? "src" : "";
2583
- const files = (darkMarker) => planSectionFiles({ framework, appDir, srcDir, targets: t, manifest, blocks: decision.blocks, keptBlockIds: blockIds, darkMarker });
3452
+ const srcDir = existsSync9(join5(root, "src")) ? "src" : "";
3453
+ const registryOnDisk = existsSync9(resolveInside(root, registryPath(t.componentsDir)));
3454
+ const files = (darkMarker) => planSectionFiles({ framework, appDir, srcDir, targets: t, manifest, blocks: decision.blocks, keptBlockIds: blockIds, darkMarker, screens, registryOnDisk });
2584
3455
  return {
2585
3456
  decision,
2586
3457
  files,
@@ -2611,14 +3482,48 @@ async function runAdd(input, deps) {
2611
3482
  assertCanAdd(info);
2612
3483
  const planned = info.shadcn ? resolveTargets(root, info.shadcn) : defaultTargets(root, info);
2613
3484
  const cssAbs = resolveInside(root, planned.cssFile);
2614
- if (!existsSync8(cssAbs)) throw new CliError(NO_THEME_FILE(planned.cssFile));
3485
+ if (!existsSync9(cssAbs)) throw new CliError(NO_THEME_FILE(planned.cssFile));
2615
3486
  assertKitUtils(root, info, planned);
2616
- const manifest = await fetchKit({ api: input.api, token: input.token, path: input.kitPath, messages: input.messages }, deps.fetchImpl);
3487
+ const disk = screensOnDisk(root, planned);
3488
+ const query = screensQuery(input, disk);
3489
+ const manifest = await fetchKit({ api: input.api, token: input.token, path: input.kitPath, messages: input.messages, screens: query }, deps.fetchImpl);
3490
+ const indexOnly = (input.shell === true || input.site === true) && input.screens === void 0;
3491
+ if (input.site) {
3492
+ if (manifest.screenIndex === void 0) throw new CliError(SCREENS_NOT_SERVED);
3493
+ if (!manifest.screenIndex.some((e) => isPageKind(e.kind))) throw new CliError(NO_PAGES_YET(manifest.name));
3494
+ }
3495
+ const screenSelection = query === void 0 ? null : indexOnly ? { wanted: [], skipped: [] } : selectScreens(query, input.screens !== void 0, manifest, info.deps);
3496
+ const fetchedScreens = query !== void 0 && manifest.screenIndex !== void 0;
3497
+ const siteWanted = input.site === true || disk.site && fetchedScreens;
3498
+ const siteConflict = siteWanted ? partsConflict(sitePartsOf(manifest), manifest, info.deps) : null;
3499
+ const screenPlan = screenSelection === null ? null : planScreenFiles({ root, targets: planned, manifest, wanted: screenSelection.wanted, force: input.force, site: siteWanted && siteConflict === null });
3500
+ const slugsAfter = [...disk.slugs, ...(screenPlan?.added ?? []).map((a) => a.slug)];
3501
+ const screensAfter = shellScreensFor(slugsAfter, manifest.screenIndex);
3502
+ const sitePages = sitePagesFor(slugsAfter, manifest.screenIndex);
3503
+ if (input.site && sitePages.length === 0) {
3504
+ const pageSlugs = new Set(manifest.screenIndex.filter((e) => isPageKind(e.kind)).map((e) => e.slug));
3505
+ const namedSkip = [...screenSelection?.skipped ?? [], ...screenPlan?.skipped ?? []].find((k) => pageSlugs.has(k.slug)) ?? null;
3506
+ const first = manifest.screenIndex.find((e) => isPageKind(e.kind) && e.available);
3507
+ throw new NoPagesPulledError(manifest.name, first?.slug ?? null, namedSkip);
3508
+ }
3509
+ const bareRerun = input.refreshScreens === true && input.components.length === 0 && input.screens === void 0 && !input.shell && !input.site;
3510
+ const noScreensLeft = bareRerun && screensAfter.length === 0;
3511
+ const listScreens2 = fetchedScreens || noScreensLeft;
3512
+ const writeShell = input.shell === true || disk.shell && listScreens2;
3513
+ const shellPlan = writeShell ? planShellFile({ root, targets: planned, name: manifest.name, screens: screensAfter }) : null;
3514
+ const siteSkipped = siteConflict !== null ? { reason: SITE_SKIPPED(siteConflict) } : screenPlan?.siteSkipped ?? null;
3515
+ const writeSite = (input.site === true || disk.site && listScreens2) && siteSkipped === null;
3516
+ const siteListed = noScreensLeft ? [] : sitePages;
3517
+ const sitePlan = writeSite ? planSiteFile({ root, targets: planned, pages: siteListed, ...registrySite(manifest) }) : null;
2617
3518
  const onDisk = sectionPresent(root, planned);
2618
- const chosen = await chooseComponents(input, manifest, previouslyAdded(root, planned), onDisk.present, deps.questions);
2619
- const section = planSection(root, input, info, planned, manifest, chosen, onDisk);
3519
+ const screensOnly = (input.screens !== void 0 || input.shell === true || input.site === true) && input.components.length === 0 && !input.all && !onDisk.present;
3520
+ const chosen = await chooseComponents(input, manifest, previouslyAdded(root, planned), onDisk.present, deps.questions, {
3521
+ components: [...screenPlan?.kitComponents ?? [], ...shellPlan ? SHELL_COMPONENTS : []],
3522
+ only: screensOnly
3523
+ });
3524
+ const section = planSection(root, input, info, planned, manifest, chosen, onDisk, listScreens2 ? screensAfter : null);
2620
3525
  let packages = planPackages(chosen, manifest, info.deps);
2621
- let sectionNote = section.decision.note;
3526
+ let sectionNote = screensOnly && section.decision.note === SECTION_NEEDS_FULL_KIT ? null : section.decision.note;
2622
3527
  let writeSection = section.decision.write;
2623
3528
  if (writeSection) {
2624
3529
  const withSection = planPackages(chosen, manifest, info.deps, section.packages);
@@ -2628,8 +3533,14 @@ async function runAdd(input, deps) {
2628
3533
  sectionNote = SECTION_CONFLICT(blocking);
2629
3534
  } else packages = withSection;
2630
3535
  }
3536
+ const shellBlocker = shellPlan === null ? null : SHELL_COMPONENTS.map(
3537
+ (name) => !manifest.components.some((c) => c.name === name) ? SHELL_NOT_IN_KIT(name) : packages.skipped.find((k) => k.name === name)?.reason ?? null
3538
+ ).find((r) => r !== null) ?? null;
3539
+ const shellToWrite = shellBlocker === null ? shellPlan : null;
3540
+ const registryAlone = !writeSection && onDisk.present && fetchedScreens && (screenPlan?.write.length ?? 0) > 0 && planned.componentsDir !== null && sectionReadsScreens(root, planned) ? registryFile(planned.componentsDir, planned, screensAfter, registrySite(manifest)) : null;
2631
3541
  const plan = planFiles(root, planned, componentClosure(packages.components, manifest), manifest);
2632
- const sectionStatus = (writeSection ? section.paths : []).filter((p) => !p.endsWith(".json")).map((p) => [p, existingFileStatus(resolveInside(root, p))]);
3542
+ const sectionStatus = [...writeSection ? section.paths : [], ...registryAlone ? [registryAlone.path] : []].filter((p) => !p.endsWith(".json")).map((p) => [p, existingFileStatus(resolveInside(root, p))]);
3543
+ const shellStatus = [...shellToWrite ? [shellToWrite] : [], ...sitePlan ? [sitePlan] : []].map((f) => [f.path, f.status]);
2633
3544
  const setup = planSetup(info, manifest, deps.exec);
2634
3545
  if (writeSection && info.framework === "vite") {
2635
3546
  try {
@@ -2640,13 +3551,22 @@ async function runAdd(input, deps) {
2640
3551
  sectionNote = VITE_INPUT_MANUAL;
2641
3552
  }
2642
3553
  }
2643
- const replaceForeign = [...plan.replaceForeign, ...sectionStatus.filter(([, s]) => s === "foreign").map(([p]) => p)];
3554
+ const replaceForeign = [
3555
+ ...plan.replaceForeign,
3556
+ ...[...sectionStatus, ...shellStatus].filter(([, s]) => s === "foreign").map(([p]) => p),
3557
+ ...screenPlan?.foreign ?? []
3558
+ ];
2644
3559
  if (replaceForeign.length > 0 && !await deps.questions.confirmReplace(replaceForeign)) throw new CliError(REPLACE_DECLINED);
2645
3560
  const kept = [];
2646
- for (const path of [...plan.edited, ...sectionStatus.filter(([, s]) => s === "edited").map(([p]) => p)]) {
3561
+ for (const path of [...plan.edited, ...[...sectionStatus, ...shellStatus].filter(([, s]) => s === "edited").map(([p]) => p)]) {
2647
3562
  if (await deps.questions.keepEdits(path)) kept.push(path);
2648
3563
  }
3564
+ const screensKept = [];
3565
+ for (const path of screenPlan?.edited ?? []) {
3566
+ if (await deps.questions.keepEdits(path)) screensKept.push(path);
3567
+ }
2649
3568
  const writes = plan.write.filter((w) => !kept.includes(w.path));
3569
+ const screenWrites = (screenPlan?.write ?? []).filter((w) => !screensKept.includes(w.path));
2650
3570
  if (!info.shadcn) deps.progress(NO_SHADCN);
2651
3571
  for (const step of setup.steps) {
2652
3572
  await step.run();
@@ -2657,16 +3577,19 @@ async function runAdd(input, deps) {
2657
3577
  if (!written) throw new CliError("Setup did not leave a components.json. Run this again.");
2658
3578
  assertSameTargets(planned, resolveTargets(root, written));
2659
3579
  }
2660
- const sheet = readFileSync8(cssAbs, "utf8");
3580
+ const sheet = readFileSync9(cssAbs, "utf8");
2661
3581
  const dark = readDarkMarker(sheet);
2662
3582
  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)) : [];
3583
+ const sectionWrites = [...writeSection ? section.files(dark.marker) : [], ...registryAlone ? [registryAlone] : []].filter((f) => !kept.includes(f.path));
3584
+ const shellWrite = shellToWrite && !kept.includes(shellToWrite.path) ? shellToWrite : null;
3585
+ const siteWrite = sitePlan && !kept.includes(sitePlan.path) ? sitePlan : null;
3586
+ const registryWritten = listScreens2 && planned.componentsDir !== null && sectionWrites.some((f) => f.path === registryPath(planned.componentsDir));
2664
3587
  const removeScaffolding = info.shadcn !== null || hasThemeRegion(sheet);
2665
3588
  const themed = applyTheme(sheet, manifest.theme, { preflight: setup.preflight, removeScaffolding });
2666
3589
  try {
2667
3590
  writeFiles(
2668
3591
  root,
2669
- [{ path: planned.cssFile, contents: themed.css }, ...[...writes, ...sectionWrites].map(({ path, contents }) => ({ path, contents }))],
3592
+ [{ path: planned.cssFile, contents: themed.css }, ...[...writes, ...sectionWrites, ...screenWrites, ...shellWrite ? [shellWrite] : [], ...siteWrite ? [siteWrite] : []].map(({ path, contents }) => ({ path, contents }))],
2670
3593
  { force: true, created: false }
2671
3594
  );
2672
3595
  } catch (e) {
@@ -2678,7 +3601,18 @@ async function runAdd(input, deps) {
2678
3601
  const shown = added.filter((n) => n !== PORTAL).length;
2679
3602
  if (shown > 0) deps.progress(`Adding ${shown} component${shown === 1 ? "" : "s"}\u2026 \u2713`);
2680
3603
  if (writeSection) deps.progress("Adding the /design-system section\u2026 \u2713");
2681
- const commands = installCommands(info, manifest, packages.install);
3604
+ const screensAdded = (screenPlan?.added ?? []).filter((a) => screenWrites.some((w) => w.screen === a.slug));
3605
+ if (screensAdded.length > 0) deps.progress(`Adding ${screensAdded.length} screen${screensAdded.length === 1 ? "" : "s"}\u2026 \u2713`);
3606
+ if (shellWrite) deps.progress("Adding the app shell\u2026 \u2713");
3607
+ if (siteWrite) deps.progress("Adding the site menu\u2026 \u2713");
3608
+ const install = {
3609
+ ...packages.install,
3610
+ ...screenInstalls((screenPlan?.added ?? []).map((s) => s.slug), manifest, info.deps),
3611
+ ...partInstalls(screenPlan?.siteParts ?? [], manifest, info.deps)
3612
+ };
3613
+ const reactIs = manifest.packages["react-is"];
3614
+ if ("recharts" in install && reactIs !== void 0 && info.deps["react-is"] === void 0) install["react-is"] = reactIs;
3615
+ const commands = installCommands(info, manifest, install);
2682
3616
  const installCommand = commands.map(printedCommand).join(" && ") || null;
2683
3617
  if (installCommand && input.skipInstall) deps.progress(`Skipped installing libraries. Run: ${installCommand}`);
2684
3618
  else if (installCommand) {
@@ -2705,13 +3639,48 @@ async function runAdd(input, deps) {
2705
3639
  blocks: section.blockCount,
2706
3640
  ...section.decision.blocks === "keep" ? { blocksLeftInPlace: true } : {}
2707
3641
  } : null,
2708
- sectionNote
3642
+ sectionNote,
3643
+ screens: screenPlan === null || screenSelection === null ? null : {
3644
+ added: screensAdded,
3645
+ kept: screensKept,
3646
+ skipped: [...screenSelection.skipped, ...screenPlan.skipped],
3647
+ gone: screenPlan.gone,
3648
+ routeDir: info.framework === "next" ? nextAppDir(root) : null
3649
+ },
3650
+ screensView: registryWritten && screensAfter.length > 0 ? info.framework === "vite" ? "/design-system.html#/screens" : "/design-system/screens" : null,
3651
+ // The app shell lists app screens alone: pages have the site menu.
3652
+ shell: shellWrite ? { importPath: shellWrite.importPath, screens: screensAfter.filter((s) => !isPageKind(s.kind)).length } : null,
3653
+ shellNote: shellBlocker === null ? null : SHELL_SKIPPED(shellBlocker),
3654
+ site: siteWrite ? { importPath: siteWrite.importPath, pages: siteListed.length } : null,
3655
+ siteSkipped,
3656
+ siteOnDisk: disk.site || siteWrite !== null
2709
3657
  };
2710
3658
  }
2711
3659
 
2712
3660
  // src/add/summary.ts
2713
3661
  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
3662
  var sectionNoteFor = (note, reader) => reader === "agent" && note === SECTION_NEEDS_FULL_KIT ? SECTION_NEEDS_FULL_KIT_FOR_AGENT : note;
3663
+ var screenSkipLine = (s, reader) => screenSkipText(s.slug, reader === "agent" && s.agentReason ? s.agentReason : s.reason);
3664
+ var GET_SITE_SHELL = {
3665
+ cli: "Get <SiteShell> with npx designsource add --screen site.",
3666
+ agent: 'Get <SiteShell>: call add_ui_kit with screens ["site"].'
3667
+ };
3668
+ function screenLines(r, reader, siteOnDisk) {
3669
+ const first = r.added.find((s) => !s.page);
3670
+ 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.`];
3671
+ const pages = !r.added.some((s) => s.page) ? [] : [
3672
+ r.routeDir !== null ? `Mount each page on its own route inside <SiteShell>: ${r.routeDir}/page.tsx for the home page, ${r.routeDir}/<name>/page.tsx for the others. Never inside the app shell.` : "Render each page on its own route inside <SiteShell>, never inside the app shell.",
3673
+ ...siteOnDisk ? [] : [GET_SITE_SHELL[reader]]
3674
+ ];
3675
+ return [
3676
+ ...r.added.map((s) => `import { ${s.component} } from '${s.importPath}'`),
3677
+ ...mount,
3678
+ ...pages,
3679
+ ...r.kept.map((path) => `Kept your edits to ${path}`),
3680
+ ...r.skipped.map((skip) => screenSkipLine(skip, reader)),
3681
+ ...r.gone.map((slug) => `Screen "${printable(slug)}" is no longer in DS source; left it in place`)
3682
+ ];
3683
+ }
2715
3684
  function summaryLines(r, reader = "cli") {
2716
3685
  return [
2717
3686
  ...r.replacedTheme ? [`Replaced the theme in ${r.themeFile}`] : [],
@@ -2722,6 +3691,12 @@ function summaryLines(r, reader = "cli") {
2722
3691
  ...r.section?.blocksLeftInPlace ? [leftBlocksLine(r.section.blocks, reader)] : [],
2723
3692
  ...r.section ? [`Your design system: ${r.section.path}`] : [],
2724
3693
  ...r.sectionNote ? [sectionNoteFor(r.sectionNote, reader)] : [],
3694
+ ...r.screens ? screenLines(r.screens, reader, r.siteOnDisk) : [],
3695
+ ...r.screensView ? [`Your screens: ${r.screensView}`] : [],
3696
+ ...r.shell ? [`import { AppShell } from '${r.shell.importPath}'`, ...r.shell.screens === 0 ? [reader === "agent" ? SHELL_EMPTY_FOR_AGENT : SHELL_EMPTY] : []] : [],
3697
+ ...r.shellNote ? [r.shellNote] : [],
3698
+ ...r.site ? [`import { SiteShell } from '${r.site.importPath}'`] : [],
3699
+ ...r.siteSkipped ? [reader === "agent" && r.siteSkipped.agentReason ? r.siteSkipped.agentReason : r.siteSkipped.reason] : [],
2725
3700
  `Done. Your components now use "${r.projectName}" from designsource.app.`,
2726
3701
  "Run it again any time to pull updates."
2727
3702
  ];
@@ -3021,7 +3996,7 @@ import { homedir } from "node:os";
3021
3996
 
3022
3997
  // src/connect/store.ts
3023
3998
  import { randomBytes } from "node:crypto";
3024
- import { chmodSync, constants, copyFileSync, mkdirSync as mkdirSync2, readFileSync as readFileSync9, renameSync, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
3999
+ import { chmodSync, constants, copyFileSync, mkdirSync as mkdirSync2, readFileSync as readFileSync10, renameSync, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
3025
4000
  import { basename, dirname as dirname2, isAbsolute as isAbsolute2, join as join6, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
3026
4001
  var WHERE = ["keychain", "secret-service", "dpapi", "file"];
3027
4002
  function credentialsPath(env, platform, home) {
@@ -3037,7 +4012,7 @@ function isFileEntry(value) {
3037
4012
  function readCredentials(path) {
3038
4013
  let text;
3039
4014
  try {
3040
- text = readFileSync9(path, "utf8");
4015
+ text = readFileSync10(path, "utf8");
3041
4016
  } catch {
3042
4017
  return { version: 1, projects: {} };
3043
4018
  }
@@ -3224,7 +4199,7 @@ function validateManifest(json) {
3224
4199
 
3225
4200
  // src/fetch-manifest.ts
3226
4201
  async function fetchManifest(opts, fetchImpl = fetch) {
3227
- const query = { framework: opts.framework, ...opts.name ? { name: opts.name } : {} };
4202
+ const query = { framework: opts.framework, ...opts.name ? { name: opts.name } : {}, ...opts.screens ? { screens: opts.screens, pages: "1" } : {} };
3228
4203
  return validateManifest(await getJson({ api: opts.api, token: opts.token, path: "/api/starter", query }, fetchImpl));
3229
4204
  }
3230
4205
 
@@ -3285,7 +4260,8 @@ async function savedToken(given, opts) {
3285
4260
  async function scaffold(input, env, io) {
3286
4261
  const { folder, framework, token, api, force } = input;
3287
4262
  const { root, created } = planTarget(io.cwd, folder, framework, force);
3288
- const manifest = await fetchManifest({ api, token, framework, name: packageNameFor(folder) }, io.fetchImpl);
4263
+ const screens = input.screens === true && framework === "next" ? { screens: "all" } : {};
4264
+ const manifest = await fetchManifest({ api, token, framework, name: packageNameFor(folder), ...screens }, io.fetchImpl);
3289
4265
  const { runner, version } = detectRunner(env.npm_config_user_agent);
3290
4266
  const packageManager = runner === "pnpm" && version ? `pnpm@${version}` : void 0;
3291
4267
  const { written } = writeFiles(root, manifest.files, { force, created, packageManager });
@@ -3338,7 +4314,7 @@ async function runAddCommand(args, io, exec = spawnExec, store) {
3338
4314
  const targets = info.shadcn ? resolveTargets(root, info.shadcn) : defaultTargets(root, info);
3339
4315
  assertKitUtils(root, info, targets);
3340
4316
  let mode;
3341
- if (interactive && args.components.length === 0 && !args.all) {
4317
+ if (interactive && args.components.length === 0 && !args.all && args.screens === void 0 && !args.shell && !args.site) {
3342
4318
  const first = previouslyAdded(root, targets).every((n) => n === "utils") && !sectionPresent(root, targets).present;
3343
4319
  if (first) mode = await pick(PICK_QUESTION, ADD_MODES, 0);
3344
4320
  }
@@ -3346,7 +4322,20 @@ async function runAddCommand(args, io, exec = spawnExec, store) {
3346
4322
  const questions = interactive ? ttyQuestions(args, mode, io) : nonInteractiveQuestions(args);
3347
4323
  try {
3348
4324
  const result = await runAdd(
3349
- { root, token, api: apiFor(args, entry), components: args.components, skipInstall: args.skipInstall, all: args.all, blocks: !args.noBlocks },
4325
+ {
4326
+ root,
4327
+ token,
4328
+ api: apiFor(args, entry),
4329
+ components: args.components,
4330
+ skipInstall: args.skipInstall,
4331
+ all: args.all,
4332
+ blocks: !args.noBlocks,
4333
+ screens: args.screens,
4334
+ shell: args.shell,
4335
+ site: args.site,
4336
+ refreshScreens: true,
4337
+ force: args.force
4338
+ },
3350
4339
  { fetchImpl: io.fetchImpl, exec, questions, progress: (line) => io.stdout(`${line}
3351
4340
  `) }
3352
4341
  );
@@ -3360,7 +4349,7 @@ async function runAddCommand(args, io, exec = spawnExec, store) {
3360
4349
  }
3361
4350
 
3362
4351
  // src/commands/connect.ts
3363
- import { accessSync, constants as constants2, existsSync as existsSync10, statSync as statSync3 } from "node:fs";
4352
+ import { accessSync, constants as constants2, existsSync as existsSync11, statSync as statSync3 } from "node:fs";
3364
4353
  import { homedir as homedir2 } from "node:os";
3365
4354
  import { join as join8 } from "node:path";
3366
4355
 
@@ -3387,9 +4376,9 @@ async function fetchProject(opts, fetchImpl = fetch) {
3387
4376
  }
3388
4377
 
3389
4378
  // src/connect/project-root.ts
3390
- import { existsSync as existsSync9 } from "node:fs";
4379
+ import { existsSync as existsSync10 } from "node:fs";
3391
4380
  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 = existsSync9) {
4381
+ function projectRoot(cwd, exists = existsSync10) {
3393
4382
  let dir = resolve5(cwd);
3394
4383
  for (; ; ) {
3395
4384
  if (exists(join7(dir, ".git"))) return dir;
@@ -3435,7 +4424,7 @@ function defaultConnectDeps(env) {
3435
4424
  const platform = process.platform;
3436
4425
  return {
3437
4426
  store: defaultStore(env),
3438
- detect: () => detectApps({ env, platform, home, exists: existsSync10, onPath: (bin) => onPath(bin, env, platform) }),
4427
+ detect: () => detectApps({ env, platform, home, exists: existsSync11, onPath: (bin) => onPath(bin, env, platform) }),
3439
4428
  credentialsPath: credentialsPath(env, platform, home)
3440
4429
  };
3441
4430
  }
@@ -3573,7 +4562,7 @@ async function runCreate(args, env, io, store) {
3573
4562
  const saved = await savedToken(args.token, { cwd: io.cwd, store });
3574
4563
  const folder = args.folder ?? await askFolder(CREATE_DEFAULT_FOLDER);
3575
4564
  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);
4565
+ await scaffold({ folder, framework: "next", token, api: apiFor(args, saved?.entry), force: args.force, screens: args.noScreens !== true }, env, io);
3577
4566
  }
3578
4567
 
3579
4568
  // src/commands/integrate.ts
@@ -3592,16 +4581,16 @@ async function runIntegrate(args, env, io, store) {
3592
4581
  }
3593
4582
 
3594
4583
  // src/commands/login.ts
3595
- import { existsSync as existsSync11 } from "node:fs";
4584
+ import { existsSync as existsSync12 } from "node:fs";
3596
4585
  import { join as join10 } from "node:path";
3597
4586
  import { homedir as homedir3, hostname } from "node:os";
3598
4587
 
3599
4588
  // src/connect/account-store.ts
3600
4589
  import { createHash as createHash2 } from "node:crypto";
3601
- import { readFileSync as readFileSync10, realpathSync } from "node:fs";
4590
+ import { readFileSync as readFileSync11, realpathSync } from "node:fs";
3602
4591
  import { dirname as dirname4, join as join9, parse, resolve as resolve6, sep as sep4 } from "node:path";
3603
4592
  var WHERE2 = ["keychain", "secret-service", "dpapi", "file"];
3604
- var ACCOUNT_TOKEN = /^dsa_[A-Za-z0-9_-]{43}$/;
4593
+ var ACCOUNT_TOKEN2 = /^dsa_[A-Za-z0-9_-]{43}$/;
3605
4594
  var PROJECT_ID2 = /^[A-Za-z0-9_-]+$/;
3606
4595
  var LABEL = "account";
3607
4596
  function normaliseOrigin(origin) {
@@ -3633,15 +4622,15 @@ function normaliseFolder(folder) {
3633
4622
  while (path.length > root.length && (path.endsWith(sep4) || path.endsWith("/"))) path = path.slice(0, -1);
3634
4623
  return path;
3635
4624
  }
3636
- function isRecord2(value) {
4625
+ function isRecord3(value) {
3637
4626
  return typeof value === "object" && value !== null && !Array.isArray(value);
3638
4627
  }
3639
4628
  function readAccount(value) {
3640
- if (!isRecord2(value)) return null;
4629
+ if (!isRecord3(value)) return null;
3641
4630
  const { email, where, folders, links, secret } = value;
3642
4631
  if (typeof email !== "string" || !WHERE2.includes(where)) return null;
3643
4632
  if (!Array.isArray(folders) || !folders.every((f) => typeof f === "string")) return null;
3644
- if (!isRecord2(links) || !Object.values(links).every((id) => typeof id === "string" && PROJECT_ID2.test(id))) return null;
4633
+ if (!isRecord3(links) || !Object.values(links).every((id) => typeof id === "string" && PROJECT_ID2.test(id))) return null;
3645
4634
  if (secret !== void 0 && typeof secret !== "string") return null;
3646
4635
  const entry = { email, where, folders: [...folders], links: Object.assign(/* @__PURE__ */ Object.create(null), links) };
3647
4636
  if (secret !== void 0) entry.secret = secret;
@@ -3651,7 +4640,7 @@ function readAccounts(path) {
3651
4640
  const accounts = /* @__PURE__ */ Object.create(null);
3652
4641
  let text;
3653
4642
  try {
3654
- text = readFileSync10(path, "utf8");
4643
+ text = readFileSync11(path, "utf8");
3655
4644
  } catch {
3656
4645
  return { version: 1, accounts };
3657
4646
  }
@@ -3661,7 +4650,7 @@ function readAccounts(path) {
3661
4650
  } catch {
3662
4651
  return { version: 1, accounts, unreadable: true };
3663
4652
  }
3664
- if (!isRecord2(parsed) || parsed.version !== 1 || !isRecord2(parsed.accounts)) return { version: 1, accounts, unreadable: true };
4653
+ if (!isRecord3(parsed) || parsed.version !== 1 || !isRecord3(parsed.accounts)) return { version: 1, accounts, unreadable: true };
3665
4654
  for (const [origin, value] of Object.entries(parsed.accounts)) {
3666
4655
  const entry = readAccount(value);
3667
4656
  if (entry) accounts[origin] = entry;
@@ -3699,11 +4688,11 @@ function createAccountStore(opts) {
3699
4688
  if (!Object.hasOwn(accounts, key)) return null;
3700
4689
  const entry = accounts[key];
3701
4690
  const value = entry.where === "file" ? entry.secret ?? null : await osBackend(entry.where).get(accountSecretId(key), entry.secret);
3702
- return value !== null && ACCOUNT_TOKEN.test(value) ? value : null;
4691
+ return value !== null && ACCOUNT_TOKEN2.test(value) ? value : null;
3703
4692
  },
3704
4693
  async save({ origin, email, token, folder }) {
3705
4694
  const key = normaliseOrigin(origin);
3706
- if (!ACCOUNT_TOKEN.test(token)) throw new CliError("Unexpected account token from the API.");
4695
+ if (!ACCOUNT_TOKEN2.test(token)) throw new CliError("Unexpected account token from the API.");
3707
4696
  const id = accountSecretId(key);
3708
4697
  const { unreadable, ...data } = readAccounts(path);
3709
4698
  const previous = Object.hasOwn(data.accounts, key) ? data.accounts[key] : void 0;
@@ -3763,113 +4752,6 @@ function trustedRootFor(cwd) {
3763
4752
  return normaliseFolder(projectRoot(normaliseFolder(cwd)));
3764
4753
  }
3765
4754
 
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
4755
  // src/commands/login.ts
3874
4756
  function defaultLoginDeps(env) {
3875
4757
  const home = homedir3();
@@ -3877,7 +4759,7 @@ function defaultLoginDeps(env) {
3877
4759
  return {
3878
4760
  accounts: createAccountStore({ env, platform, exec: spawnExec, home }),
3879
4761
  accountPath: accountPath(env, platform, home),
3880
- detect: () => detectApps({ env, platform, home, exists: existsSync11, onPath: (bin) => onPath(bin, env, platform) }),
4762
+ detect: () => detectApps({ env, platform, home, exists: existsSync12, onPath: (bin) => onPath(bin, env, platform) }),
3881
4763
  home,
3882
4764
  terminal: process.stdin.isTTY === true && process.stdout.isTTY === true,
3883
4765
  hostname: hostname(),
@@ -3886,6 +4768,7 @@ function defaultLoginDeps(env) {
3886
4768
  }
3887
4769
  var sleepFor = (ms) => new Promise((resolve8) => setTimeout(resolve8, ms));
3888
4770
  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.`;
4771
+ var ACCOUNT_SCOPES_NEEDED = ["projects:create", "projects:read", "screens:create"];
3889
4772
  var REVOKE_FAILED = "Could not reach the server to revoke this sign-in; revoke it on your profile page.";
3890
4773
  function loginApi(args, terminal) {
3891
4774
  const api = originOf(args.api);
@@ -3893,7 +4776,7 @@ function loginApi(args, terminal) {
3893
4776
  throw new CliError(UNTRUSTED_LOGIN_SERVER(api));
3894
4777
  }
3895
4778
  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) => existsSync11(join10(root, ".git")) || existsSync11(join10(root, "package.json"));
4779
+ var isProjectFolder = (root) => existsSync12(join10(root, ".git")) || existsSync12(join10(root, "package.json"));
3897
4780
  function savedLine2(where, file) {
3898
4781
  if (where === "keychain") return "Saved the sign-in in the macOS keychain \u2713";
3899
4782
  if (where === "secret-service") return "Saved the sign-in in the system keyring \u2713";
@@ -3944,11 +4827,12 @@ async function runLogin(args, io, deps = defaultLoginDeps(process.env)) {
3944
4827
  const savedToken2 = saved ? await accounts.token(api).catch(() => null) : null;
3945
4828
  if (terminal && saved && savedToken2) {
3946
4829
  const check = await requestJson({ api, path: "/api/agent/projects", method: "GET", token: savedToken2 }, io.fetchImpl);
3947
- if (check.status === 200) {
4830
+ const stale = check.status === 200 && await lacksScope(api, savedToken2, io.fetchImpl);
4831
+ if (check.status === 200 && !stale) {
3948
4832
  accounts.trust(api, root);
3949
4833
  email = printable(saved.email);
3950
4834
  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) {
4835
+ } else if (check.status !== 200 && check.status !== 401 && check.status !== 403) {
3952
4836
  throw new CliError(messageForResponse(check.status, check.body, api));
3953
4837
  }
3954
4838
  }
@@ -3989,6 +4873,17 @@ async function runLogin(args, io, deps = defaultLoginDeps(process.env)) {
3989
4873
  ...closingLines2(apps, changed, usesAccount)
3990
4874
  ]);
3991
4875
  }
4876
+ async function lacksScope(api, token, fetchImpl) {
4877
+ try {
4878
+ const res = await requestJson({ api, path: "/api/agent/token", method: "GET", token }, fetchImpl);
4879
+ if (res.status !== 200 || typeof res.body !== "object" || res.body === null) return false;
4880
+ const scopes = res.body.scopes;
4881
+ if (!Array.isArray(scopes)) return false;
4882
+ return ACCOUNT_SCOPES_NEEDED.some((needed) => !scopes.includes(needed));
4883
+ } catch {
4884
+ return false;
4885
+ }
4886
+ }
3992
4887
  async function revoke(api, token, fetchImpl) {
3993
4888
  try {
3994
4889
  const res = await requestJson({ api, path: "/api/agent/token", method: "DELETE", token }, fetchImpl);
@@ -4027,7 +4922,7 @@ async function runLogout(args, io, deps = defaultLoginDeps(process.env)) {
4027
4922
  import { homedir as homedir4 } from "node:os";
4028
4923
 
4029
4924
  // src/version.ts
4030
- var VERSION = true ? "0.9.0" : "0.0.0-dev";
4925
+ var VERSION = true ? "0.11.0" : "0.0.0-dev";
4031
4926
 
4032
4927
  // src/mcp/account-session.ts
4033
4928
  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 +5037,9 @@ function getPrompt(name) {
4142
5037
  return { description: "Integrate the design system into the current repository.", messages: [{ role: "user", content: { type: "text", text: INTEGRATE_TEXT } }] };
4143
5038
  }
4144
5039
 
5040
+ // src/mcp/account-tools.ts
5041
+ import { randomUUID } from "node:crypto";
5042
+
4145
5043
  // src/mcp/results.ts
4146
5044
  var textResult = (text) => ({ content: [{ type: "text", text }] });
4147
5045
  var errorResult = (text) => ({ content: [{ type: "text", text }], isError: true });
@@ -4278,6 +5176,63 @@ async function useDesignSystem(args, ctx) {
4278
5176
  if (!account.link(id)) return errorResult(NOT_SIGNED_IN_FOR(account.folder));
4279
5177
  return textResult(`This folder now uses "${found.name}" from ${email}'s account.`);
4280
5178
  }
5179
+ var SCREEN_PROMPT_MAX = 500;
5180
+ var FUNDING_CODES = ["credits_required", "provider_key_required"];
5181
+ var SCREENS_NOT_SERVED_YET = "This DS source server cannot make screens yet.";
5182
+ var UNKNOWN_SCREEN = (slug, project) => `No screen named "${slug}" in ${project}. Call list_screens for the names.`;
5183
+ var isScreenName = (v) => typeof v === "string" && SCREEN_SLUG.test(v) && !RESERVED_SCREEN_SLUGS.includes(v);
5184
+ var generatePath = (projectId) => `/api/agent/projects/${encodeURIComponent(projectId)}/screens/generate`;
5185
+ var serverText = (body) => {
5186
+ const error = isPlainObject(body) ? body.error : void 0;
5187
+ const text = typeof error === "string" ? printable(error).trim() : "";
5188
+ return text || null;
5189
+ };
5190
+ var fundingRefusal = (body, api) => {
5191
+ if (!isPlainObject(body) || !FUNDING_CODES.includes(String(body.code))) return null;
5192
+ return errorResult(`${serverText(body) ?? "This account cannot pay for a screen right now."} ${FUNDING_HINT(api)}`);
5193
+ };
5194
+ 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 a marketing page (home, pricing or waitlist: one of each kind), or change an existing screen or page 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.";
5195
+ async function generateScreen(args, ctx) {
5196
+ if (!ctx.account) return errorResult(ctx.accountRefusal ?? GENERATE_NEEDS_LOGIN);
5197
+ const account = ctx.account;
5198
+ const { prompt, screen, data_model: dataModel } = args;
5199
+ if (typeof prompt !== "string" || !prompt.trim()) return errorResult('"prompt" must say what the screen should show.');
5200
+ if (prompt.trim().length > SCREEN_PROMPT_MAX) return errorResult(`"prompt" must be at most ${SCREEN_PROMPT_MAX} characters.`);
5201
+ if (screen !== void 0 && !isScreenName(screen)) return errorResult('"screen" must be a screen name from list_screens, or left out for a new screen.');
5202
+ if (dataModel !== void 0 && !isPlainObject(dataModel)) return errorResult('"data_model" must be an object (see its description), or left out.');
5203
+ if (account.projectId === null) return errorResult(NO_LINK);
5204
+ const projectId = account.projectId;
5205
+ const projects = await listProjects(account, ctx);
5206
+ if (!Array.isArray(projects)) return projects;
5207
+ const project = projects.find((p) => p.id === projectId);
5208
+ if (!project) return errorResult(LINKED_PROJECT_GONE);
5209
+ const body = { prompt, operationId: randomUUID(), pages: true };
5210
+ if (screen !== void 0) body.screen = screen;
5211
+ if (dataModel !== void 0) body.dataModel = dataModel;
5212
+ const outcome = await postNdjson({ api: account.api, path: generatePath(projectId), token: account.token, body }, ctx.fetchImpl);
5213
+ if (outcome.kind === "refused") {
5214
+ const { status, body: refusal } = outcome;
5215
+ const code2 = isPlainObject(refusal) ? refusal.code : void 0;
5216
+ if (status === 403 && code2 === "agent_scope_missing") return errorResult(SCOPE_LOGIN_AGAIN);
5217
+ if (status === 404 && !(isPlainObject(refusal) && typeof refusal.error === "string")) return errorResult(SCREENS_NOT_SERVED_YET);
5218
+ if (status === 404) return errorResult(screen !== void 0 ? UNKNOWN_SCREEN(screen, project.name) : LINKED_PROJECT_GONE);
5219
+ return fundingRefusal(refusal, account.api) ?? serverError(status, refusal, account.api);
5220
+ }
5221
+ ctx.dropSnapshot?.();
5222
+ if (outcome.kind === "error") return fundingRefusal(outcome.event, account.api) ?? errorResult(serverText(outcome.event) ?? SCREEN_NOT_MADE);
5223
+ if (outcome.kind === "ended") return errorResult(SCREEN_NOT_MADE);
5224
+ const data = outcome.data;
5225
+ const made = isPlainObject(data) && isPlainObject(data.screen) ? data.screen : null;
5226
+ if (!made || !isScreenName(made.slug) || typeof made.title !== "string" || !isPlainObject(data) || typeof data.url !== "string") {
5227
+ return errorResult(UNEXPECTED2(account.api));
5228
+ }
5229
+ const verb = screen !== void 0 ? "Changed" : "Made";
5230
+ return textResult(
5231
+ `${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).`
5232
+ );
5233
+ }
5234
+ var SCREEN_FIELD_TYPES = ["text", "number", "money", "date", "status", "person", "email", "boolean"];
5235
+ 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
5236
  var ACCOUNT_TOOLS = [
4282
5237
  {
4283
5238
  name: "list_design_systems",
@@ -4321,6 +5276,24 @@ var ACCOUNT_TOOLS = [
4321
5276
  needsSnapshot: false,
4322
5277
  accountTool: true,
4323
5278
  run: (_s, _at, args, ctx) => useDesignSystem(args, ctx)
5279
+ },
5280
+ {
5281
+ name: "generate_screen",
5282
+ description: GENERATE_DESCRIPTION,
5283
+ inputSchema: {
5284
+ type: "object",
5285
+ properties: {
5286
+ prompt: { type: "string", description: "What the screen should show, or what to change in it, in a sentence or two (up to 500 characters)." },
5287
+ screen: { type: "string", description: "A screen name from list_screens, to change that screen. Leave it out to make a new one." },
5288
+ data_model: { type: "object", description: DATA_MODEL_DESCRIPTION }
5289
+ },
5290
+ required: ["prompt"],
5291
+ additionalProperties: false
5292
+ },
5293
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
5294
+ needsSnapshot: false,
5295
+ accountTool: true,
5296
+ run: (_s, _at, args, ctx) => generateScreen(args, ctx)
4324
5297
  }
4325
5298
  ];
4326
5299
 
@@ -4368,6 +5341,74 @@ function optionalEnum(args, key, allowed) {
4368
5341
  var MCP_EXEC_TIMEOUT_MS = 10 * 60 * 1e3;
4369
5342
  var UNKNOWN_FOR_AGENT = (names) => `Unknown component(s): ${names.join(", ")}. Call list_components for the names.`;
4370
5343
  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.`;
5344
+ function kitAccess(ctx) {
5345
+ if (ctx.token !== null) return { token: ctx.token, api: ctx.api };
5346
+ if (!ctx.account) return errorResult(ctx.missingToken ?? MCP_TOKEN_REQUIRED);
5347
+ const { token, api, projectId } = ctx.account;
5348
+ if (projectId === null) return errorResult(NO_LINK);
5349
+ return { token, api, kitPath: accountProjectPath(projectId, "kit"), messages: accountMessageForResponse };
5350
+ }
5351
+ var isResult2 = (v) => "content" in v;
5352
+ var isScreenName2 = (v) => typeof v === "string" && SCREEN_SLUG.test(v) && !RESERVED_SCREEN_SLUGS.includes(v);
5353
+ var SCREENS_NOT_LISTED = "This DS source server does not list screens yet.";
5354
+ 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.";
5355
+ var SCREEN_NAME_ARG = '"screen" must be a screen name from list_screens.';
5356
+ var SCREENS_ARG = '"screens" must be screen names from list_screens, "site", or ["all"].';
5357
+ var SCREENS_NOT_SERVED_FOR_AGENT = "This DS source server does not send screens yet. Call add_ui_kit without screens.";
5358
+ var NO_PAGES_PULLED_FOR_AGENT = (e) => {
5359
+ if (e.skip) return PAGE_SKIPPED_NO_SITE(screenSkipText(e.skip.slug, e.skip.agentReason ?? e.skip.reason));
5360
+ const head = "None of this design system's pages is in the app yet, and the site menu links only the pages there.";
5361
+ return e.page === null ? `${head} None of them can be built now: ask the user to pick another version of one in DS source.` : `${head} Call add_ui_kit with screens ["${e.page}", "site"] to pull a page with it.`;
5362
+ };
5363
+ function listScreens(snapshot) {
5364
+ if (!snapshot.screens) return errorResult(SCREENS_NOT_LISTED);
5365
+ if (snapshot.screens.length === 0) return textResult(NO_SCREENS_LISTED);
5366
+ return textResult(snapshot.screens.map((s) => `${s.slug} \u2014 ${printable(s.title)} (${s.kind})`).join("\n"));
5367
+ }
5368
+ function fenced(path, lang, text) {
5369
+ const longest = Math.max(0, ...(text.match(/`+/g) ?? []).map((run2) => run2.length));
5370
+ const fence = "`".repeat(Math.max(3, longest + 1));
5371
+ return `### ${path}
5372
+ ${fence}${lang}
5373
+ ${text}${text.endsWith("\n") ? "" : "\n"}${fence}`;
5374
+ }
5375
+ async function getScreenSource(args, ctx) {
5376
+ const slug = args.screen;
5377
+ if (!isScreenName2(slug)) return errorResult(SCREEN_NAME_ARG);
5378
+ const access = kitAccess(ctx);
5379
+ if (isResult2(access)) return access;
5380
+ const { kitPath, ...rest } = access;
5381
+ const manifest = await fetchKit({ ...rest, ...kitPath ? { path: kitPath } : {}, screens: [slug] }, ctx.fetchImpl);
5382
+ const index = manifest.screenIndex;
5383
+ if (index === void 0) return errorResult(SCREENS_NOT_LISTED);
5384
+ const entry = index.find((e) => e.slug === slug);
5385
+ if (!entry) return errorResult(UNKNOWN_SCREENS([slug], index, manifest.name));
5386
+ const screen = manifest.screens?.find((s) => s.slug === slug);
5387
+ if (!entry.available || !screen) return errorResult(SCREEN_UNAVAILABLE);
5388
+ const parts = screenPartsOf(screen, manifest);
5389
+ const partNames = parts.map((p) => p.name).sort();
5390
+ const components = [...new Set(parts.flatMap((p) => p.kitImports))].sort();
5391
+ const [tsx, data] = screen.files;
5392
+ return textResult(
5393
+ [
5394
+ `${slug} \u2014 ${printable(entry.title)} (${entry.kind}). Imports use the starter's @/components paths; add_ui_kit rewrites them to this app's aliases.`,
5395
+ fenced(`components/screens/${tsx.file}`, "tsx", tsx.contents),
5396
+ fenced(`components/screens/${data.file}`, "ts", data.contents),
5397
+ `Screen parts it imports (components/screens/parts/): ${partNames.join(", ") || "none"}`,
5398
+ `Kit components they import (components/ui/): ${components.join(", ") || "none"}`,
5399
+ `Call add_ui_kit with screens: ["${slug}"] to write it into the app.`
5400
+ ].join("\n\n")
5401
+ );
5402
+ }
5403
+ function screensArg(v) {
5404
+ if (v === void 0) return { ok: true, value: void 0, site: false };
5405
+ if (!Array.isArray(v) || !v.every((n) => typeof n === "string")) return { ok: false };
5406
+ const site = v.includes("site");
5407
+ const names = v.filter((n) => n !== "site");
5408
+ if (names.includes("all")) return { ok: true, value: "all", site };
5409
+ if (!names.every(isScreenName2)) return { ok: false };
5410
+ return { ok: true, value: names.length > 0 ? [...new Set(names)] : void 0, site };
5411
+ }
4371
5412
  async function addUiKit(args, ctx) {
4372
5413
  const { components, replace_existing: replace, no_blocks: noBlocks } = args;
4373
5414
  if (components !== void 0 && !(Array.isArray(components) && components.every((c) => typeof c === "string"))) {
@@ -4375,16 +5416,12 @@ async function addUiKit(args, ctx) {
4375
5416
  }
4376
5417
  if (replace !== void 0 && typeof replace !== "boolean") return errorResult('"replace_existing" must be true or false.');
4377
5418
  if (noBlocks !== void 0 && typeof noBlocks !== "boolean") return errorResult('"no_blocks" must be true or false.');
4378
- let target;
4379
- if (ctx.token !== null) {
4380
- const root = resolveProjectFolder(ctx.cwd, ctx.projectFolders === null ? null : { folders: ctx.projectFolders });
4381
- if (root === null) return errorResult(NOT_SURE_WHICH_FOLDER);
4382
- target = { root, token: ctx.token, api: ctx.api };
4383
- } else if (ctx.account) {
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);
5419
+ const screens = screensArg(args.screens);
5420
+ if (!screens.ok) return errorResult(SCREENS_ARG);
5421
+ const access = kitAccess(ctx);
5422
+ if (isResult2(access)) return access;
5423
+ const root = ctx.token !== null ? resolveProjectFolder(ctx.cwd, ctx.projectFolders === null ? null : { folders: ctx.projectFolders }) : ctx.account.folder;
5424
+ if (root === null) return errorResult(NOT_SURE_WHICH_FOLDER);
4388
5425
  const questions = {
4389
5426
  pickComponents: async (all) => all,
4390
5427
  confirmReplace: async (paths) => {
@@ -4397,7 +5434,17 @@ async function addUiKit(args, ctx) {
4397
5434
  const exec = (cmd, cmdArgs, opts) => ctx.exec(cmd, cmdArgs, { ...opts, timeoutMs: MCP_EXEC_TIMEOUT_MS });
4398
5435
  try {
4399
5436
  const result = await runAdd(
4400
- { ...target, components: components ?? [], skipInstall: false, blocks: noBlocks !== true },
5437
+ {
5438
+ ...access,
5439
+ root,
5440
+ components: components ?? [],
5441
+ skipInstall: false,
5442
+ blocks: noBlocks !== true,
5443
+ ...screens.value !== void 0 ? { screens: screens.value } : {},
5444
+ ...screens.site ? { site: true } : {},
5445
+ // As a bare CLI rerun: a call naming neither components nor screens refreshes the screens an earlier run wrote.
5446
+ refreshScreens: true
5447
+ },
4401
5448
  { fetchImpl: ctx.fetchImpl, exec, questions, progress: (line) => progress.push(line) }
4402
5449
  );
4403
5450
  const written = result.added.filter((n) => n !== "preview-portal");
@@ -4411,7 +5458,7 @@ async function addUiKit(args, ctx) {
4411
5458
  );
4412
5459
  } catch (e) {
4413
5460
  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);
5461
+ 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 NoPagesPulledError ? NO_PAGES_PULLED_FOR_AGENT(e) : e instanceof Error ? e.message : String(e);
4415
5462
  const tail = e instanceof StepError && e.outputTail ? ["Last output:", e.outputTail] : [];
4416
5463
  return errorResult([...progress, message, ...tail].join("\n"));
4417
5464
  }
@@ -4534,15 +5581,31 @@ ${blocks.sources[f] ?? ""}`);
4534
5581
  ${files.join("\n\n")}`);
4535
5582
  }
4536
5583
  },
5584
+ {
5585
+ name: "list_screens",
5586
+ 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). Marketing pages (home, pricing, waitlist) are listed too; they mount on their own routes inside the site shell (add_ui_kit with screens including "site"). Follow with get_screen_source, or write them into the app with add_ui_kit and screens.',
5587
+ inputSchema: NO_INPUT,
5588
+ annotations: READ_ONLY,
5589
+ run: (snapshot) => listScreens(snapshot)
5590
+ },
5591
+ {
5592
+ name: "get_screen_source",
5593
+ 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.",
5594
+ inputSchema: { type: "object", properties: { screen: { type: "string", description: "A screen name from list_screens." } }, required: ["screen"], additionalProperties: false },
5595
+ annotations: READ_ONLY,
5596
+ needsSnapshot: false,
5597
+ run: (_snapshot, _at, args, ctx) => getScreenSource(args, ctx)
5598
+ },
4537
5599
  {
4538
5600
  name: "add_ui_kit",
4539
- 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 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. Changes files in the project, so your client will ask the user first. Never overwrites components the user edited.",
5601
+ 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 and marketing pages with the parts and components they import; you mount each on a route. Add "site" to screens to write the site menu (header and footer) that pages mount inside, at least one page being pulled with it. Changes files in the project, so your client will ask the user first. Never overwrites components or screens the user edited.`,
4540
5602
  inputSchema: {
4541
5603
  type: "object",
4542
5604
  properties: {
4543
5605
  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
5606
  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." }
5607
+ 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." },
5608
+ screens: { type: "array", items: { type: "string" }, description: `Screen names from list_screens, or ["all"] for every screen; "site" adds the site menu for marketing pages. Each is written under the components folder's screens/ with the parts and kit components it imports.` }
4546
5609
  },
4547
5610
  additionalProperties: false
4548
5611
  },
@@ -4634,24 +5697,28 @@ var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4634
5697
  var isStringRecord = (v) => isObject2(v) && Object.values(v).every((x) => typeof x === "string");
4635
5698
  var isStringListRecord = (v) => isObject2(v) && Object.values(v).every((x) => Array.isArray(x) && x.every((s) => typeof s === "string"));
4636
5699
  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");
5700
+ 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) || isPageKind(v.kind)) && typeof v.updatedAt === "string";
5701
+ var isScreenIndex = (v) => Array.isArray(v) && v.every(isScreenRow) && new Set(v.map((r) => r.slug)).size === v.length;
4637
5702
  function validateSnapshot(json) {
4638
5703
  if (!isObject2(json)) throw malformed4();
4639
5704
  if (typeof json.version !== "number") throw malformed4();
4640
5705
  if (json.version !== 1) throw new CliError(UPDATE_MESSAGE);
4641
- const { project, canonical, cssVars, shadcnTheme, kit, mockup, blocks, guide } = json;
5706
+ const { project, canonical, cssVars, shadcnTheme, kit, mockup, blocks, screens, guide } = json;
4642
5707
  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
5708
  if (!isObject2(canonical) || !Array.isArray(canonical.tokens) || !canonical.tokens.every(isObject2)) throw malformed4();
4644
5709
  if (typeof cssVars !== "string" || typeof shadcnTheme !== "string" || typeof guide !== "string") throw malformed4();
4645
5710
  if (!isObject2(kit) || !isStringRecord(kit.sources) || !isStringListRecord(kit.variables)) throw malformed4();
4646
5711
  if (mockup !== null && !(isObject2(mockup) && isObject2(mockup.spec) && isStringRecord(mockup.renderer))) throw malformed4();
5712
+ const out = { ...json };
5713
+ if (screens !== void 0 && !isScreenIndex(screens)) out.screens = void 0;
4647
5714
  const validBlocks = isObject2(blocks) && Array.isArray(blocks.index) && blocks.index.every(isBlockEntry) && isStringRecord(blocks.sources);
4648
- if (!validBlocks) return { ...json, blocks: void 0 };
4649
- if (blocks.header !== void 0 && typeof blocks.header !== "string") return { ...json, blocks: { ...blocks, header: void 0 } };
4650
- return json;
5715
+ if (!validBlocks) out.blocks = void 0;
5716
+ else if (blocks.header !== void 0 && typeof blocks.header !== "string") out.blocks = { ...blocks, header: void 0 };
5717
+ return out;
4651
5718
  }
4652
5719
  async function fetchSnapshot(opts, fetchImpl = fetch) {
4653
5720
  const { api, token, path = "/api/snapshot", messages } = opts;
4654
- return validateSnapshot(await getJson({ api, token, path, ...messages ? { messages } : {} }, fetchImpl));
5721
+ return validateSnapshot(await getJson({ api, token, path: `${path}?pages=1`, ...messages ? { messages } : {} }, fetchImpl));
4655
5722
  }
4656
5723
  var STALE_RETRY_MS = 15e3;
4657
5724
  var servesStale = (e) => !(e instanceof ApiError) || e.status === null || e.status >= 500;
@@ -4774,7 +5841,7 @@ ${resolved.message}`,
4774
5841
  }
4775
5842
  return res;
4776
5843
  });
4777
- return { token: null, projectFolders: null, api: current.api, cwd, account: current, fetchImpl, exec: spawnExec };
5844
+ return { token: null, projectFolders: null, api: current.api, cwd, account: current, fetchImpl, exec: spawnExec, dropSnapshot: () => cache.clear() };
4778
5845
  };
4779
5846
  const session = () => projectPath ? projectSession() : accountSession();
4780
5847
  const cache = createSnapshotCache(async () => {