designsource 0.10.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +3 -1
  2. package/dist/index.js +835 -440
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -21,7 +21,7 @@ var CliError = class extends Error {
21
21
  };
22
22
  var CANCELLED = "Cancelled.";
23
23
  var TOKEN_MESSAGE = "Project token not recognised. In the workbench open Project settings and copy the project token.";
24
- var MCP_TOKEN_REQUIRED = "A project token is required: pass --token or set DS_SYNC_TOKEN (workbench \u2192 Project settings).";
24
+ var MCP_TOKEN_REQUIRED = "designsource has no project token or sign-in here. Ask the user to run npx designsource login in a terminal in the project folder, then restart this app. The server runs on this computer over stdio; there is no web address to connect to instead.";
25
25
  var UNREACHABLE = (api) => `Could not reach ${api}.`;
26
26
  var UPDATE_MESSAGE = "This design system needs a newer designsource CLI. Update it (for example `npx designsource@latest`) and run again.";
27
27
  var PLAN_MESSAGE = "This project's account is on the free plan. Exports need Pro: https://designsource.app/pricing";
@@ -119,9 +119,9 @@ function resolveAlias(alias, tsconfig) {
119
119
  best = { prefixLength: prefix.length, resolved: star === -1 ? target : target.replace("*", () => rest) };
120
120
  }
121
121
  if (!best) throw noAlias(alias);
122
- const relative5 = posix.normalize(posix.join(tsconfig.baseUrl, best.resolved));
123
- if (relative5 === ".." || relative5.startsWith("../") || posix.isAbsolute(relative5)) throw outside(alias);
124
- return relative5 === "." ? "" : relative5;
122
+ const relative6 = posix.normalize(posix.join(tsconfig.baseUrl, best.resolved));
123
+ if (relative6 === ".." || relative6.startsWith("../") || posix.isAbsolute(relative6)) throw outside(alias);
124
+ return relative6 === "." ? "" : relative6;
125
125
  }
126
126
  function resolveTargets(root, shadcn) {
127
127
  const { aliases, tailwind } = shadcn ?? {};
@@ -993,7 +993,7 @@ function planToml(path, text, projectId) {
993
993
 
994
994
  // src/add/screen-rules.ts
995
995
  var SCREEN_SLUG = /^[a-z][a-z0-9-]{0,39}$/;
996
- var RESERVED_SCREEN_SLUGS = ["all", "shell", "app-shell", "parts"];
996
+ var RESERVED_SCREEN_SLUGS = ["all", "shell", "app-shell", "parts", "app", "design-system", "api", "site"];
997
997
  var SCREEN_COMPONENT = /^[A-Z][A-Za-z0-9]*Screen$/;
998
998
  var SCREEN_PART_FILE = /^[a-z][a-z0-9-]*\.tsx?$/;
999
999
  var SCREENS_QUERY_MAX = 50;
@@ -1038,7 +1038,7 @@ ${TOKEN_LINE}
1038
1038
  ${API_LINE}
1039
1039
  --force overwrite files the bundle writes when design-system/ already exists
1040
1040
  `;
1041
- var ADD_USAGE = `designsource add [names\u2026] [--yes] [--all] [--force] [--skip-install] [--no-blocks] [--screen <name>|all|shell] [--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>]
1042
1042
 
1043
1043
  Adds your design system's UI kit to the React app in this folder: the theme in its global stylesheet, the
1044
1044
  components and the libraries they import. Sets up Tailwind and the shadcn config when the app has none.
@@ -1051,8 +1051,9 @@ your components, blocks and sample pages.
1051
1051
  --force replace component files add did not write, and edited ones
1052
1052
  --skip-install write the files, then print the install command instead of running it
1053
1053
  --no-blocks the /design-system section without its blocks and their libraries (blocks already there stay)
1054
- --screen screens from DS source, by file name (repeatable, or comma-separated); all for every one; shell for
1055
- a sidebar app shell listing the screens in the app
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
1056
1057
  --token the project token (workbench \u2192 Project settings); or DS_SYNC_TOKEN
1057
1058
  --api API origin (default ${DEFAULT_API_ORIGIN})
1058
1059
  `;
@@ -1177,8 +1178,8 @@ var SCREEN_NAME_MESSAGE = "--screen takes screen names from DS source (letters,
1177
1178
  function screensIn(values, usage) {
1178
1179
  const words = values.flatMap((v) => v.split(",").map((w) => w.trim()));
1179
1180
  if (words.some((n) => n === "")) throw new ArgsError(SCREEN_NAME_MESSAGE, usage);
1180
- const shell = words.includes("shell") ? { shell: true } : {};
1181
- const names = words.filter((n) => n !== "shell");
1181
+ const shell = { ...words.includes("shell") ? { shell: true } : {}, ...words.includes("site") ? { site: true } : {} };
1182
+ const names = words.filter((n) => n !== "shell" && n !== "site");
1182
1183
  if (names.includes("all")) return { screens: "all", ...shell };
1183
1184
  for (const n of names) {
1184
1185
  if (!SCREEN_SLUG.test(n) || RESERVED_SCREEN_SLUGS.includes(n)) throw new ArgsError(SCREEN_NAME_MESSAGE, usage);
@@ -1369,14 +1370,14 @@ function quoteArg(arg) {
1369
1370
  function childEnv(env) {
1370
1371
  return Object.fromEntries(Object.entries(env).filter(([name]) => name.toUpperCase() !== "DS_SYNC_TOKEN"));
1371
1372
  }
1372
- var spawnExec = (cmd, args, { cwd, timeoutMs, input, stdoutOnly }) => new Promise((resolve8) => {
1373
+ var spawnExec = (cmd, args, { cwd, timeoutMs, input, stdoutOnly }) => new Promise((resolve9) => {
1373
1374
  let output = "";
1374
1375
  let child;
1375
1376
  try {
1376
1377
  const shell = process.platform === "win32";
1377
1378
  child = spawn(cmd, shell ? args.map(quoteArg) : args, { cwd, env: childEnv(process.env), stdio: [input === void 0 ? "ignore" : "pipe", "pipe", "pipe"], shell });
1378
1379
  } catch (e) {
1379
- resolve8({ code: 127, output: e instanceof Error ? e.message : String(e) });
1380
+ resolve9({ code: 127, output: e instanceof Error ? e.message : String(e) });
1380
1381
  return;
1381
1382
  }
1382
1383
  let timedOut = false;
@@ -1386,7 +1387,7 @@ var spawnExec = (cmd, args, { cwd, timeoutMs, input, stdoutOnly }) => new Promis
1386
1387
  }, timeoutMs);
1387
1388
  const done = (result) => {
1388
1389
  if (timer) clearTimeout(timer);
1389
- resolve8(timedOut ? { code: result.code === 0 ? 124 : result.code, output: `${result.output.trimEnd()}
1390
+ resolve9(timedOut ? { code: result.code === 0 ? 124 : result.code, output: `${result.output.trimEnd()}
1390
1391
  timed out after ${timeoutMs / 1e3}s` } : result);
1391
1392
  };
1392
1393
  child.stdout?.on("data", (chunk) => {
@@ -1502,6 +1503,11 @@ import { join as join4 } from "node:path";
1502
1503
 
1503
1504
  // src/add/screen-gen.ts
1504
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);
1505
1511
  var SCREEN_KIND_ICON_NAMES = {
1506
1512
  list: "ListDetailsIcon",
1507
1513
  detail: "UserIcon",
@@ -1522,7 +1528,7 @@ function checkShellScreens(screens) {
1522
1528
  if (RESERVED_SCREEN_SLUGS.includes(s.slug)) throw new Error("Reserved screen slug");
1523
1529
  if (seen.has(s.slug)) throw new Error("Duplicate screen slug");
1524
1530
  seen.add(s.slug);
1525
- if (!SCREEN_KINDS.includes(s.kind)) throw new Error("Unknown screen kind");
1531
+ if (typeof s.kind !== "string" || !SCREEN_KINDS.includes(s.kind) && !isPageKind(s.kind)) throw new Error("Unknown screen kind");
1526
1532
  if (typeof s.title !== "string") throw new Error("Invalid screen title");
1527
1533
  }
1528
1534
  }
@@ -1531,7 +1537,11 @@ function assembleAppShell(input) {
1531
1537
  if (typeof input.name !== "string") throw new Error("Invalid app name");
1532
1538
  if (input.hrefFor !== "app" && input.hrefFor !== "root") throw new Error("Invalid hrefFor");
1533
1539
  const prefix = input.hrefFor === "app" ? "/app/" : "/";
1534
- const links = input.screens.map((s) => ({ href: `${prefix}${s.slug}`, title: s.title, kind: s.kind }));
1540
+ const screenLinks = input.screenLinks === true;
1541
+ const screenHrefs = Object.fromEntries(
1542
+ input.screens.map((s) => [s.slug, !isPageKind(s.kind) ? `${prefix}${s.slug}` : s.kind === "home" ? "/" : `/${s.slug}`])
1543
+ );
1544
+ const links = input.screens.filter(isAppScreen).map((s) => ({ href: `${prefix}${s.slug}`, title: s.title, kind: s.kind }));
1535
1545
  const icons = [...new Set(SCREEN_KINDS.map((k) => SCREEN_KIND_ICON_NAMES[k]))].sort();
1536
1546
  const kindIcons = SCREEN_KINDS.map((k) => ` ${k}: ${SCREEN_KIND_ICON_NAMES[k]},`);
1537
1547
  return [
@@ -1552,6 +1562,7 @@ function assembleAppShell(input) {
1552
1562
  " SidebarProvider,",
1553
1563
  " SidebarTrigger,",
1554
1564
  "} from '@/components/ui/sidebar'",
1565
+ ...screenLinks ? ["import { ScreenLinksProvider, type ScreenLinks } from '@/components/screens/parts/screen-links'"] : [],
1555
1566
  "",
1556
1567
  `type ScreenKind = ${SCREEN_KINDS.map((k) => `'${k}'`).join(" | ")}`,
1557
1568
  "type ShellLink = { href: string; title: string; kind: ScreenKind }",
@@ -1560,6 +1571,7 @@ function assembleAppShell(input) {
1560
1571
  "",
1561
1572
  `const SCREENS: ShellLink[] = ${jsonLiteral(links, 2)}`,
1562
1573
  "",
1574
+ ...screenLinks ? [`const SCREEN_LINKS: ScreenLinks = ${jsonLiteral({ strict: true, hrefs: screenHrefs }, 2)}`, ""] : [],
1563
1575
  "const KIND_ICONS: Record<ScreenKind, IconComponent> = {",
1564
1576
  ...kindIcons,
1565
1577
  "}",
@@ -1612,7 +1624,13 @@ function assembleAppShell(input) {
1612
1624
  ' <header className="flex h-12 shrink-0 items-center gap-2 border-b px-4 @[40rem]/stage:px-6">',
1613
1625
  ' <SidebarTrigger className="-ml-1" />',
1614
1626
  " </header>",
1615
- ' <div className="flex flex-1 flex-col">{children}</div>',
1627
+ ...screenLinks ? [
1628
+ ' <div className="flex flex-1 flex-col">',
1629
+ " <ScreenLinksProvider value={SCREEN_LINKS}>",
1630
+ " {children}",
1631
+ " </ScreenLinksProvider>",
1632
+ " </div>"
1633
+ ] : [' <div className="flex flex-1 flex-col">{children}</div>'],
1616
1634
  " </SidebarInset>",
1617
1635
  " </SidebarProvider>",
1618
1636
  " </div>",
@@ -1625,15 +1643,23 @@ function assembleAppShell(input) {
1625
1643
  }
1626
1644
  var DEFAULT_SCREENS_IMPORT = "@/components/screens";
1627
1645
  var SCREENS_IMPORT = /^[A-Za-z0-9@~#_.-]+(?:\/[A-Za-z0-9@~#_.-]+)*$/;
1646
+ var HREF_BASE = /^(?:\/|#\/)(?:[A-Za-z0-9_-]+\/)*$/;
1628
1647
  var HEAD = [
1629
- `export type SectionScreenKind = ${SCREEN_KINDS.map((k) => `'${k}'`).join(" | ")}`,
1648
+ `export type SectionScreenKind = ${[...SCREEN_KINDS, ...PAGE_KINDS].map((k) => `'${k}'`).join(" | ")}`,
1630
1649
  "export type SectionScreenEntry = { slug: string; title: string; kind: SectionScreenKind }"
1631
1650
  ];
1632
1651
  function assembleScreenRegistry(input) {
1633
1652
  checkShellScreens(input.screens);
1634
1653
  const screensImport = input.screensImport ?? DEFAULT_SCREENS_IMPORT;
1635
1654
  if (typeof screensImport !== "string" || !SCREENS_IMPORT.test(screensImport)) throw new Error("Invalid screensImport");
1655
+ if (typeof input.name !== "string") throw new Error("Invalid site name");
1656
+ if (!Number.isInteger(input.year)) throw new Error("Invalid year");
1657
+ if (input.action !== void 0 && typeof input.action !== "string") throw new Error("Invalid action label");
1658
+ const base = input.screenHrefBase;
1659
+ if (base !== void 0 && (typeof base !== "string" || !HREF_BASE.test(base))) throw new Error("Invalid screenHrefBase");
1636
1660
  const entries = input.screens.map((s) => ({ slug: s.slug, title: s.title, kind: s.kind }));
1661
+ const pages = entries.flatMap((s) => isPageKind(s.kind) ? [{ slug: s.slug, title: s.title, kind: s.kind }] : []);
1662
+ const site = siteFrameProps({ name: input.name, pages, year: input.year, fallbackActionLabel: input.action });
1637
1663
  if (entries.length === 0) {
1638
1664
  return [
1639
1665
  ...HEAD,
@@ -1651,8 +1677,45 @@ function assembleScreenRegistry(input) {
1651
1677
  const views = entries.map(
1652
1678
  (s) => ` ${jsonLiteral(s.slug)}: lazy(() => import(${jsonLiteral(`${screensImport}/${s.slug}`)}).then((m) => ({ default: m.${screenComponentName(s.slug)} }))),`
1653
1679
  );
1680
+ const linksImport = base === void 0 ? [] : [`import { ScreenLinksProvider } from '${screensImport}/parts/screen-links'`];
1681
+ const linksConst = base === void 0 ? [] : [
1682
+ `const SCREEN_LINKS = ${jsonLiteral({ strict: true, hrefs: Object.fromEntries(entries.map((s) => [s.slug, `${base}${s.slug}`])) }, 2)}`,
1683
+ ""
1684
+ ];
1685
+ const wrap = (indent, inner) => base === void 0 ? inner : [`${indent}<ScreenLinksProvider value={SCREEN_LINKS}>`, ...inner.map((l) => ` ${l}`), `${indent}</ScreenLinksProvider>`];
1686
+ if (pages.length === 0) {
1687
+ return [
1688
+ "import { lazy, Suspense, type ComponentType } from 'react'",
1689
+ ...linksImport,
1690
+ "",
1691
+ ...HEAD,
1692
+ "",
1693
+ `export const SECTION_SCREENS: SectionScreenEntry[] = ${jsonLiteral(entries, 2)}`,
1694
+ "",
1695
+ "const VIEWS: Record<string, ComponentType> = {",
1696
+ ...views,
1697
+ "}",
1698
+ "",
1699
+ ...linksConst,
1700
+ "export function SectionScreen({ slug }: { slug: string }) {",
1701
+ " const View = Object.prototype.hasOwnProperty.call(VIEWS, slug) ? VIEWS[slug] : undefined",
1702
+ " if (!View) return null",
1703
+ " return (",
1704
+ " <Suspense fallback={null}>",
1705
+ ...wrap(" ", [" <View />"]),
1706
+ " </Suspense>",
1707
+ " )",
1708
+ "}",
1709
+ "",
1710
+ "SectionScreen.displayName = 'SectionScreen'",
1711
+ ""
1712
+ ].join("\n");
1713
+ }
1654
1714
  return [
1655
- "import { lazy, Suspense, type ComponentType } from 'react'",
1715
+ "import { lazy, Suspense, type ComponentProps, type ComponentType } from 'react'",
1716
+ `import { SiteFrame, SiteHeader, SiteFooter } from '${screensImport}/parts/site-frame'`,
1717
+ `import { SiteLinksProvider } from '${screensImport}/parts/site-links'`,
1718
+ ...linksImport,
1656
1719
  "",
1657
1720
  ...HEAD,
1658
1721
  "",
@@ -1662,12 +1725,36 @@ function assembleScreenRegistry(input) {
1662
1725
  ...views,
1663
1726
  "}",
1664
1727
  "",
1728
+ "/** The marketing pages: drawn inside the site menu and footer, their links inert, since the section is a showcase. */",
1729
+ `const PAGES: ReadonlySet<string> = new Set(${jsonLiteral(pages.map((p) => p.slug))})`,
1730
+ "",
1731
+ "type SiteProps = {",
1732
+ " hrefs: ComponentProps<typeof SiteLinksProvider>['value']['hrefs']",
1733
+ " header: ComponentProps<typeof SiteHeader>",
1734
+ " footer: ComponentProps<typeof SiteFooter>",
1735
+ "}",
1736
+ "",
1737
+ `const SITE: SiteProps = ${jsonLiteral(site, 2)}`,
1738
+ "",
1739
+ ...linksConst,
1665
1740
  "export function SectionScreen({ slug }: { slug: string }) {",
1666
1741
  " const View = Object.prototype.hasOwnProperty.call(VIEWS, slug) ? VIEWS[slug] : undefined",
1667
1742
  " if (!View) return null",
1668
1743
  " return (",
1669
1744
  " <Suspense fallback={null}>",
1670
- " <View />",
1745
+ ...wrap(" ", [
1746
+ " {PAGES.has(slug) ? (",
1747
+ " <SiteLinksProvider value={{ hrefs: SITE.hrefs, inert: true }}>",
1748
+ " <SiteFrame>",
1749
+ " <SiteHeader {...SITE.header} />",
1750
+ " <View />",
1751
+ " <SiteFooter {...SITE.footer} />",
1752
+ " </SiteFrame>",
1753
+ " </SiteLinksProvider>",
1754
+ " ) : (",
1755
+ " <View />",
1756
+ " )}"
1757
+ ]),
1671
1758
  " </Suspense>",
1672
1759
  " )",
1673
1760
  "}",
@@ -1676,6 +1763,88 @@ function assembleScreenRegistry(input) {
1676
1763
  ""
1677
1764
  ].join("\n");
1678
1765
  }
1766
+ function checkSitePages(pages) {
1767
+ const kinds = /* @__PURE__ */ new Set();
1768
+ for (const p of pages) {
1769
+ if (typeof p.slug !== "string" || !SCREEN_SLUG.test(p.slug)) throw new Error("Invalid page slug");
1770
+ if (RESERVED_SCREEN_SLUGS.includes(p.slug)) throw new Error("Reserved page slug");
1771
+ if (typeof p.kind !== "string" || !isPageKind(p.kind)) throw new Error("Unknown page kind");
1772
+ if (kinds.has(p.kind)) throw new Error("Duplicate page kind");
1773
+ kinds.add(p.kind);
1774
+ if (typeof p.title !== "string") throw new Error("Invalid page title");
1775
+ }
1776
+ }
1777
+ var inKindOrder = (pages) => PAGE_KINDS.flatMap((k) => pages.filter((p) => p.kind === k));
1778
+ function siteFrameProps(input) {
1779
+ checkSitePages(input.pages);
1780
+ const ordered = inKindOrder(input.pages);
1781
+ const hrefs = {};
1782
+ for (const p of ordered) hrefs[p.kind] = p.kind === "home" ? "/" : `/${p.slug}`;
1783
+ const action = ordered.some((p) => p.kind === "waitlist") ? { label: "Join the waitlist", variant: "default", to: "waitlist" } : { label: input.fallbackActionLabel ?? "Get started", variant: "default" };
1784
+ return {
1785
+ hrefs,
1786
+ header: {
1787
+ name: input.name,
1788
+ links: ordered.filter((p) => p.kind !== "home" && p.kind !== "waitlist").map((p) => ({ label: p.title, to: p.kind })),
1789
+ action
1790
+ },
1791
+ footer: { name: input.name, links: ordered.map((p) => ({ label: p.title, to: p.kind })), year: input.year }
1792
+ };
1793
+ }
1794
+ function assembleSiteShell(input) {
1795
+ checkSitePages(input.pages);
1796
+ if (typeof input.name !== "string") throw new Error("Invalid site name");
1797
+ if (!Number.isInteger(input.year)) throw new Error("Invalid year");
1798
+ if (input.fallbackActionLabel !== void 0 && typeof input.fallbackActionLabel !== "string") throw new Error("Invalid action label");
1799
+ const appBase = input.appBase;
1800
+ if (appBase !== void 0 && appBase !== "/app/" && appBase !== "/") throw new Error("Invalid appBase");
1801
+ const { hrefs, header, footer } = siteFrameProps({
1802
+ name: input.name,
1803
+ pages: input.pages,
1804
+ year: input.year,
1805
+ fallbackActionLabel: input.fallbackActionLabel
1806
+ });
1807
+ const linked = appBase !== void 0;
1808
+ const appScreens = linked ? (input.screens ?? []).filter((s) => !isPageKind(s.kind)) : [];
1809
+ if (linked) checkShellScreens([...input.pages, ...appScreens]);
1810
+ const screenHrefs = Object.fromEntries([
1811
+ ...input.pages.map((p) => [p.slug, p.kind === "home" ? "/" : `/${p.slug}`]),
1812
+ ...appScreens.map((s) => [s.slug, `${appBase}${s.slug}`])
1813
+ ]);
1814
+ const frame = [
1815
+ " <SiteLinksProvider value={{ hrefs }}>",
1816
+ " <SiteFrame>",
1817
+ " <SiteHeader {...header} />",
1818
+ " {children}",
1819
+ " <SiteFooter {...footer} />",
1820
+ " </SiteFrame>",
1821
+ " </SiteLinksProvider>"
1822
+ ];
1823
+ return [
1824
+ "'use client'",
1825
+ "",
1826
+ "import type { ComponentProps } from 'react'",
1827
+ "import { SiteFrame, SiteHeader, SiteFooter } from '@/components/screens/parts/site-frame'",
1828
+ "import { SiteLinksProvider } from '@/components/screens/parts/site-links'",
1829
+ ...linked ? ["import { ScreenLinksProvider, type ScreenLinks } from '@/components/screens/parts/screen-links'"] : [],
1830
+ "",
1831
+ `const hrefs: ComponentProps<typeof SiteLinksProvider>['value']['hrefs'] = ${jsonLiteral(hrefs, 2)}`,
1832
+ "",
1833
+ `const header: ComponentProps<typeof SiteHeader> = ${jsonLiteral(header, 2)}`,
1834
+ "",
1835
+ `const footer: ComponentProps<typeof SiteFooter> = ${jsonLiteral(footer, 2)}`,
1836
+ "",
1837
+ ...linked ? [`const screenLinks: ScreenLinks = ${jsonLiteral({ strict: true, hrefs: screenHrefs }, 2)}`, ""] : [],
1838
+ "export function SiteShell({ children }: { children: React.ReactNode }) {",
1839
+ " return (",
1840
+ ...linked ? [" <ScreenLinksProvider value={screenLinks}>", ...frame.map((l) => ` ${l}`), " </ScreenLinksProvider>"] : frame,
1841
+ " )",
1842
+ "}",
1843
+ "",
1844
+ "SiteShell.displayName = 'SiteShell'",
1845
+ ""
1846
+ ].join("\n");
1847
+ }
1679
1848
 
1680
1849
  // src/add/section.ts
1681
1850
  var SECTION_NEEDS_FULL_KIT = "The /design-system section comes with the full kit: run designsource add --all.";
@@ -1697,8 +1866,14 @@ function sectionReadsScreens(root, t) {
1697
1866
  }
1698
1867
  }
1699
1868
  var registryPath = (componentsDir) => join22(componentsDir, "design-system/section-screens.tsx");
1700
- function registryFile(componentsDir, t, screens) {
1701
- return stamped(registryPath(componentsDir), REGISTRY_STAMP, rewriteForApp(assembleScreenRegistry({ screens }), t));
1869
+ function registrySite(manifest, year = (/* @__PURE__ */ new Date()).getUTCFullYear()) {
1870
+ const action = manifest.screenIndex?.find((e) => e.kind === "home")?.action;
1871
+ return { name: manifest.name, year, ...typeof action === "string" ? { action } : {} };
1872
+ }
1873
+ var SECTION_SCREENS_BASE = "/design-system/screens/";
1874
+ function registryFile(componentsDir, t, screens, site, links = null) {
1875
+ const screenHrefBase = links === null ? void 0 : links.framework === "vite" ? "#/screens/" : SECTION_SCREENS_BASE;
1876
+ return stamped(registryPath(componentsDir), REGISTRY_STAMP, rewriteForApp(assembleScreenRegistry({ screens, ...site, ...screenHrefBase !== void 0 ? { screenHrefBase } : {} }), t));
1702
1877
  }
1703
1878
  function shownBlockGroups(groups, blocks, keptBlockIds = []) {
1704
1879
  if (blocks === "write") return groups;
@@ -1756,7 +1931,7 @@ function planSectionFiles(input) {
1756
1931
  }
1757
1932
  if (blocks === "skip") files.push(stamped(ds("block-view.tsx"), "section:block-view", NO_BLOCKS_VIEW));
1758
1933
  const screens = sectionKnowsScreens(manifest);
1759
- if (screens && input.screens !== null) files.push(registryFile(componentsDir, t, input.screens));
1934
+ if (screens && input.screens !== null) files.push(registryFile(componentsDir, t, input.screens, registrySite(manifest), input.screenLinks ? { framework: input.framework } : null));
1760
1935
  else if (screens && !input.registryOnDisk) {
1761
1936
  const fallback = section.files.find((f) => f.key === REGISTRY_KEY);
1762
1937
  files.push(stamped(registryPath(componentsDir), REGISTRY_STAMP, rewriteForApp(fallback.contents, t)));
@@ -2358,92 +2533,9 @@ async function postNdjson(opts, fetchImpl = fetch) {
2358
2533
  }
2359
2534
  }
2360
2535
 
2361
- // src/add/kit-manifest.ts
2362
- var malformed = () => new CliError("Unexpected response from the API \u2014 not a kit manifest.");
2363
- var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2364
- var isStrings = (v) => Array.isArray(v) && v.every((s) => typeof s === "string");
2365
- var isStringMap = (v) => isRecord(v) && Object.values(v).every((s) => typeof s === "string");
2366
- var isSectionFile = (f) => isRecord(f) && typeof f.key === "string" && typeof f.contents === "string" && isStrings(f.kitImports) && isStrings(f.packages) && typeof f.block === "boolean";
2367
- 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");
2368
- function validateSection(s) {
2369
- if (!isRecord(s) || !Array.isArray(s.files) || !s.files.every(isSectionFile)) throw malformed();
2370
- if (typeof s.themeCss !== "string" || !Array.isArray(s.blockGroups) || !s.blockGroups.every(isBlockGroup)) throw malformed();
2371
- if (!isStringMap(s.packages) || !isStringMap(s.blockPackages)) throw malformed();
2372
- return { files: s.files, themeCss: s.themeCss, blockGroups: s.blockGroups, packages: s.packages, blockPackages: s.blockPackages, mockupSpec: s.mockupSpec ?? null };
2373
- }
2374
- var isScreen = (s) => {
2375
- if (!isRecord(s) || typeof s.slug !== "string" || !SCREEN_SLUG.test(s.slug) || typeof s.title !== "string") return false;
2376
- if (typeof s.component !== "string" || !SCREEN_COMPONENT.test(s.component) || !isStrings(s.parts)) return false;
2377
- if (!Array.isArray(s.files) || s.files.length !== 2) return false;
2378
- if (!s.files.every((f) => isRecord(f) && typeof f.file === "string" && typeof f.contents === "string")) return false;
2379
- return s.files[0].file === `${s.slug}.tsx` && s.files[1].file === `${s.slug}.data.ts`;
2380
- };
2381
- var isScreenPart = (p) => isRecord(p) && typeof p.name === "string" && typeof p.file === "string" && SCREEN_PART_FILE.test(p.file) && p.file.replace(/\.tsx?$/, "") === p.name && typeof p.contents === "string" && isStrings(p.kitImports) && isStrings(p.partImports) && isStrings(p.packages);
2382
- var isScreenEntry = (e) => isRecord(e) && typeof e.slug === "string" && SCREEN_SLUG.test(e.slug) && !RESERVED_SCREEN_SLUGS.includes(e.slug) && typeof e.title === "string" && typeof e.available === "boolean" && (e.kind === void 0 || typeof e.kind === "string" && SCREEN_KINDS.includes(e.kind));
2383
- function validateKitManifest(json) {
2384
- if (!isRecord(json)) throw malformed();
2385
- if (typeof json.version !== "number") throw malformed();
2386
- if (json.version !== 1) throw new CliError(UPDATE_MESSAGE);
2387
- if (json.kind !== "kit" || typeof json.name !== "string" || typeof json.utils !== "string") throw malformed();
2388
- const { theme } = json;
2389
- if (!isRecord(theme) || typeof theme.css !== "string" || !isStrings(theme.fontImports)) throw malformed();
2390
- if (!Array.isArray(json.components)) throw malformed();
2391
- for (const c of json.components) {
2392
- if (!isRecord(c)) throw malformed();
2393
- if (typeof c.name !== "string" || typeof c.file !== "string" || typeof c.contents !== "string") throw malformed();
2394
- if (!isStrings(c.kitImports) || !isStrings(c.packages)) throw malformed();
2395
- }
2396
- if (!isStrings(json.utilsPackages)) throw malformed();
2397
- if (!isStringMap(json.packages) || !isStringMap(json.devPackages)) throw malformed();
2398
- const section = json.section === void 0 ? void 0 : validateSection(json.section);
2399
- const { screens, screenParts, screenIndex } = json;
2400
- if (screens !== void 0 && !(Array.isArray(screens) && screens.every(isScreen))) throw malformed();
2401
- if (screenParts !== void 0 && !(Array.isArray(screenParts) && screenParts.every(isScreenPart))) throw malformed();
2402
- if (screenIndex !== void 0 && !(Array.isArray(screenIndex) && screenIndex.every(isScreenEntry))) throw malformed();
2403
- if (screens !== void 0) {
2404
- const slugs = /* @__PURE__ */ new Set();
2405
- for (const s of screens) {
2406
- if (RESERVED_SCREEN_SLUGS.includes(s.slug) || slugs.has(s.slug)) throw malformed();
2407
- slugs.add(s.slug);
2408
- }
2409
- }
2410
- if (screenParts !== void 0) {
2411
- const names = /* @__PURE__ */ new Set();
2412
- for (const p of screenParts) {
2413
- if (names.has(p.name)) throw malformed();
2414
- names.add(p.name);
2415
- }
2416
- for (const s of screens ?? []) if (s.parts.some((n) => !names.has(n))) throw malformed();
2417
- } else if ((screens ?? []).some((s) => s.parts.length > 0)) throw malformed();
2418
- return {
2419
- version: 1,
2420
- kind: "kit",
2421
- name: json.name,
2422
- theme: { css: theme.css, fontImports: theme.fontImports },
2423
- components: json.components,
2424
- utils: json.utils,
2425
- utilsPackages: json.utilsPackages,
2426
- packages: json.packages,
2427
- devPackages: json.devPackages,
2428
- ...section ? { section } : {},
2429
- ...screens !== void 0 ? { screens } : {},
2430
- ...screenParts !== void 0 ? { screenParts } : {},
2431
- ...screenIndex !== void 0 ? { screenIndex: screenIndex.map((e) => ({ slug: e.slug, title: e.title, available: e.available, kind: e.kind ?? "list" })) } : {}
2432
- };
2433
- }
2434
-
2435
- // src/add/fetch-kit.ts
2436
- async function fetchKit(opts, fetchImpl = fetch) {
2437
- const { api, token, screens, messages } = opts;
2438
- const asAll = screens === "all" || Array.isArray(screens) && (screens.includes("all") || new Set(screens).size > SCREENS_QUERY_MAX);
2439
- const query = screens === void 0 || Array.isArray(screens) && screens.length === 0 ? "" : `?screens=${encodeURIComponent(asAll ? "all" : screens.join(","))}`;
2440
- const path = `${opts.path ?? "/api/kit"}${query}`;
2441
- return validateKitManifest(await getJson({ api, token, path, ...messages ? { messages } : {} }, fetchImpl));
2442
- }
2443
-
2444
2536
  // src/connect/open-browser.ts
2445
2537
  import { spawn as spawn2 } from "node:child_process";
2446
- var launchDetached = (cmd, args) => new Promise((resolve8) => {
2538
+ var launchDetached = (cmd, args) => new Promise((resolve9) => {
2447
2539
  try {
2448
2540
  const child = spawn2(cmd, args, {
2449
2541
  shell: false,
@@ -2451,13 +2543,13 @@ var launchDetached = (cmd, args) => new Promise((resolve8) => {
2451
2543
  detached: true,
2452
2544
  windowsHide: true
2453
2545
  });
2454
- child.once("error", () => resolve8(false));
2546
+ child.once("error", () => resolve9(false));
2455
2547
  child.once("spawn", () => {
2456
2548
  child.unref();
2457
- resolve8(true);
2549
+ resolve9(true);
2458
2550
  });
2459
2551
  } catch {
2460
- resolve8(false);
2552
+ resolve9(false);
2461
2553
  }
2462
2554
  });
2463
2555
  function deviceUrl(api) {
@@ -2498,8 +2590,8 @@ function clientName(hostname2) {
2498
2590
  const host = hostname2.replace(/[^A-Za-z0-9 '._-]/g, "-") || "this computer";
2499
2591
  return `designsource on ${host}`.slice(0, CLIENT_NAME_MAX).trimEnd();
2500
2592
  }
2501
- var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2502
- var errorCode = (body) => isRecord2(body) && typeof body.error === "string" ? body.error : null;
2593
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2594
+ var errorCode = (body) => isRecord(body) && typeof body.error === "string" ? body.error : null;
2503
2595
  function seconds(value, fallback, min, max) {
2504
2596
  const ms = typeof value === "number" && Number.isFinite(value) ? value * 1e3 : fallback;
2505
2597
  return Math.min(max, Math.max(min, ms));
@@ -2511,7 +2603,7 @@ async function deviceLogin(opts) {
2511
2603
  if (code2.status === 429) throw new CliError("Too many sign-in attempts from this network. Wait a while and run npx designsource login again.");
2512
2604
  if (code2.status !== 200) throw new CliError(`${api} answered ${code2.status}.`);
2513
2605
  const body = code2.body;
2514
- if (!isRecord2(body) || typeof body.deviceCode !== "string" || !DEVICE_CODE.test(body.deviceCode) || typeof body.userCode !== "string" || !USER_CODE.test(body.userCode)) {
2606
+ if (!isRecord(body) || typeof body.deviceCode !== "string" || !DEVICE_CODE.test(body.deviceCode) || typeof body.userCode !== "string" || !USER_CODE.test(body.userCode)) {
2515
2607
  throw new CliError(UNEXPECTED);
2516
2608
  }
2517
2609
  const deviceCode = body.deviceCode;
@@ -2540,14 +2632,97 @@ async function deviceLogin(opts) {
2540
2632
  }
2541
2633
  }
2542
2634
  function accepted(body) {
2543
- if (!isRecord2(body) || typeof body.accessToken !== "string" || !ACCOUNT_TOKEN.test(body.accessToken)) throw new CliError("Unexpected account token from the API.");
2635
+ if (!isRecord(body) || typeof body.accessToken !== "string" || !ACCOUNT_TOKEN.test(body.accessToken)) throw new CliError("Unexpected account token from the API.");
2544
2636
  const account = body.account;
2545
- if (!isRecord2(account) || typeof account.email !== "string") throw new CliError(UNEXPECTED);
2637
+ if (!isRecord(account) || typeof account.email !== "string") throw new CliError(UNEXPECTED);
2546
2638
  const email = printable(account.email).slice(0, EMAIL_MAX);
2547
2639
  if (email === "") throw new CliError(UNEXPECTED);
2548
2640
  return { token: body.accessToken, email };
2549
2641
  }
2550
2642
 
2643
+ // src/add/kit-manifest.ts
2644
+ var malformed = () => new CliError("Unexpected response from the API \u2014 not a kit manifest.");
2645
+ var isRecord2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2646
+ var isStrings = (v) => Array.isArray(v) && v.every((s) => typeof s === "string");
2647
+ var isStringMap = (v) => isRecord2(v) && Object.values(v).every((s) => typeof s === "string");
2648
+ var isSectionFile = (f) => isRecord2(f) && typeof f.key === "string" && typeof f.contents === "string" && isStrings(f.kitImports) && isStrings(f.packages) && typeof f.block === "boolean";
2649
+ 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");
2650
+ function validateSection(s) {
2651
+ if (!isRecord2(s) || !Array.isArray(s.files) || !s.files.every(isSectionFile)) throw malformed();
2652
+ if (typeof s.themeCss !== "string" || !Array.isArray(s.blockGroups) || !s.blockGroups.every(isBlockGroup)) throw malformed();
2653
+ if (!isStringMap(s.packages) || !isStringMap(s.blockPackages)) throw malformed();
2654
+ return { files: s.files, themeCss: s.themeCss, blockGroups: s.blockGroups, packages: s.packages, blockPackages: s.blockPackages, mockupSpec: s.mockupSpec ?? null };
2655
+ }
2656
+ var isScreen = (s) => {
2657
+ if (!isRecord2(s) || typeof s.slug !== "string" || !SCREEN_SLUG.test(s.slug) || typeof s.title !== "string") return false;
2658
+ if (typeof s.component !== "string" || !SCREEN_COMPONENT.test(s.component) || !isStrings(s.parts)) return false;
2659
+ if (!Array.isArray(s.files) || s.files.length !== 2) return false;
2660
+ if (!s.files.every((f) => isRecord2(f) && typeof f.file === "string" && typeof f.contents === "string")) return false;
2661
+ return s.files[0].file === `${s.slug}.tsx` && s.files[1].file === `${s.slug}.data.ts`;
2662
+ };
2663
+ 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);
2664
+ 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);
2665
+ function validateKitManifest(json) {
2666
+ if (!isRecord2(json)) throw malformed();
2667
+ if (typeof json.version !== "number") throw malformed();
2668
+ if (json.version !== 1) throw new CliError(UPDATE_MESSAGE);
2669
+ if (json.kind !== "kit" || typeof json.name !== "string" || typeof json.utils !== "string") throw malformed();
2670
+ const { theme } = json;
2671
+ if (!isRecord2(theme) || typeof theme.css !== "string" || !isStrings(theme.fontImports)) throw malformed();
2672
+ if (!Array.isArray(json.components)) throw malformed();
2673
+ for (const c of json.components) {
2674
+ if (!isRecord2(c)) throw malformed();
2675
+ if (typeof c.name !== "string" || typeof c.file !== "string" || typeof c.contents !== "string") throw malformed();
2676
+ if (!isStrings(c.kitImports) || !isStrings(c.packages)) throw malformed();
2677
+ }
2678
+ if (!isStrings(json.utilsPackages)) throw malformed();
2679
+ if (!isStringMap(json.packages) || !isStringMap(json.devPackages)) throw malformed();
2680
+ const section = json.section === void 0 ? void 0 : validateSection(json.section);
2681
+ const { screens, screenParts, screenIndex } = json;
2682
+ if (screens !== void 0 && !(Array.isArray(screens) && screens.every(isScreen))) throw malformed();
2683
+ if (screenParts !== void 0 && !(Array.isArray(screenParts) && screenParts.every(isScreenPart))) throw malformed();
2684
+ if (screenIndex !== void 0 && !(Array.isArray(screenIndex) && screenIndex.every(isScreenEntry))) throw malformed();
2685
+ if (screens !== void 0) {
2686
+ const slugs = /* @__PURE__ */ new Set();
2687
+ for (const s of screens) {
2688
+ if (RESERVED_SCREEN_SLUGS.includes(s.slug) || slugs.has(s.slug)) throw malformed();
2689
+ slugs.add(s.slug);
2690
+ }
2691
+ }
2692
+ if (screenParts !== void 0) {
2693
+ const names = /* @__PURE__ */ new Set();
2694
+ for (const p of screenParts) {
2695
+ if (names.has(p.name)) throw malformed();
2696
+ names.add(p.name);
2697
+ }
2698
+ for (const s of screens ?? []) if (s.parts.some((n) => !names.has(n))) throw malformed();
2699
+ } else if ((screens ?? []).some((s) => s.parts.length > 0)) throw malformed();
2700
+ return {
2701
+ version: 1,
2702
+ kind: "kit",
2703
+ name: json.name,
2704
+ theme: { css: theme.css, fontImports: theme.fontImports },
2705
+ components: json.components,
2706
+ utils: json.utils,
2707
+ utilsPackages: json.utilsPackages,
2708
+ packages: json.packages,
2709
+ devPackages: json.devPackages,
2710
+ ...section ? { section } : {},
2711
+ ...screens !== void 0 ? { screens } : {},
2712
+ ...screenParts !== void 0 ? { screenParts } : {},
2713
+ ...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 } : {} })) } : {}
2714
+ };
2715
+ }
2716
+
2717
+ // src/add/fetch-kit.ts
2718
+ async function fetchKit(opts, fetchImpl = fetch) {
2719
+ const { api, token, screens, messages } = opts;
2720
+ const asAll = screens === "all" || Array.isArray(screens) && (screens.includes("all") || new Set(screens).size > SCREENS_QUERY_MAX);
2721
+ const query = screens === void 0 || Array.isArray(screens) && screens.length === 0 ? "" : `?screens=${encodeURIComponent(asAll ? "all" : screens.join(","))}`;
2722
+ const path = `${opts.path ?? "/api/kit"}${query}${query === "" ? "?" : "&"}pages=1`;
2723
+ return validateKitManifest(await getJson({ api, token, path, ...messages ? { messages } : {} }, fetchImpl));
2724
+ }
2725
+
2551
2726
  // src/add/plan-packages.ts
2552
2727
  function componentClosure(picked, manifest) {
2553
2728
  const byName = new Map(manifest.components.map((c) => [c.name, c]));
@@ -2617,8 +2792,13 @@ var SCREEN_PART_EDITED = (slug, part) => `Skipped screen "${slug}": you edited s
2617
2792
  var SCREEN_PAIR_EDITED = (slug, editedPath) => `Skipped screen "${slug}": you edited ${editedPath} and the kit has since changed the file beside it, so they would no longer fit together. Run again with --force to replace both.`;
2618
2793
  var SCREEN_PART_EDITED_FOR_AGENT = (slug, part) => `Skipped screen "${slug}": the user edited screens/parts/${part} and the kit's version has changed since. Tell the user; they can replace it by running npx designsource add --force themselves.`;
2619
2794
  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.`;
2795
+ 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.`;
2796
+ 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.`;
2620
2797
  var SHELL_FILE = "app-shell.tsx";
2621
2798
  var SHELL_STAMP = "screen:shell";
2799
+ var SITE_FILE = "site-shell.tsx";
2800
+ var SITE_STAMP = "screen:site";
2801
+ var SITE_PART_NAMES = ["site-frame", "site-links"];
2622
2802
  function stampAt(root, path) {
2623
2803
  const abs = resolveInside(root, path);
2624
2804
  if (!existsSync8(abs)) return null;
@@ -2650,11 +2830,12 @@ var stampsIn = (root, dir, ext) => {
2650
2830
  return found;
2651
2831
  };
2652
2832
  function screensOnDisk(root, t) {
2653
- const out = { slugs: [], parts: /* @__PURE__ */ new Map(), shell: false };
2833
+ const out = { slugs: [], parts: /* @__PURE__ */ new Map(), shell: false, site: false };
2654
2834
  if (t.componentsDir === null) return out;
2655
2835
  const dir = `${t.componentsDir}/screens`;
2656
2836
  for (const s of stampsIn(root, dir, /\.tsx$/)) {
2657
2837
  if (s.name === SHELL_STAMP) out.shell ||= s.path === `${dir}/${SHELL_FILE}`;
2838
+ else if (s.name === SITE_STAMP) out.site ||= s.path === `${dir}/${SITE_FILE}`;
2658
2839
  else if (s.name.startsWith("screen:") && !s.name.endsWith(".data")) out.slugs.push(s.name.slice("screen:".length));
2659
2840
  }
2660
2841
  for (const p of stampsIn(root, `${dir}/parts`, /\.tsx?$/)) {
@@ -2674,6 +2855,10 @@ function closureOf(names, byName) {
2674
2855
  names.forEach(visit);
2675
2856
  return [...seen.values()];
2676
2857
  }
2858
+ function sitePartsOf(manifest) {
2859
+ const byName = new Map((manifest.screenParts ?? []).map((p) => [p.name, p]));
2860
+ return byName.has("site-frame") ? closureOf(SITE_PART_NAMES.filter((n) => byName.has(n)), byName) : [];
2861
+ }
2677
2862
  function screenPartsOf(screen, manifest) {
2678
2863
  return closureOf(screen.parts, new Map((manifest.screenParts ?? []).map((p) => [p.name, p])));
2679
2864
  }
@@ -2683,15 +2868,20 @@ function planScreenFiles(a) {
2683
2868
  const dir = `${t.componentsDir}/screens`;
2684
2869
  const byName = new Map((manifest.screenParts ?? []).map((p) => [p.name, p]));
2685
2870
  const disk = screensOnDisk(root, t);
2686
- const plan = { write: [], edited: [], foreign: [], skipped: [], gone: [], kitComponents: [], added: [] };
2871
+ const plan = { write: [], edited: [], foreign: [], skipped: [], gone: [], kitComponents: [], added: [], siteParts: [], siteSkipped: null };
2687
2872
  const rewritten = (p) => rewriteForApp(p.contents, t);
2873
+ const editedAndChanged = (p) => {
2874
+ const on = disk.parts.get(p.name);
2875
+ return on !== void 0 && on.edited && on.hash !== hashOf(rewritten(p));
2876
+ };
2688
2877
  const written = [];
2878
+ const kindOf = new Map((manifest.screenIndex ?? []).map((e) => [e.slug, e.kind]));
2689
2879
  for (const screen of (manifest.screens ?? []).filter((s) => wanted.includes(s.slug))) {
2690
- const parts = closureOf(screen.parts, byName);
2691
- const blocker = force ? void 0 : parts.find((p) => {
2692
- const on = disk.parts.get(p.name);
2693
- return on !== void 0 && on.edited && on.hash !== hashOf(rewritten(p));
2694
- });
2880
+ const page = isPageKind(kindOf.get(screen.slug) ?? "");
2881
+ const withFrame = page && byName.has("site-frame");
2882
+ const roots = [...screen.parts, ...withFrame ? ["site-frame"] : [], ...byName.has("screen-links") ? ["screen-links"] : []];
2883
+ const parts = closureOf(roots, byName);
2884
+ const blocker = force ? void 0 : parts.find(editedAndChanged);
2695
2885
  if (blocker) {
2696
2886
  plan.skipped.push({ slug: screen.slug, reason: SCREEN_PART_EDITED(screen.slug, blocker.file), agentReason: SCREEN_PART_EDITED_FOR_AGENT(screen.slug, blocker.file) });
2697
2887
  continue;
@@ -2709,7 +2899,7 @@ function planScreenFiles(a) {
2709
2899
  continue;
2710
2900
  }
2711
2901
  const kept = force ? files : files.filter((f, i) => !(f.current && files[1 - i].edited));
2712
- written.push({ slug: screen.slug, component: screen.component, parts, files: kept });
2902
+ written.push({ slug: screen.slug, component: screen.component, page, parts, files: kept });
2713
2903
  }
2714
2904
  const push = (path, name, contents, component, screen) => {
2715
2905
  const abs = resolveInside(root, path);
@@ -2719,21 +2909,31 @@ function planScreenFiles(a) {
2719
2909
  else if (status === "edited") plan.edited.push(path);
2720
2910
  };
2721
2911
  const partsDone = /* @__PURE__ */ new Set();
2912
+ const pushPart = (p) => {
2913
+ if (partsDone.has(p.name)) return;
2914
+ partsDone.add(p.name);
2915
+ const on = disk.parts.get(p.name);
2916
+ if (force || !(on && on.edited)) push(`${dir}/parts/${p.file}`, `screen-part:${p.name}`, p.contents, p.name);
2917
+ };
2722
2918
  for (const s of written) {
2723
2919
  for (const f of s.files) {
2724
2920
  const name = f.file.endsWith(".data.ts") ? `screen:${s.slug}.data` : `screen:${s.slug}`;
2725
2921
  push(`${dir}/${f.file}`, name, f.contents, s.slug, s.slug);
2726
2922
  }
2727
- plan.added.push({ slug: s.slug, component: s.component, importPath: `${t.componentsAlias}/screens/${s.slug}` });
2728
- for (const p of s.parts) {
2729
- if (partsDone.has(p.name)) continue;
2730
- partsDone.add(p.name);
2731
- const on = disk.parts.get(p.name);
2732
- if (force || !(on && on.edited)) push(`${dir}/parts/${p.file}`, `screen-part:${p.name}`, p.contents, p.name);
2923
+ plan.added.push({ slug: s.slug, component: s.component, importPath: `${t.componentsAlias}/screens/${s.slug}`, ...s.page ? { page: true } : {} });
2924
+ s.parts.forEach(pushPart);
2925
+ }
2926
+ if (a.site) {
2927
+ const parts = sitePartsOf(manifest);
2928
+ const blocker = force ? void 0 : parts.find(editedAndChanged);
2929
+ if (blocker) plan.siteSkipped = { reason: SITE_PART_EDITED(blocker.file), agentReason: SITE_PART_EDITED_FOR_AGENT(blocker.file) };
2930
+ else {
2931
+ plan.siteParts = parts;
2932
+ parts.forEach(pushPart);
2733
2933
  }
2734
2934
  }
2735
2935
  const kitComponents = /* @__PURE__ */ new Set();
2736
- for (const s of written) for (const p of s.parts) for (const k of p.kitImports) kitComponents.add(k);
2936
+ for (const p of [...written.flatMap((s) => s.parts), ...plan.siteParts]) for (const k of p.kitImports) kitComponents.add(k);
2737
2937
  plan.kitComponents = [...kitComponents].sort();
2738
2938
  const inIndex = new Set((manifest.screenIndex ?? []).map((e) => e.slug));
2739
2939
  plan.gone = manifest.screenIndex === void 0 ? [] : disk.slugs.filter((s) => !inIndex.has(s));
@@ -2751,9 +2951,44 @@ function planShellFile(a) {
2751
2951
  const { targets: t } = a;
2752
2952
  if (t.componentsDir === null) throw new CliError(SCREENS_NEED_COMPONENTS_DIR(t.componentsAlias));
2753
2953
  const path = `${t.componentsDir}/screens/${SHELL_FILE}`;
2754
- const contents = stampContents(SHELL_STAMP, rewriteForApp(assembleAppShell({ name: a.name, screens: a.screens, hrefFor: "root" }), t));
2954
+ const source = assembleAppShell({ name: a.name, screens: a.screens, hrefFor: "root", ...a.screenLinks === true ? { screenLinks: true } : {} });
2955
+ const contents = stampContents(SHELL_STAMP, rewriteForApp(source, t));
2755
2956
  return { path, contents, status: existingFileStatus(resolveInside(a.root, path)), importPath: `${t.componentsAlias}/screens/app-shell` };
2756
2957
  }
2958
+ function sitePagesFor(slugs, index) {
2959
+ const bySlug = new Map((index ?? []).map((e) => [e.slug, e]));
2960
+ const kinds = /* @__PURE__ */ new Set();
2961
+ const pages = [];
2962
+ const valid = [...new Set(slugs)].filter((s) => SCREEN_SLUG.test(s) && !RESERVED_SCREEN_SLUGS.includes(s));
2963
+ for (const slug of valid.sort((a, b) => a < b ? -1 : a > b ? 1 : 0)) {
2964
+ const e = bySlug.get(slug);
2965
+ if (!e || !isPageKind(e.kind) || kinds.has(e.kind)) continue;
2966
+ kinds.add(e.kind);
2967
+ pages.push({ slug, title: e.title, kind: e.kind });
2968
+ }
2969
+ return pages;
2970
+ }
2971
+ function screenLinksPresent(root, t, manifest, disk, written) {
2972
+ const part = (manifest.screenParts ?? []).find((p) => p.name === "screen-links");
2973
+ if (!part) return false;
2974
+ if (written.some((w) => w.path.endsWith("/parts/screen-links.tsx"))) return true;
2975
+ const on = disk.parts.get("screen-links");
2976
+ return on !== void 0 && !on.edited && on.hash === hashOf(rewriteForApp(part.contents, t));
2977
+ }
2978
+ function planSiteFile(a) {
2979
+ const { targets: t } = a;
2980
+ if (t.componentsDir === null) throw new CliError(SCREENS_NEED_COMPONENTS_DIR(t.componentsAlias));
2981
+ const path = `${t.componentsDir}/screens/${SITE_FILE}`;
2982
+ const source = assembleSiteShell({
2983
+ name: a.name,
2984
+ pages: a.pages,
2985
+ year: a.year,
2986
+ ...a.action !== void 0 ? { fallbackActionLabel: a.action } : {},
2987
+ ...a.screens !== void 0 ? { appBase: "/", screens: a.screens } : {}
2988
+ });
2989
+ const contents = stampContents(SITE_STAMP, rewriteForApp(source, t));
2990
+ return { path, contents, status: existingFileStatus(resolveInside(a.root, path)), importPath: `${t.componentsAlias}/screens/site-shell` };
2991
+ }
2757
2992
 
2758
2993
  // src/add/css-blocks.ts
2759
2994
  var isSpace = (c) => c === " " || c === " " || c === "\n" || c === "\r" || c === "\f";
@@ -3101,8 +3336,24 @@ var SHELL_EMPTY = "The app shell lists no screens yet: each one you add with des
3101
3336
  var SHELL_EMPTY_FOR_AGENT = "The app shell lists no screens yet: call add_ui_kit with screens to pull some first; each one joins its menu.";
3102
3337
  var SHELL_COMPONENTS = ["sidebar", "icons"];
3103
3338
  var SHELL_SKIPPED = (reason) => `Skipped the app shell: ${reason}.`;
3339
+ var SITE_SKIPPED = (reason) => `Skipped the site menu: ${reason}.`;
3104
3340
  var SHELL_NOT_IN_KIT = (name) => `the kit from this DS source server has no ${name}`;
3105
3341
  var NO_SCREENS_YET = (project) => `${printable(project)} has no screens yet. Make one in the Screens view of the workbench.`;
3342
+ 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.`;
3343
+ 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`}`;
3344
+ var PAGE_SKIPPED_NO_SITE = (skipLine) => `${skipLine} The site menu links only the pages in this app, so it was not written either.`;
3345
+ var screenSkipText = (slug, reason) => reason.startsWith("Skipped screen ") ? reason : `Skipped screen "${slug}": ${reason}`;
3346
+ var NoPagesPulledError = class extends CliError {
3347
+ constructor(project, page, skip) {
3348
+ super(skip ? PAGE_SKIPPED_NO_SITE(screenSkipText(skip.slug, skip.reason)) : NO_PAGES_PULLED(project, page));
3349
+ this.project = project;
3350
+ this.page = page;
3351
+ this.skip = skip;
3352
+ }
3353
+ project;
3354
+ page;
3355
+ skip;
3356
+ };
3106
3357
  var UNKNOWN_SCREENS_SHOWN = 10;
3107
3358
  var UNKNOWN_SCREENS = (names, index, project) => {
3108
3359
  const head = `No screen${names.length === 1 ? "" : "s"} named ${names.map((n) => `"${printable(n)}"`).join(", ")} in ${printable(project)}.`;
@@ -3178,14 +3429,16 @@ async function chooseComponents(input, manifest, before, sectionOnDisk, question
3178
3429
  }
3179
3430
  function screensQuery(input, disk) {
3180
3431
  if (input.screens !== void 0) return input.screens === "all" || input.screens.length > 0 ? input.screens : void 0;
3181
- if (!input.shell && (!input.refreshScreens || input.components.length > 0)) return void 0;
3432
+ if (!input.shell && !input.site && (!input.refreshScreens || input.components.length > 0)) return void 0;
3182
3433
  const slugs = disk.slugs.filter((s) => SCREEN_SLUG.test(s) && !RESERVED_SCREEN_SLUGS.includes(s));
3183
- return slugs.length > 0 ? slugs : void 0;
3434
+ if (slugs.length > 0) return slugs;
3435
+ return input.site ? "all" : void 0;
3184
3436
  }
3185
3437
  function screenConflict(slug, manifest, appDeps) {
3186
3438
  const screen = manifest.screens?.find((s) => s.slug === slug);
3187
- if (!screen) return null;
3188
- const parts = screenPartsOf(screen, manifest);
3439
+ return screen ? partsConflict(screenPartsOf(screen, manifest), manifest, appDeps) : null;
3440
+ }
3441
+ function partsConflict(parts, manifest, appDeps) {
3189
3442
  const byName = new Map(manifest.components.map((c) => [c.name, c]));
3190
3443
  const components = componentClosure(parts.flatMap((p) => p.kitImports).filter((n) => byName.has(n)), manifest);
3191
3444
  for (const pkg of [...parts.flatMap((p) => p.packages), ...components.flatMap((n) => byName.get(n)?.packages ?? [])]) {
@@ -3198,12 +3451,14 @@ function screenConflict(slug, manifest, appDeps) {
3198
3451
  return null;
3199
3452
  }
3200
3453
  function screenInstalls(slugs, manifest, appDeps) {
3454
+ const screens = (manifest.screens ?? []).filter((s) => slugs.includes(s.slug));
3455
+ return partInstalls(screens.flatMap((s) => screenPartsOf(s, manifest)), manifest, appDeps);
3456
+ }
3457
+ function partInstalls(parts, manifest, appDeps) {
3201
3458
  const install = {};
3202
- for (const screen of (manifest.screens ?? []).filter((s) => slugs.includes(s.slug))) {
3203
- for (const pkg of screenPartsOf(screen, manifest).flatMap((p) => p.packages)) {
3204
- const need = manifest.packages[pkg];
3205
- if (need !== void 0 && appDeps[pkg] === void 0) install[pkg] = need;
3206
- }
3459
+ for (const pkg of parts.flatMap((p) => p.packages)) {
3460
+ const need = manifest.packages[pkg];
3461
+ if (need !== void 0 && appDeps[pkg] === void 0) install[pkg] = need;
3207
3462
  }
3208
3463
  return install;
3209
3464
  }
@@ -3238,7 +3493,7 @@ function sectionDecision(input) {
3238
3493
  const blocks = !input.present ? input.blocksWanted ? "write" : "skip" : input.blocksOnDisk ? input.blocksWanted ? "write" : "keep" : "skip";
3239
3494
  return { write: true, blocks, note: null };
3240
3495
  }
3241
- function planSection(root, input, info, t, manifest, chosen, onDisk, screens) {
3496
+ function planSection(root, input, info, t, manifest, chosen, onDisk, screens, screenLinks) {
3242
3497
  const none = (note) => ({ decision: { write: false, blocks: "skip", note }, files: () => [], paths: [], packages: {}, blockCount: 0 });
3243
3498
  const section = manifest.section;
3244
3499
  if (!section) return none(null);
@@ -3254,7 +3509,7 @@ function planSection(root, input, info, t, manifest, chosen, onDisk, screens) {
3254
3509
  const framework = info.framework === "vite" ? "vite" : "next";
3255
3510
  const srcDir = existsSync9(join5(root, "src")) ? "src" : "";
3256
3511
  const registryOnDisk = existsSync9(resolveInside(root, registryPath(t.componentsDir)));
3257
- const files = (darkMarker) => planSectionFiles({ framework, appDir, srcDir, targets: t, manifest, blocks: decision.blocks, keptBlockIds: blockIds, darkMarker, screens, registryOnDisk });
3512
+ const files = (darkMarker) => planSectionFiles({ framework, appDir, srcDir, targets: t, manifest, blocks: decision.blocks, keptBlockIds: blockIds, darkMarker, screens, registryOnDisk, screenLinks });
3258
3513
  return {
3259
3514
  decision,
3260
3515
  files,
@@ -3290,23 +3545,42 @@ async function runAdd(input, deps) {
3290
3545
  const disk = screensOnDisk(root, planned);
3291
3546
  const query = screensQuery(input, disk);
3292
3547
  const manifest = await fetchKit({ api: input.api, token: input.token, path: input.kitPath, messages: input.messages, screens: query }, deps.fetchImpl);
3293
- const shellAlone = input.shell === true && input.screens === void 0;
3294
- const screenSelection = query === void 0 ? null : shellAlone ? { wanted: [], skipped: [] } : selectScreens(query, input.screens !== void 0, manifest, info.deps);
3295
- const screenPlan = screenSelection === null ? null : planScreenFiles({ root, targets: planned, manifest, wanted: screenSelection.wanted, force: input.force });
3548
+ const indexOnly = (input.shell === true || input.site === true) && input.screens === void 0;
3549
+ if (input.site) {
3550
+ if (manifest.screenIndex === void 0) throw new CliError(SCREENS_NOT_SERVED);
3551
+ if (!manifest.screenIndex.some((e) => isPageKind(e.kind))) throw new CliError(NO_PAGES_YET(manifest.name));
3552
+ }
3553
+ const screenSelection = query === void 0 ? null : indexOnly ? { wanted: [], skipped: [] } : selectScreens(query, input.screens !== void 0, manifest, info.deps);
3296
3554
  const fetchedScreens = query !== void 0 && manifest.screenIndex !== void 0;
3297
- const screensAfter = shellScreensFor([...disk.slugs, ...(screenPlan?.added ?? []).map((a) => a.slug)], manifest.screenIndex);
3298
- const bareRerun = input.refreshScreens === true && input.components.length === 0 && input.screens === void 0 && !input.shell;
3555
+ const siteWanted = input.site === true || disk.site && fetchedScreens;
3556
+ const siteConflict = siteWanted ? partsConflict(sitePartsOf(manifest), manifest, info.deps) : null;
3557
+ const screenPlan = screenSelection === null ? null : planScreenFiles({ root, targets: planned, manifest, wanted: screenSelection.wanted, force: input.force, site: siteWanted && siteConflict === null });
3558
+ const slugsAfter = [...disk.slugs, ...(screenPlan?.added ?? []).map((a) => a.slug)];
3559
+ const screensAfter = shellScreensFor(slugsAfter, manifest.screenIndex);
3560
+ const sitePages = sitePagesFor(slugsAfter, manifest.screenIndex);
3561
+ if (input.site && sitePages.length === 0) {
3562
+ const pageSlugs = new Set(manifest.screenIndex.filter((e) => isPageKind(e.kind)).map((e) => e.slug));
3563
+ const namedSkip = [...screenSelection?.skipped ?? [], ...screenPlan?.skipped ?? []].find((k) => pageSlugs.has(k.slug)) ?? null;
3564
+ const first = manifest.screenIndex.find((e) => isPageKind(e.kind) && e.available);
3565
+ throw new NoPagesPulledError(manifest.name, first?.slug ?? null, namedSkip);
3566
+ }
3567
+ const bareRerun = input.refreshScreens === true && input.components.length === 0 && input.screens === void 0 && !input.shell && !input.site;
3299
3568
  const noScreensLeft = bareRerun && screensAfter.length === 0;
3300
3569
  const listScreens2 = fetchedScreens || noScreensLeft;
3301
3570
  const writeShell = input.shell === true || disk.shell && listScreens2;
3302
- const shellPlan = writeShell ? planShellFile({ root, targets: planned, name: manifest.name, screens: screensAfter }) : null;
3571
+ const screenLinks = screenLinksPresent(root, planned, manifest, disk, screenPlan?.write ?? []);
3572
+ const shellPlan = writeShell ? planShellFile({ root, targets: planned, name: manifest.name, screens: screensAfter, screenLinks }) : null;
3573
+ const siteSkipped = siteConflict !== null ? { reason: SITE_SKIPPED(siteConflict) } : screenPlan?.siteSkipped ?? null;
3574
+ const writeSite = (input.site === true || disk.site && listScreens2) && siteSkipped === null;
3575
+ const siteListed = noScreensLeft ? [] : sitePages;
3576
+ const sitePlan = writeSite ? planSiteFile({ root, targets: planned, pages: siteListed, ...registrySite(manifest), ...screenLinks ? { screens: noScreensLeft ? [] : screensAfter } : {} }) : null;
3303
3577
  const onDisk = sectionPresent(root, planned);
3304
- const screensOnly = (input.screens !== void 0 || input.shell === true) && input.components.length === 0 && !input.all && !onDisk.present;
3578
+ const screensOnly = (input.screens !== void 0 || input.shell === true || input.site === true) && input.components.length === 0 && !input.all && !onDisk.present;
3305
3579
  const chosen = await chooseComponents(input, manifest, previouslyAdded(root, planned), onDisk.present, deps.questions, {
3306
3580
  components: [...screenPlan?.kitComponents ?? [], ...shellPlan ? SHELL_COMPONENTS : []],
3307
3581
  only: screensOnly
3308
3582
  });
3309
- const section = planSection(root, input, info, planned, manifest, chosen, onDisk, listScreens2 ? screensAfter : null);
3583
+ const section = planSection(root, input, info, planned, manifest, chosen, onDisk, listScreens2 ? screensAfter : null, screenLinks);
3310
3584
  let packages = planPackages(chosen, manifest, info.deps);
3311
3585
  let sectionNote = screensOnly && section.decision.note === SECTION_NEEDS_FULL_KIT ? null : section.decision.note;
3312
3586
  let writeSection = section.decision.write;
@@ -3322,10 +3596,10 @@ async function runAdd(input, deps) {
3322
3596
  (name) => !manifest.components.some((c) => c.name === name) ? SHELL_NOT_IN_KIT(name) : packages.skipped.find((k) => k.name === name)?.reason ?? null
3323
3597
  ).find((r) => r !== null) ?? null;
3324
3598
  const shellToWrite = shellBlocker === null ? shellPlan : null;
3325
- const registryAlone = !writeSection && onDisk.present && fetchedScreens && (screenPlan?.write.length ?? 0) > 0 && planned.componentsDir !== null && sectionReadsScreens(root, planned) ? registryFile(planned.componentsDir, planned, screensAfter) : null;
3599
+ const registryAlone = !writeSection && onDisk.present && fetchedScreens && (screenPlan?.write.length ?? 0) > 0 && planned.componentsDir !== null && sectionReadsScreens(root, planned) ? registryFile(planned.componentsDir, planned, screensAfter, registrySite(manifest), screenLinks ? { framework: info.framework === "vite" ? "vite" : "next" } : null) : null;
3326
3600
  const plan = planFiles(root, planned, componentClosure(packages.components, manifest), manifest);
3327
3601
  const sectionStatus = [...writeSection ? section.paths : [], ...registryAlone ? [registryAlone.path] : []].filter((p) => !p.endsWith(".json")).map((p) => [p, existingFileStatus(resolveInside(root, p))]);
3328
- const shellStatus = shellToWrite ? [[shellToWrite.path, shellToWrite.status]] : [];
3602
+ const shellStatus = [...shellToWrite ? [shellToWrite] : [], ...sitePlan ? [sitePlan] : []].map((f) => [f.path, f.status]);
3329
3603
  const setup = planSetup(info, manifest, deps.exec);
3330
3604
  if (writeSection && info.framework === "vite") {
3331
3605
  try {
@@ -3367,13 +3641,14 @@ async function runAdd(input, deps) {
3367
3641
  if (writeSection && info.framework !== "vite" && !dark.known) sectionNote = UNKNOWN_DARK(dark.selector ?? "");
3368
3642
  const sectionWrites = [...writeSection ? section.files(dark.marker) : [], ...registryAlone ? [registryAlone] : []].filter((f) => !kept.includes(f.path));
3369
3643
  const shellWrite = shellToWrite && !kept.includes(shellToWrite.path) ? shellToWrite : null;
3644
+ const siteWrite = sitePlan && !kept.includes(sitePlan.path) ? sitePlan : null;
3370
3645
  const registryWritten = listScreens2 && planned.componentsDir !== null && sectionWrites.some((f) => f.path === registryPath(planned.componentsDir));
3371
3646
  const removeScaffolding = info.shadcn !== null || hasThemeRegion(sheet);
3372
3647
  const themed = applyTheme(sheet, manifest.theme, { preflight: setup.preflight, removeScaffolding });
3373
3648
  try {
3374
3649
  writeFiles(
3375
3650
  root,
3376
- [{ path: planned.cssFile, contents: themed.css }, ...[...writes, ...sectionWrites, ...screenWrites, ...shellWrite ? [shellWrite] : []].map(({ path, contents }) => ({ path, contents }))],
3651
+ [{ path: planned.cssFile, contents: themed.css }, ...[...writes, ...sectionWrites, ...screenWrites, ...shellWrite ? [shellWrite] : [], ...siteWrite ? [siteWrite] : []].map(({ path, contents }) => ({ path, contents }))],
3377
3652
  { force: true, created: false }
3378
3653
  );
3379
3654
  } catch (e) {
@@ -3388,7 +3663,12 @@ async function runAdd(input, deps) {
3388
3663
  const screensAdded = (screenPlan?.added ?? []).filter((a) => screenWrites.some((w) => w.screen === a.slug));
3389
3664
  if (screensAdded.length > 0) deps.progress(`Adding ${screensAdded.length} screen${screensAdded.length === 1 ? "" : "s"}\u2026 \u2713`);
3390
3665
  if (shellWrite) deps.progress("Adding the app shell\u2026 \u2713");
3391
- const install = { ...packages.install, ...screenInstalls((screenPlan?.added ?? []).map((s) => s.slug), manifest, info.deps) };
3666
+ if (siteWrite) deps.progress("Adding the site menu\u2026 \u2713");
3667
+ const install = {
3668
+ ...packages.install,
3669
+ ...screenInstalls((screenPlan?.added ?? []).map((s) => s.slug), manifest, info.deps),
3670
+ ...partInstalls(screenPlan?.siteParts ?? [], manifest, info.deps)
3671
+ };
3392
3672
  const reactIs = manifest.packages["react-is"];
3393
3673
  if ("recharts" in install && reactIs !== void 0 && info.deps["react-is"] === void 0) install["react-is"] = reactIs;
3394
3674
  const commands = installCommands(info, manifest, install);
@@ -3427,24 +3707,34 @@ async function runAdd(input, deps) {
3427
3707
  routeDir: info.framework === "next" ? nextAppDir(root) : null
3428
3708
  },
3429
3709
  screensView: registryWritten && screensAfter.length > 0 ? info.framework === "vite" ? "/design-system.html#/screens" : "/design-system/screens" : null,
3430
- shell: shellWrite ? { importPath: shellWrite.importPath, screens: screensAfter.length } : null,
3431
- shellNote: shellBlocker === null ? null : SHELL_SKIPPED(shellBlocker)
3710
+ // The app shell lists app screens alone: pages have the site menu.
3711
+ shell: shellWrite ? { importPath: shellWrite.importPath, screens: screensAfter.filter((s) => !isPageKind(s.kind)).length } : null,
3712
+ shellNote: shellBlocker === null ? null : SHELL_SKIPPED(shellBlocker),
3713
+ site: siteWrite ? { importPath: siteWrite.importPath, pages: siteListed.length } : null,
3714
+ siteSkipped,
3715
+ siteOnDisk: disk.site || siteWrite !== null
3432
3716
  };
3433
3717
  }
3434
3718
 
3435
3719
  // src/add/summary.ts
3436
3720
  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"}.`;
3437
3721
  var sectionNoteFor = (note, reader) => reader === "agent" && note === SECTION_NEEDS_FULL_KIT ? SECTION_NEEDS_FULL_KIT_FOR_AGENT : note;
3438
- var screenSkipLine = (s, reader) => {
3439
- const reason = reader === "agent" && s.agentReason ? s.agentReason : s.reason;
3440
- return reason.startsWith("Skipped screen ") ? reason : `Skipped screen "${s.slug}": ${reason}`;
3722
+ var screenSkipLine = (s, reader) => screenSkipText(s.slug, reader === "agent" && s.agentReason ? s.agentReason : s.reason);
3723
+ var GET_SITE_SHELL = {
3724
+ cli: "Get <SiteShell> with npx designsource add --screen site.",
3725
+ agent: 'Get <SiteShell>: call add_ui_kit with screens ["site"].'
3441
3726
  };
3442
- function screenLines(r, reader) {
3443
- const first = r.added[0];
3727
+ function screenLines(r, reader, siteOnDisk) {
3728
+ const first = r.added.find((s) => !s.page);
3444
3729
  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.`];
3730
+ const pages = !r.added.some((s) => s.page) ? [] : [
3731
+ 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.",
3732
+ ...siteOnDisk ? [] : [GET_SITE_SHELL[reader]]
3733
+ ];
3445
3734
  return [
3446
3735
  ...r.added.map((s) => `import { ${s.component} } from '${s.importPath}'`),
3447
3736
  ...mount,
3737
+ ...pages,
3448
3738
  ...r.kept.map((path) => `Kept your edits to ${path}`),
3449
3739
  ...r.skipped.map((skip) => screenSkipLine(skip, reader)),
3450
3740
  ...r.gone.map((slug) => `Screen "${printable(slug)}" is no longer in DS source; left it in place`)
@@ -3460,10 +3750,12 @@ function summaryLines(r, reader = "cli") {
3460
3750
  ...r.section?.blocksLeftInPlace ? [leftBlocksLine(r.section.blocks, reader)] : [],
3461
3751
  ...r.section ? [`Your design system: ${r.section.path}`] : [],
3462
3752
  ...r.sectionNote ? [sectionNoteFor(r.sectionNote, reader)] : [],
3463
- ...r.screens ? screenLines(r.screens, reader) : [],
3753
+ ...r.screens ? screenLines(r.screens, reader, r.siteOnDisk) : [],
3464
3754
  ...r.screensView ? [`Your screens: ${r.screensView}`] : [],
3465
3755
  ...r.shell ? [`import { AppShell } from '${r.shell.importPath}'`, ...r.shell.screens === 0 ? [reader === "agent" ? SHELL_EMPTY_FOR_AGENT : SHELL_EMPTY] : []] : [],
3466
3756
  ...r.shellNote ? [r.shellNote] : [],
3757
+ ...r.site ? [`import { SiteShell } from '${r.site.importPath}'`] : [],
3758
+ ...r.siteSkipped ? [reader === "agent" && r.siteSkipped.agentReason ? r.siteSkipped.agentReason : r.siteSkipped.reason] : [],
3467
3759
  `Done. Your components now use "${r.projectName}" from designsource.app.`,
3468
3760
  "Run it again any time to pull updates."
3469
3761
  ];
@@ -3550,10 +3842,10 @@ function nextLine() {
3550
3842
  if (line !== void 0) return Promise.resolve(line);
3551
3843
  if (closed) return Promise.reject(new CliError(EOF_MESSAGE));
3552
3844
  process.stdin.ref?.();
3553
- return new Promise((resolve8, reject) => waiting.push({
3845
+ return new Promise((resolve9, reject) => waiting.push({
3554
3846
  resolve: (line2) => {
3555
3847
  process.stdin.unref?.();
3556
- resolve8(line2);
3848
+ resolve9(line2);
3557
3849
  },
3558
3850
  reject: (err) => {
3559
3851
  process.stdin.unref?.();
@@ -3666,7 +3958,7 @@ function pickTty(question, options, start, stdin, stdout) {
3666
3958
  stdin.resume();
3667
3959
  stdout.write("\x1B[?25l");
3668
3960
  draw([question, ...rows()]);
3669
- return new Promise((resolve8, reject) => {
3961
+ return new Promise((resolve9, reject) => {
3670
3962
  const finish = (after) => {
3671
3963
  stdin.off("keypress", onKey);
3672
3964
  stdin.setRawMode(false);
@@ -3687,7 +3979,7 @@ function pickTty(question, options, start, stdin, stdout) {
3687
3979
  stdout.write(`\r\x1B[J${question} ${chosen.label}
3688
3980
  `);
3689
3981
  });
3690
- resolve8(chosen.value);
3982
+ resolve9(chosen.value);
3691
3983
  return;
3692
3984
  }
3693
3985
  if (key.name === "up" || str === "k") index = (index - 1 + n) % n;
@@ -3719,7 +4011,7 @@ function pickManyTty(question, options, preselected, stdin, stdout) {
3719
4011
  stdin.resume();
3720
4012
  stdout.write("\x1B[?25l");
3721
4013
  draw([head, ...rows()]);
3722
- return new Promise((resolve8, reject) => {
4014
+ return new Promise((resolve9, reject) => {
3723
4015
  const finish = (after) => {
3724
4016
  stdin.off("keypress", onKey);
3725
4017
  stdin.setRawMode(false);
@@ -3740,7 +4032,7 @@ function pickManyTty(question, options, preselected, stdin, stdout) {
3740
4032
  stdout.write(`\r\x1B[J${question} ${chosen.length > 0 ? chosen.map((o) => o.label).join(", ") : "none"}
3741
4033
  `);
3742
4034
  });
3743
- resolve8(chosen.map((o) => o.value));
4035
+ resolve9(chosen.map((o) => o.value));
3744
4036
  return;
3745
4037
  }
3746
4038
  if (key.name === "up" || str === "k") index = (index - 1 + n) % n;
@@ -3756,14 +4048,20 @@ function pickManyTty(question, options, preselected, stdin, stdout) {
3756
4048
  }
3757
4049
 
3758
4050
  // src/commands/scaffold.ts
3759
- import { resolve as resolve4 } from "node:path";
4051
+ import { resolve as resolve7 } from "node:path";
3760
4052
 
3761
4053
  // src/connect/resolve-token.ts
3762
4054
  import { homedir } from "node:os";
4055
+ import { join as join10, relative as relative4 } from "node:path";
4056
+
4057
+ // src/connect/account-store.ts
4058
+ import { createHash as createHash2 } from "node:crypto";
4059
+ import { readFileSync as readFileSync11, realpathSync as realpathSync2 } from "node:fs";
4060
+ import { dirname as dirname3, join as join7, parse, resolve as resolve4, sep as sep3 } from "node:path";
3763
4061
 
3764
4062
  // src/connect/store.ts
3765
4063
  import { randomBytes } from "node:crypto";
3766
- import { chmodSync, constants, copyFileSync, mkdirSync as mkdirSync2, readFileSync as readFileSync10, renameSync, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
4064
+ import { chmodSync, constants, copyFileSync, mkdirSync as mkdirSync2, readFileSync as readFileSync10, realpathSync, renameSync, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
3767
4065
  import { basename, dirname as dirname2, isAbsolute as isAbsolute2, join as join6, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
3768
4066
  var WHERE = ["keychain", "secret-service", "dpapi", "file"];
3769
4067
  function credentialsPath(env, platform, home) {
@@ -3850,6 +4148,16 @@ function isWithin(folder, root) {
3850
4148
  const rel = relative2(root, folder);
3851
4149
  return rel === "" || rel !== ".." && !rel.startsWith(`..${sep2}`) && !isAbsolute2(rel);
3852
4150
  }
4151
+ function real(path) {
4152
+ try {
4153
+ return realpathSync(path);
4154
+ } catch {
4155
+ return resolve3(path);
4156
+ }
4157
+ }
4158
+ function savedHolds(folder, saved) {
4159
+ return isWithin(resolve3(folder), resolve3(saved)) || isWithin(real(folder), real(saved));
4160
+ }
3853
4161
  function createStore(opts) {
3854
4162
  const { env, platform, exec, home } = opts;
3855
4163
  const path = credentialsPath(env, platform, home);
@@ -3883,8 +4191,7 @@ function createStore(opts) {
3883
4191
  return osBackend(entry.where).get(projectId, entry.secret);
3884
4192
  },
3885
4193
  byFolder(folder) {
3886
- const target = resolve3(folder);
3887
- return Object.entries(readCredentials(path).projects).filter(([, e]) => e.folders.some((saved) => isWithin(target, resolve3(saved)))).map(([id, e]) => publicEntry(id, e));
4194
+ return Object.entries(readCredentials(path).projects).filter(([, e]) => e.folders.some((saved) => savedHolds(folder, saved))).map(([id, e]) => publicEntry(id, e));
3888
4195
  },
3889
4196
  entry(projectId) {
3890
4197
  const found = readCredentials(path).projects;
@@ -3915,24 +4222,271 @@ function createStore(opts) {
3915
4222
  };
3916
4223
  }
3917
4224
 
3918
- // src/connect/resolve-token.ts
3919
- var NO_TOKEN_FOR_PROJECT = (nameOrId) => `This computer has no token for the "${nameOrId}" design system. Run npx designsource connect in the project folder.`;
3920
- function defaultStore(env = process.env) {
3921
- return createStore({ env, platform: process.platform, exec: spawnExec, home: homedir() });
4225
+ // src/connect/account-store.ts
4226
+ var WHERE2 = ["keychain", "secret-service", "dpapi", "file"];
4227
+ var ACCOUNT_TOKEN2 = /^dsa_[A-Za-z0-9_-]{43}$/;
4228
+ var PROJECT_ID2 = /^[A-Za-z0-9_-]+$/;
4229
+ var LABEL = "account";
4230
+ function normaliseOrigin(origin) {
4231
+ let url;
4232
+ try {
4233
+ url = new URL(origin);
4234
+ } catch {
4235
+ throw new CliError(`Not a server address: ${JSON.stringify(origin)}.`);
4236
+ }
4237
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new CliError("A server address must start with http:// or https://.");
4238
+ if (url.username || url.password) throw new CliError("A server address must not carry a user name or password.");
4239
+ return `${url.origin.toLowerCase()}${url.pathname.replace(/\/+$/, "")}`;
3922
4240
  }
3923
- var TERMINAL = { askHidden, pick: (q, options) => pick(q, options, 0) };
3924
- async function resolveToken(input, prompts = TERMINAL) {
3925
- const { given, cwd, projectId, store, interactive, prompt } = input;
3926
- if (given) return { token: given, entry: projectId ? store.entry(projectId) : null };
3927
- if (projectId) {
3928
- const token = await store.token(projectId);
3929
- return token ? { token, entry: store.entry(projectId) } : null;
4241
+ function accountSecretId(origin) {
4242
+ const id = `account-${createHash2("sha256").update(normaliseOrigin(origin)).digest("hex").slice(0, 16)}`;
4243
+ assertProjectId(id);
4244
+ return id;
4245
+ }
4246
+ function accountPath(env, platform, home) {
4247
+ return join7(dirname3(credentialsPath(env, platform, home)), "account.json");
4248
+ }
4249
+ function normaliseFolder(folder) {
4250
+ let path = resolve4(folder);
4251
+ try {
4252
+ path = realpathSync2(path);
4253
+ } catch {
3930
4254
  }
3931
- const matches = store.byFolder(cwd);
3932
- let chosen = matches[0];
3933
- if (matches.length > 1) {
3934
- if (!interactive) {
3935
- throw new CliError(`More than one design system is connected to this folder: ${matches.map((m) => m.name).join(", ")}. Pass --token, or run in the project folder you mean.`);
4255
+ const root = parse(path).root;
4256
+ while (path.length > root.length && (path.endsWith(sep3) || path.endsWith("/"))) path = path.slice(0, -1);
4257
+ return path;
4258
+ }
4259
+ function isRecord3(value) {
4260
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4261
+ }
4262
+ function readAccount(value) {
4263
+ if (!isRecord3(value)) return null;
4264
+ const { email, where, folders, links, secret } = value;
4265
+ if (typeof email !== "string" || !WHERE2.includes(where)) return null;
4266
+ if (!Array.isArray(folders) || !folders.every((f) => typeof f === "string")) return null;
4267
+ if (!isRecord3(links) || !Object.values(links).every((id) => typeof id === "string" && PROJECT_ID2.test(id))) return null;
4268
+ if (secret !== void 0 && typeof secret !== "string") return null;
4269
+ const entry = { email, where, folders: [...folders], links: Object.assign(/* @__PURE__ */ Object.create(null), links) };
4270
+ if (secret !== void 0) entry.secret = secret;
4271
+ return entry;
4272
+ }
4273
+ function readAccounts(path) {
4274
+ const accounts = /* @__PURE__ */ Object.create(null);
4275
+ let text;
4276
+ try {
4277
+ text = readFileSync11(path, "utf8");
4278
+ } catch {
4279
+ return { version: 1, accounts };
4280
+ }
4281
+ let parsed;
4282
+ try {
4283
+ parsed = JSON.parse(text);
4284
+ } catch {
4285
+ return { version: 1, accounts, unreadable: true };
4286
+ }
4287
+ if (!isRecord3(parsed) || parsed.version !== 1 || !isRecord3(parsed.accounts)) return { version: 1, accounts, unreadable: true };
4288
+ for (const [origin, value] of Object.entries(parsed.accounts)) {
4289
+ const entry = readAccount(value);
4290
+ if (entry) accounts[origin] = entry;
4291
+ }
4292
+ return { version: 1, accounts };
4293
+ }
4294
+ function publicEntry2(origin, e) {
4295
+ return { origin, email: e.email, where: e.where, folders: [...e.folders], links: { ...e.links } };
4296
+ }
4297
+ function createAccountStore(opts) {
4298
+ const { env, platform, exec, home } = opts;
4299
+ const path = accountPath(env, platform, home);
4300
+ const forceFile = env.DESIGNSOURCE_STORE === "file";
4301
+ const osBackend = (where) => where === "file" ? null : backendFor(where, exec, home);
4302
+ const update = (origin, change) => {
4303
+ const key = normaliseOrigin(origin);
4304
+ const data = readAccounts(path);
4305
+ const entry = Object.hasOwn(data.accounts, key) ? data.accounts[key] : null;
4306
+ if (!entry) return null;
4307
+ if (change(entry)) writePrivateJson(path, data);
4308
+ return publicEntry2(key, entry);
4309
+ };
4310
+ return {
4311
+ all() {
4312
+ return Object.entries(readAccounts(path).accounts).map(([origin, e]) => publicEntry2(origin, e));
4313
+ },
4314
+ get(origin) {
4315
+ const key = normaliseOrigin(origin);
4316
+ const { accounts } = readAccounts(path);
4317
+ return Object.hasOwn(accounts, key) ? publicEntry2(key, accounts[key]) : null;
4318
+ },
4319
+ async token(origin) {
4320
+ const key = normaliseOrigin(origin);
4321
+ const { accounts } = readAccounts(path);
4322
+ if (!Object.hasOwn(accounts, key)) return null;
4323
+ const entry = accounts[key];
4324
+ const value = entry.where === "file" ? entry.secret ?? null : await osBackend(entry.where).get(accountSecretId(key), entry.secret);
4325
+ return value !== null && ACCOUNT_TOKEN2.test(value) ? value : null;
4326
+ },
4327
+ async save({ origin, email, token, folder }) {
4328
+ const key = normaliseOrigin(origin);
4329
+ if (!ACCOUNT_TOKEN2.test(token)) throw new CliError("Unexpected account token from the API.");
4330
+ const id = accountSecretId(key);
4331
+ const { unreadable, ...data } = readAccounts(path);
4332
+ const previous = Object.hasOwn(data.accounts, key) ? data.accounts[key] : void 0;
4333
+ const folders = [.../* @__PURE__ */ new Set([...previous?.folders ?? [], normaliseFolder(folder)])];
4334
+ const links = Object.assign(/* @__PURE__ */ Object.create(null), previous?.links);
4335
+ let entry = { email, where: "file", folders, links, secret: token };
4336
+ const backend = forceFile ? null : await chooseBackend({ platform, exec, cwd: home, token });
4337
+ if (backend) {
4338
+ const kept = await backend.put(id, LABEL, token);
4339
+ if (kept) entry = { email, where: backend.where, folders, links, ...kept.secret === void 0 ? {} : { secret: kept.secret } };
4340
+ }
4341
+ data.accounts[key] = entry;
4342
+ const backup = unreadable ? backUp(path) : void 0;
4343
+ writePrivateJson(path, data);
4344
+ if (previous && previous.where !== entry.where) await osBackend(previous.where)?.remove(id);
4345
+ return { ...publicEntry2(key, entry), ...backup === void 0 ? {} : { backup } };
4346
+ },
4347
+ trust(origin, folder) {
4348
+ const target = normaliseFolder(folder);
4349
+ return update(origin, (entry) => {
4350
+ if (entry.folders.includes(target)) return false;
4351
+ entry.folders = [...entry.folders, target];
4352
+ return true;
4353
+ });
4354
+ },
4355
+ link(origin, folder, projectId) {
4356
+ assertProjectId(projectId);
4357
+ const target = normaliseFolder(folder);
4358
+ return update(origin, (entry) => {
4359
+ if (entry.links[target] === projectId) return false;
4360
+ entry.links[target] = projectId;
4361
+ return true;
4362
+ });
4363
+ },
4364
+ async forget(origin) {
4365
+ const key = normaliseOrigin(origin);
4366
+ const data = readAccounts(path);
4367
+ if (!Object.hasOwn(data.accounts, key)) return null;
4368
+ const entry = data.accounts[key];
4369
+ try {
4370
+ await osBackend(entry.where)?.remove(accountSecretId(key));
4371
+ } catch {
4372
+ }
4373
+ delete data.accounts[key];
4374
+ writePrivateJson(path, data);
4375
+ return publicEntry2(key, entry);
4376
+ }
4377
+ };
4378
+ }
4379
+
4380
+ // src/connect/project-root.ts
4381
+ import { existsSync as existsSync10 } from "node:fs";
4382
+ import { dirname as dirname4, isAbsolute as isAbsolute3, join as join8, relative as relative3, resolve as resolve5, sep as sep4 } from "node:path";
4383
+ function projectRoot(cwd, exists = existsSync10) {
4384
+ let dir = resolve5(cwd);
4385
+ for (; ; ) {
4386
+ if (exists(join8(dir, ".git"))) return dir;
4387
+ const parent = dirname4(dir);
4388
+ if (parent === dir) return resolve5(cwd);
4389
+ dir = parent;
4390
+ }
4391
+ }
4392
+ function within2(folder, root) {
4393
+ const rel = relative3(root, folder);
4394
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep4}`) && !isAbsolute3(rel);
4395
+ }
4396
+ function homeFolderRefusal(root, home) {
4397
+ const folder = resolve5(root);
4398
+ const homeDir = resolve5(home);
4399
+ const tail = "and writing there would set up every project on this computer.";
4400
+ if (folder === homeDir) return `Run this in your project folder \u2014 ${folder} is your home folder, ${tail}`;
4401
+ if (dirname4(folder) === folder || within2(homeDir, folder)) return `Run this in your project folder \u2014 ${folder} is a system folder, ${tail}`;
4402
+ return null;
4403
+ }
4404
+
4405
+ // src/connect/worktree.ts
4406
+ import { lstatSync, readFileSync as readFileSync12, realpathSync as realpathSync3 } from "node:fs";
4407
+ import { basename as basename2, dirname as dirname5, isAbsolute as isAbsolute4, join as join9, resolve as resolve6 } from "node:path";
4408
+ var POINTER_MAX_BYTES = 4096;
4409
+ var realWorktreeFs = {
4410
+ readSmall(path) {
4411
+ try {
4412
+ const st = lstatSync(path);
4413
+ if (!st.isFile() || st.size > POINTER_MAX_BYTES) return null;
4414
+ return readFileSync12(path, "utf8");
4415
+ } catch {
4416
+ return null;
4417
+ }
4418
+ },
4419
+ realpath(path) {
4420
+ try {
4421
+ return realpathSync3(path);
4422
+ } catch {
4423
+ return null;
4424
+ }
4425
+ }
4426
+ };
4427
+ function oneLine(text) {
4428
+ const lines = text.split(/\r?\n/).filter((l) => l.trim() !== "");
4429
+ if (lines.length !== 1) return null;
4430
+ const line = lines[0].trim();
4431
+ return /[\u0000-\u001f\u007f]/.test(line) ? null : line;
4432
+ }
4433
+ function mainRepoRoot(root, fs = realWorktreeFs) {
4434
+ const dotGit = join9(root, ".git");
4435
+ const pointer = fs.readSmall(dotGit);
4436
+ if (pointer === null) return null;
4437
+ const line = oneLine(pointer);
4438
+ if (line === null || !line.startsWith("gitdir:")) return null;
4439
+ const target = line.slice("gitdir:".length).trim();
4440
+ if (target === "") return null;
4441
+ const gitdir = fs.realpath(isAbsolute4(target) ? target : resolve6(root, target));
4442
+ if (gitdir === null) return null;
4443
+ const worktrees = dirname5(gitdir);
4444
+ if (basename2(worktrees) !== "worktrees") return null;
4445
+ const commonText = fs.readSmall(join9(gitdir, "commondir"));
4446
+ const commonLine = commonText === null ? null : oneLine(commonText);
4447
+ if (commonLine === null) return null;
4448
+ const common = fs.realpath(isAbsolute4(commonLine) ? commonLine : resolve6(gitdir, commonLine));
4449
+ if (common === null || common !== dirname5(worktrees)) return null;
4450
+ if (basename2(common) !== ".git") return null;
4451
+ const backText = fs.readSmall(join9(gitdir, "gitdir"));
4452
+ const backLine = backText === null ? null : oneLine(backText);
4453
+ if (backLine === null || !isAbsolute4(backLine)) return null;
4454
+ const back = fs.realpath(backLine);
4455
+ const here = fs.realpath(dotGit);
4456
+ if (back === null || here === null || back !== here) return null;
4457
+ const main2 = fs.realpath(dirname5(common));
4458
+ return main2 !== null && main2 !== fs.realpath(root) ? main2 : null;
4459
+ }
4460
+
4461
+ // src/connect/account-paths.ts
4462
+ function originOf(api) {
4463
+ normaliseOrigin(api);
4464
+ return new URL(api).origin;
4465
+ }
4466
+ function projectFolders(cwd) {
4467
+ const work = normaliseFolder(projectRoot(normaliseFolder(cwd)));
4468
+ const main2 = mainRepoRoot(work);
4469
+ return main2 === null ? { work, trust: work, worktree: false } : { work, trust: normaliseFolder(main2), worktree: true };
4470
+ }
4471
+
4472
+ // src/connect/resolve-token.ts
4473
+ var NO_TOKEN_FOR_PROJECT = (nameOrId) => `This computer has no token for the "${nameOrId}" design system. Run npx designsource connect in the project folder.`;
4474
+ function defaultStore(env = process.env) {
4475
+ return createStore({ env, platform: process.platform, exec: spawnExec, home: homedir() });
4476
+ }
4477
+ var TERMINAL = { askHidden, pick: (q, options) => pick(q, options, 0) };
4478
+ async function resolveToken(input, prompts = TERMINAL) {
4479
+ const { given, cwd, projectId, store, interactive, prompt } = input;
4480
+ if (given) return { token: given, entry: projectId ? store.entry(projectId) : null };
4481
+ if (projectId) {
4482
+ const token = await store.token(projectId);
4483
+ return token ? { token, entry: store.entry(projectId) } : null;
4484
+ }
4485
+ const matches = byFolderOrMain(store, cwd);
4486
+ let chosen = matches[0];
4487
+ if (matches.length > 1) {
4488
+ if (!interactive) {
4489
+ throw new CliError(`More than one design system is connected to this folder: ${matches.map((m) => m.name).join(", ")}. Pass --token, or run in the project folder you mean.`);
3936
4490
  }
3937
4491
  const id = await prompts.pick("Which design system?", matches.map((m) => ({ value: m.projectId, label: m.name })));
3938
4492
  chosen = matches.find((m) => m.projectId === id);
@@ -3945,6 +4499,12 @@ async function resolveToken(input, prompts = TERMINAL) {
3945
4499
  const typed = await prompts.askHidden("Project token (workbench \u2192 Project settings):");
3946
4500
  return typed ? { token: typed, entry: null } : null;
3947
4501
  }
4502
+ function byFolderOrMain(store, cwd) {
4503
+ const here = store.byFolder(cwd);
4504
+ if (here.length > 0) return here;
4505
+ const { work, trust, worktree } = projectFolders(cwd);
4506
+ return worktree ? store.byFolder(join10(trust, relative4(work, normaliseFolder(cwd)))) : here;
4507
+ }
3948
4508
 
3949
4509
  // src/manifest.ts
3950
4510
  var malformed2 = () => new CliError("Unexpected response from the API \u2014 not a starter manifest.");
@@ -3966,7 +4526,7 @@ function validateManifest(json) {
3966
4526
 
3967
4527
  // src/fetch-manifest.ts
3968
4528
  async function fetchManifest(opts, fetchImpl = fetch) {
3969
- const query = { framework: opts.framework, ...opts.name ? { name: opts.name } : {}, ...opts.screens ? { screens: opts.screens } : {} };
4529
+ const query = { framework: opts.framework, ...opts.name ? { name: opts.name } : {}, ...opts.screens ? { screens: opts.screens, pages: "1" } : {} };
3970
4530
  return validateManifest(await getJson({ api: opts.api, token: opts.token, path: "/api/starter", query }, fetchImpl));
3971
4531
  }
3972
4532
 
@@ -4036,7 +4596,7 @@ async function scaffold(input, env, io) {
4036
4596
  ${written.map((p) => ` ${p}`).join("\n")}
4037
4597
 
4038
4598
  `);
4039
- io.stdout(nextStepsText({ runner, framework, folder, here: root === resolve4(io.cwd) }));
4599
+ io.stdout(nextStepsText({ runner, framework, folder, here: root === resolve7(io.cwd) }));
4040
4600
  }
4041
4601
 
4042
4602
  // src/commands/add.ts
@@ -4081,7 +4641,7 @@ async function runAddCommand(args, io, exec = spawnExec, store) {
4081
4641
  const targets = info.shadcn ? resolveTargets(root, info.shadcn) : defaultTargets(root, info);
4082
4642
  assertKitUtils(root, info, targets);
4083
4643
  let mode;
4084
- if (interactive && args.components.length === 0 && !args.all && args.screens === void 0 && !args.shell) {
4644
+ if (interactive && args.components.length === 0 && !args.all && args.screens === void 0 && !args.shell && !args.site) {
4085
4645
  const first = previouslyAdded(root, targets).every((n) => n === "utils") && !sectionPresent(root, targets).present;
4086
4646
  if (first) mode = await pick(PICK_QUESTION, ADD_MODES, 0);
4087
4647
  }
@@ -4099,6 +4659,7 @@ async function runAddCommand(args, io, exec = spawnExec, store) {
4099
4659
  blocks: !args.noBlocks,
4100
4660
  screens: args.screens,
4101
4661
  shell: args.shell,
4662
+ site: args.site,
4102
4663
  refreshScreens: true,
4103
4664
  force: args.force
4104
4665
  },
@@ -4117,7 +4678,7 @@ async function runAddCommand(args, io, exec = spawnExec, store) {
4117
4678
  // src/commands/connect.ts
4118
4679
  import { accessSync, constants as constants2, existsSync as existsSync11, statSync as statSync3 } from "node:fs";
4119
4680
  import { homedir as homedir2 } from "node:os";
4120
- import { join as join8 } from "node:path";
4681
+ import { join as join11 } from "node:path";
4121
4682
 
4122
4683
  // src/connect/fetch-project.ts
4123
4684
  var RejectedTokenError = class extends CliError {
@@ -4141,31 +4702,6 @@ async function fetchProject(opts, fetchImpl = fetch) {
4141
4702
  return { id, name };
4142
4703
  }
4143
4704
 
4144
- // src/connect/project-root.ts
4145
- import { existsSync as existsSync10 } from "node:fs";
4146
- import { dirname as dirname3, isAbsolute as isAbsolute3, join as join7, relative as relative3, resolve as resolve5, sep as sep3 } from "node:path";
4147
- function projectRoot(cwd, exists = existsSync10) {
4148
- let dir = resolve5(cwd);
4149
- for (; ; ) {
4150
- if (exists(join7(dir, ".git"))) return dir;
4151
- const parent = dirname3(dir);
4152
- if (parent === dir) return resolve5(cwd);
4153
- dir = parent;
4154
- }
4155
- }
4156
- function within2(folder, root) {
4157
- const rel = relative3(root, folder);
4158
- return rel === "" || rel !== ".." && !rel.startsWith(`..${sep3}`) && !isAbsolute3(rel);
4159
- }
4160
- function homeFolderRefusal(root, home) {
4161
- const folder = resolve5(root);
4162
- const homeDir = resolve5(home);
4163
- const tail = "and writing there would set up every project on this computer.";
4164
- if (folder === homeDir) return `Run this in your project folder \u2014 ${folder} is your home folder, ${tail}`;
4165
- if (dirname3(folder) === folder || within2(homeDir, folder)) return `Run this in your project folder \u2014 ${folder} is a system folder, ${tail}`;
4166
- return null;
4167
- }
4168
-
4169
4705
  // src/commands/connect.ts
4170
4706
  var TERMINAL_PROMPTS = { pickMany, pick: (question, options) => pick(question, options, 0), askHidden };
4171
4707
  function onPath(bin, env, platform) {
@@ -4174,7 +4710,7 @@ function onPath(bin, env, platform) {
4174
4710
  const exts = windows ? ["", ...(env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)] : [""];
4175
4711
  return dirs.some(
4176
4712
  (dir) => exts.some((ext) => {
4177
- const file = join8(dir, bin + ext);
4713
+ const file = join11(dir, bin + ext);
4178
4714
  try {
4179
4715
  if (!statSync3(file).isFile()) return false;
4180
4716
  if (!windows) accessSync(file, constants2.X_OK);
@@ -4224,6 +4760,8 @@ function appLines(id, plan) {
4224
4760
  }
4225
4761
  var CODEX_TRUST_NOTE = "Codex reads it once you trust this project in Codex.";
4226
4762
  var GEMINI_TRUST_NOTE = "Gemini CLI reads it unless folder trust is on and this folder is not trusted.";
4763
+ var COMMIT_SETTINGS_NOTE = "Commit these settings files: they hold no token, and worktrees and teammates get designsource only from a committed copy.";
4764
+ var WORKTREE_NOTE = (main2) => `This folder is a git worktree of ${main2}: that repository and every worktree of it are set up; the settings files go here.`;
4227
4765
  function closingLines(apps, changed) {
4228
4766
  const has = (id) => apps.includes(id);
4229
4767
  const restart = [changed.includes("cursor") && "Cursor", changed.includes("vscode") && "VS Code"].filter((s) => typeof s === "string");
@@ -4234,7 +4772,8 @@ function closingLines(apps, changed) {
4234
4772
  ...has("codex") ? [CODEX_TRUST_NOTE] : [],
4235
4773
  ...has("gemini") ? [GEMINI_TRUST_NOTE] : [],
4236
4774
  "Then ask your agent to add the UI kit.",
4237
- "These files hold no token and are safe to commit; teammates run npx designsource connect once."
4775
+ COMMIT_SETTINGS_NOTE,
4776
+ "Teammates run npx designsource connect once."
4238
4777
  ];
4239
4778
  }
4240
4779
  async function runConnect(args, io, deps = defaultConnectDeps(process.env)) {
@@ -4243,14 +4782,16 @@ async function runConnect(args, io, deps = defaultConnectDeps(process.env)) {
4243
4782
  const interactive = terminal && !args.yes;
4244
4783
  const prompts = deps.prompts ?? TERMINAL_PROMPTS;
4245
4784
  const root = projectRoot(io.cwd);
4785
+ const main2 = mainRepoRoot(normaliseFolder(root));
4786
+ const saveFolder = main2 ?? root;
4246
4787
  const say = (lines) => io.stdout(lines.map((l) => `${l}
4247
4788
  `).join(""));
4248
- if (args.forget) return forget(args, root, store, interactive, prompts, deps.credentialsPath, say);
4249
- const refusal = homeFolderRefusal(root, deps.home ?? homedir2());
4789
+ if (args.forget) return forget(args, root, saveFolder, store, interactive, prompts, deps.credentialsPath, say);
4790
+ const refusal = homeFolderRefusal(root, deps.home ?? homedir2()) ?? (main2 ? homeFolderRefusal(main2, deps.home ?? homedir2()) : null);
4250
4791
  if (refusal) throw new CliError(refusal);
4251
- say([`Connecting ${root}`]);
4792
+ say([`Connecting ${root}`, ...main2 ? [WORKTREE_NOTE(main2)] : []]);
4252
4793
  let apps;
4253
- const connected = args.apps ? null : connectedApps(root, store);
4794
+ const connected = args.apps ? null : connectedApps(root, saveFolder, store);
4254
4795
  if (args.apps) apps = args.apps;
4255
4796
  else if (connected) apps = connected;
4256
4797
  else {
@@ -4281,8 +4822,8 @@ async function runConnect(args, io, deps = defaultConnectDeps(process.env)) {
4281
4822
  project = await fetchProject({ api, token }, io.fetchImpl);
4282
4823
  }
4283
4824
  const plans = apps.map((id) => ({ id, plan: planAppFile(root, id, project.id) }));
4284
- const kept = saved && saved.projectId === project.id ? store.addFolder(project.id, root, savedApi) : null;
4285
- const entry = kept ?? await store.save({ projectId: project.id, name: project.name, folder: root, token, ...savedApi === void 0 ? {} : { api: savedApi } });
4825
+ const kept = saved && saved.projectId === project.id ? store.addFolder(project.id, saveFolder, savedApi) : null;
4826
+ const entry = kept ?? await store.save({ projectId: project.id, name: project.name, folder: saveFolder, token, ...savedApi === void 0 ? {} : { api: savedApi } });
4286
4827
  const files = plans.flatMap(({ plan }) => plan.contents !== null && (plan.status === "create" || plan.status === "update") ? [{ path: plan.path, contents: plan.contents }] : []);
4287
4828
  try {
4288
4829
  if (files.length > 0) writeFiles(root, files, { force: true, created: false });
@@ -4294,8 +4835,8 @@ async function runConnect(args, io, deps = defaultConnectDeps(process.env)) {
4294
4835
  const backup = "backup" in entry && entry.backup ? [`Your old credentials file could not be read, so it was kept as ${entry.backup}.`] : [];
4295
4836
  say([...backup, savedLine(project.name, entry.where, deps.credentialsPath, kept !== null), ...plans.flatMap(({ id, plan }) => appLines(id, plan)), ...closingLines(apps, changed)]);
4296
4837
  }
4297
- function connectedApps(root, store) {
4298
- const saved = store.byFolder(root);
4838
+ function connectedApps(root, saveFolder, store) {
4839
+ const saved = savedFor(store, root, saveFolder);
4299
4840
  if (saved.length !== 1) return null;
4300
4841
  const { projectId } = saved[0];
4301
4842
  const apps = APPS.filter((a) => {
@@ -4307,8 +4848,8 @@ function connectedApps(root, store) {
4307
4848
  }).map((a) => a.id);
4308
4849
  return apps.length > 0 ? apps : null;
4309
4850
  }
4310
- async function forget(args, root, store, interactive, prompts, file, say) {
4311
- const matches = store.byFolder(root).filter((m) => args.project === void 0 || m.projectId === args.project);
4851
+ async function forget(args, root, saveFolder, store, interactive, prompts, file, say) {
4852
+ const matches = savedFor(store, root, saveFolder).filter((m) => args.project === void 0 || m.projectId === args.project);
4312
4853
  if (matches.length === 0) return say(["No saved token for this folder."]);
4313
4854
  let chosen = matches[0];
4314
4855
  if (matches.length > 1) {
@@ -4322,6 +4863,10 @@ async function forget(args, root, store, interactive, prompts, file, say) {
4322
4863
  const removed = await store.forget(chosen.projectId) ?? chosen;
4323
4864
  say([`Removed the saved token for "${removed.name}" from ${whereFrom(removed.where, file)}.`]);
4324
4865
  }
4866
+ function savedFor(store, root, saveFolder) {
4867
+ const here = store.byFolder(root);
4868
+ return here.length > 0 || saveFolder === root ? here : store.byFolder(saveFolder);
4869
+ }
4325
4870
 
4326
4871
  // src/commands/create.ts
4327
4872
  async function runCreate(args, env, io, store) {
@@ -4348,177 +4893,8 @@ async function runIntegrate(args, env, io, store) {
4348
4893
 
4349
4894
  // src/commands/login.ts
4350
4895
  import { existsSync as existsSync12 } from "node:fs";
4351
- import { join as join10 } from "node:path";
4896
+ import { join as join12 } from "node:path";
4352
4897
  import { homedir as homedir3, hostname } from "node:os";
4353
-
4354
- // src/connect/account-store.ts
4355
- import { createHash as createHash2 } from "node:crypto";
4356
- import { readFileSync as readFileSync11, realpathSync } from "node:fs";
4357
- import { dirname as dirname4, join as join9, parse, resolve as resolve6, sep as sep4 } from "node:path";
4358
- var WHERE2 = ["keychain", "secret-service", "dpapi", "file"];
4359
- var ACCOUNT_TOKEN2 = /^dsa_[A-Za-z0-9_-]{43}$/;
4360
- var PROJECT_ID2 = /^[A-Za-z0-9_-]+$/;
4361
- var LABEL = "account";
4362
- function normaliseOrigin(origin) {
4363
- let url;
4364
- try {
4365
- url = new URL(origin);
4366
- } catch {
4367
- throw new CliError(`Not a server address: ${JSON.stringify(origin)}.`);
4368
- }
4369
- if (url.protocol !== "http:" && url.protocol !== "https:") throw new CliError("A server address must start with http:// or https://.");
4370
- if (url.username || url.password) throw new CliError("A server address must not carry a user name or password.");
4371
- return `${url.origin.toLowerCase()}${url.pathname.replace(/\/+$/, "")}`;
4372
- }
4373
- function accountSecretId(origin) {
4374
- const id = `account-${createHash2("sha256").update(normaliseOrigin(origin)).digest("hex").slice(0, 16)}`;
4375
- assertProjectId(id);
4376
- return id;
4377
- }
4378
- function accountPath(env, platform, home) {
4379
- return join9(dirname4(credentialsPath(env, platform, home)), "account.json");
4380
- }
4381
- function normaliseFolder(folder) {
4382
- let path = resolve6(folder);
4383
- try {
4384
- path = realpathSync(path);
4385
- } catch {
4386
- }
4387
- const root = parse(path).root;
4388
- while (path.length > root.length && (path.endsWith(sep4) || path.endsWith("/"))) path = path.slice(0, -1);
4389
- return path;
4390
- }
4391
- function isRecord3(value) {
4392
- return typeof value === "object" && value !== null && !Array.isArray(value);
4393
- }
4394
- function readAccount(value) {
4395
- if (!isRecord3(value)) return null;
4396
- const { email, where, folders, links, secret } = value;
4397
- if (typeof email !== "string" || !WHERE2.includes(where)) return null;
4398
- if (!Array.isArray(folders) || !folders.every((f) => typeof f === "string")) return null;
4399
- if (!isRecord3(links) || !Object.values(links).every((id) => typeof id === "string" && PROJECT_ID2.test(id))) return null;
4400
- if (secret !== void 0 && typeof secret !== "string") return null;
4401
- const entry = { email, where, folders: [...folders], links: Object.assign(/* @__PURE__ */ Object.create(null), links) };
4402
- if (secret !== void 0) entry.secret = secret;
4403
- return entry;
4404
- }
4405
- function readAccounts(path) {
4406
- const accounts = /* @__PURE__ */ Object.create(null);
4407
- let text;
4408
- try {
4409
- text = readFileSync11(path, "utf8");
4410
- } catch {
4411
- return { version: 1, accounts };
4412
- }
4413
- let parsed;
4414
- try {
4415
- parsed = JSON.parse(text);
4416
- } catch {
4417
- return { version: 1, accounts, unreadable: true };
4418
- }
4419
- if (!isRecord3(parsed) || parsed.version !== 1 || !isRecord3(parsed.accounts)) return { version: 1, accounts, unreadable: true };
4420
- for (const [origin, value] of Object.entries(parsed.accounts)) {
4421
- const entry = readAccount(value);
4422
- if (entry) accounts[origin] = entry;
4423
- }
4424
- return { version: 1, accounts };
4425
- }
4426
- function publicEntry2(origin, e) {
4427
- return { origin, email: e.email, where: e.where, folders: [...e.folders], links: { ...e.links } };
4428
- }
4429
- function createAccountStore(opts) {
4430
- const { env, platform, exec, home } = opts;
4431
- const path = accountPath(env, platform, home);
4432
- const forceFile = env.DESIGNSOURCE_STORE === "file";
4433
- const osBackend = (where) => where === "file" ? null : backendFor(where, exec, home);
4434
- const update = (origin, change) => {
4435
- const key = normaliseOrigin(origin);
4436
- const data = readAccounts(path);
4437
- const entry = Object.hasOwn(data.accounts, key) ? data.accounts[key] : null;
4438
- if (!entry) return null;
4439
- if (change(entry)) writePrivateJson(path, data);
4440
- return publicEntry2(key, entry);
4441
- };
4442
- return {
4443
- all() {
4444
- return Object.entries(readAccounts(path).accounts).map(([origin, e]) => publicEntry2(origin, e));
4445
- },
4446
- get(origin) {
4447
- const key = normaliseOrigin(origin);
4448
- const { accounts } = readAccounts(path);
4449
- return Object.hasOwn(accounts, key) ? publicEntry2(key, accounts[key]) : null;
4450
- },
4451
- async token(origin) {
4452
- const key = normaliseOrigin(origin);
4453
- const { accounts } = readAccounts(path);
4454
- if (!Object.hasOwn(accounts, key)) return null;
4455
- const entry = accounts[key];
4456
- const value = entry.where === "file" ? entry.secret ?? null : await osBackend(entry.where).get(accountSecretId(key), entry.secret);
4457
- return value !== null && ACCOUNT_TOKEN2.test(value) ? value : null;
4458
- },
4459
- async save({ origin, email, token, folder }) {
4460
- const key = normaliseOrigin(origin);
4461
- if (!ACCOUNT_TOKEN2.test(token)) throw new CliError("Unexpected account token from the API.");
4462
- const id = accountSecretId(key);
4463
- const { unreadable, ...data } = readAccounts(path);
4464
- const previous = Object.hasOwn(data.accounts, key) ? data.accounts[key] : void 0;
4465
- const folders = [.../* @__PURE__ */ new Set([...previous?.folders ?? [], normaliseFolder(folder)])];
4466
- const links = Object.assign(/* @__PURE__ */ Object.create(null), previous?.links);
4467
- let entry = { email, where: "file", folders, links, secret: token };
4468
- const backend = forceFile ? null : await chooseBackend({ platform, exec, cwd: home, token });
4469
- if (backend) {
4470
- const kept = await backend.put(id, LABEL, token);
4471
- if (kept) entry = { email, where: backend.where, folders, links, ...kept.secret === void 0 ? {} : { secret: kept.secret } };
4472
- }
4473
- data.accounts[key] = entry;
4474
- const backup = unreadable ? backUp(path) : void 0;
4475
- writePrivateJson(path, data);
4476
- if (previous && previous.where !== entry.where) await osBackend(previous.where)?.remove(id);
4477
- return { ...publicEntry2(key, entry), ...backup === void 0 ? {} : { backup } };
4478
- },
4479
- trust(origin, folder) {
4480
- const target = normaliseFolder(folder);
4481
- return update(origin, (entry) => {
4482
- if (entry.folders.includes(target)) return false;
4483
- entry.folders = [...entry.folders, target];
4484
- return true;
4485
- });
4486
- },
4487
- link(origin, folder, projectId) {
4488
- assertProjectId(projectId);
4489
- const target = normaliseFolder(folder);
4490
- return update(origin, (entry) => {
4491
- if (entry.links[target] === projectId) return false;
4492
- entry.links[target] = projectId;
4493
- return true;
4494
- });
4495
- },
4496
- async forget(origin) {
4497
- const key = normaliseOrigin(origin);
4498
- const data = readAccounts(path);
4499
- if (!Object.hasOwn(data.accounts, key)) return null;
4500
- const entry = data.accounts[key];
4501
- try {
4502
- await osBackend(entry.where)?.remove(accountSecretId(key));
4503
- } catch {
4504
- }
4505
- delete data.accounts[key];
4506
- writePrivateJson(path, data);
4507
- return publicEntry2(key, entry);
4508
- }
4509
- };
4510
- }
4511
-
4512
- // src/connect/account-paths.ts
4513
- function originOf(api) {
4514
- normaliseOrigin(api);
4515
- return new URL(api).origin;
4516
- }
4517
- function trustedRootFor(cwd) {
4518
- return normaliseFolder(projectRoot(normaliseFolder(cwd)));
4519
- }
4520
-
4521
- // src/commands/login.ts
4522
4898
  function defaultLoginDeps(env) {
4523
4899
  const home = homedir3();
4524
4900
  const platform = process.platform;
@@ -4532,7 +4908,7 @@ function defaultLoginDeps(env) {
4532
4908
  platform
4533
4909
  };
4534
4910
  }
4535
- var sleepFor = (ms) => new Promise((resolve8) => setTimeout(resolve8, ms));
4911
+ var sleepFor = (ms) => new Promise((resolve9) => setTimeout(resolve9, ms));
4536
4912
  var UNTRUSTED_LOGIN_SERVER = (api) => `designsource will not sign in to ${api} from a script: outside a terminal it signs in only to ${DEFAULT_API_ORIGIN} or a server on this computer. If you trust ${api}, run npx designsource login --api ${api} in a terminal yourself.`;
4537
4913
  var ACCOUNT_SCOPES_NEEDED = ["projects:create", "projects:read", "screens:create"];
4538
4914
  var REVOKE_FAILED = "Could not reach the server to revoke this sign-in; revoke it on your profile page.";
@@ -4542,7 +4918,7 @@ function loginApi(args, terminal) {
4542
4918
  throw new CliError(UNTRUSTED_LOGIN_SERVER(api));
4543
4919
  }
4544
4920
  var NOT_A_PROJECT = "Run npx designsource login inside a project folder (one with a .git folder or a package.json).";
4545
- var isProjectFolder = (root) => existsSync12(join10(root, ".git")) || existsSync12(join10(root, "package.json"));
4921
+ var isProjectFolder = (root) => existsSync12(join12(root, ".git")) || existsSync12(join12(root, "package.json"));
4546
4922
  function savedLine2(where, file) {
4547
4923
  if (where === "keychain") return "Saved the sign-in in the macOS keychain \u2713";
4548
4924
  if (where === "secret-service") return "Saved the sign-in in the system keyring \u2713";
@@ -4559,7 +4935,7 @@ function closingLines2(apps, changed, usesAccount) {
4559
4935
  ...apps.includes("codex") ? [CODEX_TRUST_NOTE] : [],
4560
4936
  ...apps.includes("gemini") ? [GEMINI_TRUST_NOTE] : [],
4561
4937
  ...usesAccount ? ["Then ask your agent to create a design system for this app."] : [],
4562
- "These files hold no token and are safe to commit."
4938
+ COMMIT_SETTINGS_NOTE
4563
4939
  ];
4564
4940
  }
4565
4941
  var plansFor = (root, apps) => apps.map((id) => ({ id, plan: planAppFile(root, id, null) }));
@@ -4568,8 +4944,9 @@ async function runLogin(args, io, deps = defaultLoginDeps(process.env)) {
4568
4944
  const { accounts, terminal } = deps;
4569
4945
  const say = (lines) => io.stdout(lines.map((l) => `${l}
4570
4946
  `).join(""));
4571
- const root = trustedRootFor(io.cwd);
4572
- const refusal = homeFolderRefusal(root, normaliseFolder(deps.home));
4947
+ const { work: root, trust, worktree } = projectFolders(io.cwd);
4948
+ const homeDir = normaliseFolder(deps.home);
4949
+ const refusal = homeFolderRefusal(root, homeDir) ?? homeFolderRefusal(trust, homeDir);
4573
4950
  if (refusal) throw new CliError(refusal);
4574
4951
  if (!isProjectFolder(root)) throw new CliError(NOT_A_PROJECT);
4575
4952
  const api = loginApi(args, terminal);
@@ -4586,7 +4963,7 @@ async function runLogin(args, io, deps = defaultLoginDeps(process.env)) {
4586
4963
  }
4587
4964
  }
4588
4965
  plansFor(root, apps);
4589
- say([`Signing in for ${root}`]);
4966
+ say([`Signing in for ${trust}`, ...worktree ? [WORKTREE_NOTE(trust)] : []]);
4590
4967
  const head = [];
4591
4968
  let email = null;
4592
4969
  const saved = accounts.get(api);
@@ -4595,9 +4972,9 @@ async function runLogin(args, io, deps = defaultLoginDeps(process.env)) {
4595
4972
  const check = await requestJson({ api, path: "/api/agent/projects", method: "GET", token: savedToken2 }, io.fetchImpl);
4596
4973
  const stale = check.status === 200 && await lacksScope(api, savedToken2, io.fetchImpl);
4597
4974
  if (check.status === 200 && !stale) {
4598
- accounts.trust(api, root);
4975
+ accounts.trust(api, trust);
4599
4976
  email = printable(saved.email);
4600
- head.push(`Already signed in on this computer; your agent may now use it from ${root}.`);
4977
+ head.push(`Already signed in on this computer; your agent may now use it from ${trust}.`);
4601
4978
  } else if (check.status !== 200 && check.status !== 401 && check.status !== 403) {
4602
4979
  throw new CliError(messageForResponse(check.status, check.body, api));
4603
4980
  }
@@ -4614,7 +4991,7 @@ async function runLogin(args, io, deps = defaultLoginDeps(process.env)) {
4614
4991
  show: (line) => say([line]),
4615
4992
  open
4616
4993
  });
4617
- const entry = await accounts.save({ origin: api, email: signedIn.email, token: signedIn.token, folder: root });
4994
+ const entry = await accounts.save({ origin: api, email: signedIn.email, token: signedIn.token, folder: trust });
4618
4995
  email = signedIn.email;
4619
4996
  if (savedToken2 && savedToken2 !== signedIn.token) await revoke(api, savedToken2, io.fetchImpl);
4620
4997
  if (entry.backup) head.push(`Your old account file could not be read, so it was kept as ${entry.backup}.`);
@@ -4688,12 +5065,12 @@ async function runLogout(args, io, deps = defaultLoginDeps(process.env)) {
4688
5065
  import { homedir as homedir4 } from "node:os";
4689
5066
 
4690
5067
  // src/version.ts
4691
- var VERSION = true ? "0.10.0" : "0.0.0-dev";
5068
+ var VERSION = true ? "0.12.1" : "0.0.0-dev";
4692
5069
 
4693
5070
  // src/mcp/account-session.ts
4694
- var NOT_SIGNED_IN_FOR = (root) => `Not signed in on this computer for ${printable(root)}. Ask the user to run npx designsource login in a terminal in that folder, then restart this app.`;
5071
+ var NOT_SIGNED_IN_FOR = (root) => `designsource is not signed in for ${printable(root)}. Ask the user to run npx designsource login in a terminal in that folder, then restart this app. A sign-in there also covers its git worktrees.`;
4695
5072
  var SEVERAL_ACCOUNTS = "More than one designsource account is signed in on this computer; pass --api.";
4696
- var NO_LINK = "No design system is linked to this folder yet. Call create_design_system or use_design_system.";
5073
+ var NO_LINK = "No design system is linked to this folder yet. Call list_design_systems, then use_design_system with one of its ids, or call create_design_system to make a new one.";
4697
5074
  var ACCOUNT_TOKEN3 = /^dsa_[A-Za-z0-9_-]{43}$/;
4698
5075
  var PROJECT_ID3 = /^[A-Za-z0-9_-]+$/;
4699
5076
  var refuse = (message) => ({ kind: "none", message });
@@ -4715,12 +5092,15 @@ function chooseAccount(api, apiGiven, accounts, notSignedIn) {
4715
5092
  }
4716
5093
  async function resolveAccount(input) {
4717
5094
  const { api, apiGiven, cwd, home, accounts } = input;
4718
- const folder = trustedRootFor(cwd);
4719
- const notSignedIn = NOT_SIGNED_IN_FOR(folder);
5095
+ const { work, trust } = projectFolders(cwd);
5096
+ const notSignedIn = NOT_SIGNED_IN_FOR(trust);
4720
5097
  const chosen = chooseAccount(api, apiGiven, accounts, notSignedIn);
4721
5098
  if ("kind" in chosen) return chosen;
4722
- if (homeFolderRefusal(folder, normaliseFolder(home)) !== null) return refuse(notSignedIn);
4723
- if (!chosen.folders.some((f) => normaliseFolder(f) === folder)) return refuse(notSignedIn);
5099
+ const homeDir = normaliseFolder(home);
5100
+ if (homeFolderRefusal(trust, homeDir) !== null || homeFolderRefusal(work, homeDir) !== null) return refuse(notSignedIn);
5101
+ const trusted = (f) => chosen.folders.some((saved) => normaliseFolder(saved) === f);
5102
+ const folder = trusted(work) ? work : trusted(trust) ? trust : null;
5103
+ if (folder === null) return refuse(notSignedIn);
4724
5104
  const linked = Object.entries(chosen.links).find(([f]) => normaliseFolder(f) === folder)?.[1];
4725
5105
  const projectId = linked !== void 0 && PROJECT_ID3.test(linked) ? linked : null;
4726
5106
  let token;
@@ -4730,7 +5110,7 @@ async function resolveAccount(input) {
4730
5110
  return refuse(notSignedIn);
4731
5111
  }
4732
5112
  if (token === null || !ACCOUNT_TOKEN3.test(token)) return refuse(notSignedIn);
4733
- return { kind: "account", origin: chosen.origin, email: chosen.email, token, folder, projectId };
5113
+ return { kind: "account", origin: chosen.origin, email: chosen.email, token, folder, workFolder: work, projectId };
4734
5114
  }
4735
5115
 
4736
5116
  // src/mcp/jsonrpc.ts
@@ -4957,7 +5337,7 @@ var fundingRefusal = (body, api) => {
4957
5337
  if (!isPlainObject(body) || !FUNDING_CODES.includes(String(body.code))) return null;
4958
5338
  return errorResult(`${serverText(body) ?? "This account cannot pay for a screen right now."} ${FUNDING_HINT(api)}`);
4959
5339
  };
4960
- var GENERATE_DESCRIPTION = "Make a new app screen for the design system this folder is linked to, from a sentence (a list, a detail page, settings, a form or a dashboard built from its components), or change an existing one by passing its name in screen. Pass data_model to shape the screen's records after the app's own (read from its Prisma schema or types). Spends the signed-in account's credits or its own AI key, so your client will ask the user first, and takes up to a couple of minutes. Never writes files: the answer names the screen and a link to see it; then call add_ui_kit with screens to write it into the app.";
5340
+ 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.";
4961
5341
  async function generateScreen(args, ctx) {
4962
5342
  if (!ctx.account) return errorResult(ctx.accountRefusal ?? GENERATE_NEEDS_LOGIN);
4963
5343
  const account = ctx.account;
@@ -4972,7 +5352,7 @@ async function generateScreen(args, ctx) {
4972
5352
  if (!Array.isArray(projects)) return projects;
4973
5353
  const project = projects.find((p) => p.id === projectId);
4974
5354
  if (!project) return errorResult(LINKED_PROJECT_GONE);
4975
- const body = { prompt, operationId: randomUUID() };
5355
+ const body = { prompt, operationId: randomUUID(), pages: true };
4976
5356
  if (screen !== void 0) body.screen = screen;
4977
5357
  if (dataModel !== void 0) body.dataModel = dataModel;
4978
5358
  const outcome = await postNdjson({ api: account.api, path: generatePath(projectId), token: account.token, body }, ctx.fetchImpl);
@@ -5064,25 +5444,32 @@ var ACCOUNT_TOOLS = [
5064
5444
  ];
5065
5445
 
5066
5446
  // src/mcp/project-folder.ts
5067
- import { isAbsolute as isAbsolute4, relative as relative4, resolve as resolve7, sep as sep5 } from "node:path";
5447
+ import { isAbsolute as isAbsolute5, join as join13, relative as relative5, resolve as resolve8, sep as sep5 } from "node:path";
5068
5448
  var NOT_SURE_WHICH_FOLDER = "Not sure which project folder to change: run npx designsource connect in it first.";
5069
5449
  function isWithin2(folder, root) {
5070
- const rel = relative4(root, folder);
5071
- return rel === "" || rel !== ".." && !rel.startsWith(`..${sep5}`) && !isAbsolute4(rel);
5450
+ const rel = relative5(root, folder);
5451
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep5}`) && !isAbsolute5(rel);
5072
5452
  }
5073
- function resolveProjectFolder(cwd, entry) {
5453
+ function resolveProjectFolder(cwd, entry, worktree = worktreeOf(cwd)) {
5074
5454
  if (!entry) return cwd;
5075
- const here = resolve7(cwd);
5076
- const holding = entry.folders.map((f) => resolve7(f)).filter((f) => isWithin2(here, f)).sort((a, b) => b.length - a.length);
5455
+ const here = resolve8(cwd);
5456
+ const saved = entry.folders.map((f) => resolve8(f));
5457
+ const mapped = worktree ? saved.map((f) => normaliseFolder(f)).filter((f) => isWithin2(f, worktree.main)).map((f) => join13(worktree.work, relative5(worktree.main, f))) : [];
5458
+ const realHere = worktree ? normaliseFolder(cwd) : here;
5459
+ const holding = [...mapped.filter((f) => isWithin2(realHere, f)), ...saved.filter((f) => isWithin2(here, f))].sort((a, b) => b.length - a.length);
5077
5460
  if (holding[0]) return holding[0];
5078
- return entry.folders.length === 1 ? resolve7(entry.folders[0]) : null;
5461
+ return entry.folders.length === 1 ? resolve8(entry.folders[0]) : null;
5462
+ }
5463
+ function worktreeOf(cwd) {
5464
+ const { work, trust, worktree } = projectFolders(cwd);
5465
+ return worktree ? { work, main: trust } : null;
5079
5466
  }
5080
5467
 
5081
5468
  // src/mcp/tools.ts
5082
5469
  var accountProjectPath = (projectId, kind) => `/api/agent/projects/${encodeURIComponent(projectId)}/${kind}`;
5083
5470
  var READ_ONLY = { readOnlyHint: true };
5084
5471
  var TIERS = ["design", "semantic", "component"];
5085
- var CATEGORIES = ["color", "spacing", "radius", "typography", "shadow", "zIndex", "border"];
5472
+ var CATEGORIES = ["color", "spacing", "radius", "typography", "shadow", "zIndex", "border", "gradient"];
5086
5473
  var NO_INPUT = { type: "object", properties: {}, additionalProperties: false };
5087
5474
  var pretty = (v) => JSON.stringify(v, null, 2);
5088
5475
  var NO_BLOCKS = "This server sent no blocks. Update designsource and the server.";
@@ -5119,8 +5506,13 @@ var isScreenName2 = (v) => typeof v === "string" && SCREEN_SLUG.test(v) && !RESE
5119
5506
  var SCREENS_NOT_LISTED = "This DS source server does not list screens yet.";
5120
5507
  var NO_SCREENS_LISTED = "This design system has no screens yet. Make one with generate_screen (after the user signs in with npx designsource login), or in the Screens view of the workbench.";
5121
5508
  var SCREEN_NAME_ARG = '"screen" must be a screen name from list_screens.';
5122
- var SCREENS_ARG = '"screens" must be screen names from list_screens, or ["all"].';
5509
+ var SCREENS_ARG = '"screens" must be screen names from list_screens, "site", or ["all"].';
5123
5510
  var SCREENS_NOT_SERVED_FOR_AGENT = "This DS source server does not send screens yet. Call add_ui_kit without screens.";
5511
+ var NO_PAGES_PULLED_FOR_AGENT = (e) => {
5512
+ if (e.skip) return PAGE_SKIPPED_NO_SITE(screenSkipText(e.skip.slug, e.skip.agentReason ?? e.skip.reason));
5513
+ const head = "None of this design system's pages is in the app yet, and the site menu links only the pages there.";
5514
+ 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.`;
5515
+ };
5124
5516
  function listScreens(snapshot) {
5125
5517
  if (!snapshot.screens) return errorResult(SCREENS_NOT_LISTED);
5126
5518
  if (snapshot.screens.length === 0) return textResult(NO_SCREENS_LISTED);
@@ -5162,11 +5554,13 @@ async function getScreenSource(args, ctx) {
5162
5554
  );
5163
5555
  }
5164
5556
  function screensArg(v) {
5165
- if (v === void 0) return { ok: true, value: void 0 };
5557
+ if (v === void 0) return { ok: true, value: void 0, site: false };
5166
5558
  if (!Array.isArray(v) || !v.every((n) => typeof n === "string")) return { ok: false };
5167
- if (v.includes("all")) return { ok: true, value: "all" };
5168
- if (!v.every(isScreenName2)) return { ok: false };
5169
- return { ok: true, value: v.length > 0 ? [...new Set(v)] : void 0 };
5559
+ const site = v.includes("site");
5560
+ const names = v.filter((n) => n !== "site");
5561
+ if (names.includes("all")) return { ok: true, value: "all", site };
5562
+ if (!names.every(isScreenName2)) return { ok: false };
5563
+ return { ok: true, value: names.length > 0 ? [...new Set(names)] : void 0, site };
5170
5564
  }
5171
5565
  async function addUiKit(args, ctx) {
5172
5566
  const { components, replace_existing: replace, no_blocks: noBlocks } = args;
@@ -5179,7 +5573,7 @@ async function addUiKit(args, ctx) {
5179
5573
  if (!screens.ok) return errorResult(SCREENS_ARG);
5180
5574
  const access = kitAccess(ctx);
5181
5575
  if (isResult2(access)) return access;
5182
- const root = ctx.token !== null ? resolveProjectFolder(ctx.cwd, ctx.projectFolders === null ? null : { folders: ctx.projectFolders }) : ctx.account.folder;
5576
+ const root = ctx.token !== null ? resolveProjectFolder(ctx.cwd, ctx.projectFolders === null ? null : { folders: ctx.projectFolders }) : ctx.account.workFolder;
5183
5577
  if (root === null) return errorResult(NOT_SURE_WHICH_FOLDER);
5184
5578
  const questions = {
5185
5579
  pickComponents: async (all) => all,
@@ -5200,6 +5594,7 @@ async function addUiKit(args, ctx) {
5200
5594
  skipInstall: false,
5201
5595
  blocks: noBlocks !== true,
5202
5596
  ...screens.value !== void 0 ? { screens: screens.value } : {},
5597
+ ...screens.site ? { site: true } : {},
5203
5598
  // As a bare CLI rerun: a call naming neither components nor screens refreshes the screens an earlier run wrote.
5204
5599
  refreshScreens: true
5205
5600
  },
@@ -5216,7 +5611,7 @@ async function addUiKit(args, ctx) {
5216
5611
  );
5217
5612
  } catch (e) {
5218
5613
  if (!(e instanceof CliError) && progress.length === 0) throw e;
5219
- const message = e instanceof UnknownComponentsError ? UNKNOWN_FOR_AGENT(e.names) : e instanceof CliError && e.message === SCREENS_NOT_SERVED ? SCREENS_NOT_SERVED_FOR_AGENT : e instanceof Error ? e.message : String(e);
5614
+ 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);
5220
5615
  const tail = e instanceof StepError && e.outputTail ? ["Last output:", e.outputTail] : [];
5221
5616
  return errorResult([...progress, message, ...tail].join("\n"));
5222
5617
  }
@@ -5341,7 +5736,7 @@ ${files.join("\n\n")}`);
5341
5736
  },
5342
5737
  {
5343
5738
  name: "list_screens",
5344
- description: "The app screens made for this design system in DS source (lists, details, settings, forms, dashboards built from the kit): one line each, name \u2014 title (kind). Follow with get_screen_source, or write them into the app with add_ui_kit and screens.",
5739
+ 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.',
5345
5740
  inputSchema: NO_INPUT,
5346
5741
  annotations: READ_ONLY,
5347
5742
  run: (snapshot) => listScreens(snapshot)
@@ -5356,14 +5751,14 @@ ${files.join("\n\n")}`);
5356
5751
  },
5357
5752
  {
5358
5753
  name: "add_ui_kit",
5359
- description: `Add this design system's UI kit to the React app in the current folder: the theme, the components and their libraries. Sets up Tailwind and shadcn when the app lacks them. A full run (no components and no screens named) also writes the /design-system section, every component, block and sample page in the project's theme, with its blocks unless no_blocks is true, and refreshes the screens an earlier run wrote. screens (names from list_screens, or ["all"]) writes those app screens with the parts and components they import; you mount each on a route. Changes files in the project, so your client will ask the user first. Never overwrites components or screens the user edited.`,
5754
+ 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.`,
5360
5755
  inputSchema: {
5361
5756
  type: "object",
5362
5757
  properties: {
5363
5758
  components: { type: "array", items: { type: "string" }, description: "Component names such as button or dialog. Omit to add everything (or refresh what was added before)." },
5364
5759
  replace_existing: { type: "boolean", description: "Replace component files that exist but were not added by designsource. Ask the user first." },
5365
5760
  no_blocks: { type: "boolean", description: "Add the /design-system section without its blocks and their libraries. Blocks an earlier run wrote are left in place." },
5366
- screens: { type: "array", items: { type: "string" }, description: `Screen names from list_screens, or ["all"] for every screen. Each is written under the components folder's screens/ with the parts and kit components it imports.` }
5761
+ 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.` }
5367
5762
  },
5368
5763
  additionalProperties: false
5369
5764
  },
@@ -5455,7 +5850,7 @@ var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
5455
5850
  var isStringRecord = (v) => isObject2(v) && Object.values(v).every((x) => typeof x === "string");
5456
5851
  var isStringListRecord = (v) => isObject2(v) && Object.values(v).every((x) => Array.isArray(x) && x.every((s) => typeof s === "string"));
5457
5852
  var isBlockEntry = (v) => isObject2(v) && typeof v.id === "string" && typeof v.title === "string" && typeof v.family === "string" && Array.isArray(v.components) && v.components.every((c) => typeof c === "string") && Array.isArray(v.files) && v.files.every((f) => typeof f === "string");
5458
- var isScreenRow = (v) => isObject2(v) && typeof v.slug === "string" && SCREEN_SLUG.test(v.slug) && !RESERVED_SCREEN_SLUGS.includes(v.slug) && typeof v.title === "string" && typeof v.kind === "string" && SCREEN_KINDS.includes(v.kind) && typeof v.updatedAt === "string";
5853
+ 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";
5459
5854
  var isScreenIndex = (v) => Array.isArray(v) && v.every(isScreenRow) && new Set(v.map((r) => r.slug)).size === v.length;
5460
5855
  function validateSnapshot(json) {
5461
5856
  if (!isObject2(json)) throw malformed4();
@@ -5476,7 +5871,7 @@ function validateSnapshot(json) {
5476
5871
  }
5477
5872
  async function fetchSnapshot(opts, fetchImpl = fetch) {
5478
5873
  const { api, token, path = "/api/snapshot", messages } = opts;
5479
- return validateSnapshot(await getJson({ api, token, path, ...messages ? { messages } : {} }, fetchImpl));
5874
+ return validateSnapshot(await getJson({ api, token, path: `${path}?pages=1`, ...messages ? { messages } : {} }, fetchImpl));
5480
5875
  }
5481
5876
  var STALE_RETRY_MS = 15e3;
5482
5877
  var servesStale = (e) => !(e instanceof ApiError) || e.status === null || e.status >= 500;
@@ -5531,6 +5926,7 @@ function toolAccountFor(session, accounts, onLink, onGone = () => {
5531
5926
  token: session.token,
5532
5927
  email: session.email,
5533
5928
  folder: session.folder,
5929
+ workFolder: session.workFolder,
5534
5930
  projectId: session.projectId,
5535
5931
  link(projectId) {
5536
5932
  if (accounts.link(session.origin, session.folder, projectId) === null) {
@@ -5571,9 +5967,8 @@ async function runMcp(args, io, streams = { input: process.stdin, output: proces
5571
5967
  if (resolved.kind === "none") {
5572
5968
  return {
5573
5969
  token: null,
5574
- missingToken: `${MCP_TOKEN_REQUIRED}
5575
-
5576
- ${resolved.message}`,
5970
+ // The account path's own sentence: it names the folder and the one command (`login`).
5971
+ missingToken: resolved.message,
5577
5972
  accountRefusal: resolved.message,
5578
5973
  projectFolders: null,
5579
5974
  api: args.api,