@soroush.design/cli 0.2.0-alpha.1 → 0.2.0-alpha.3

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.
@@ -2,6 +2,7 @@ import { parseArgs } from "node:util";
2
2
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, rmdirSync, writeFileSync } from "node:fs";
3
3
  import { dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
4
4
  import { spawnSync } from "node:child_process";
5
+ import { emitKeypressEvents } from "node:readline";
5
6
  import { createInterface } from "node:readline/promises";
6
7
  // src/apply/fileSystem.ts
7
8
  const nodeFileSystem = {
@@ -727,10 +728,15 @@ function findApp(cwd) {
727
728
  folder
728
729
  };
729
730
  }
730
- /** Asks for the default color scheme: light, unless the answer is dark. */
731
+ /** Asks for the default color scheme, starting on light. */
731
732
  async function askScheme(io) {
732
- const answer = await io.ask("Default color scheme, light or dark? (light) ");
733
- return /^d(ark)?$/i.test(answer.trim()) ? "dark" : "light";
733
+ return await io.select("Default color scheme", [{
734
+ value: "light",
735
+ label: "light"
736
+ }, {
737
+ value: "dark",
738
+ label: "dark"
739
+ }]);
734
740
  }
735
741
  function collectFacts(app, scheme, designSystem) {
736
742
  const { root, packageJson, rootCandidates } = app;
@@ -836,6 +842,13 @@ async function runInit(options, io, designSystem, fileSystem = nodeFileSystem) {
836
842
  return applyAndInstall(plan, root, io, fileSystem);
837
843
  }
838
844
  // src/create/packageManager.ts
845
+ /** The package managers create installs with, in the order it offers them. */
846
+ const PACKAGE_MANAGERS = [
847
+ "npm",
848
+ "pnpm",
849
+ "yarn",
850
+ "bun"
851
+ ];
839
852
  /**
840
853
  * The package manager that ran `create`, from the user agent it gives the commands it starts
841
854
  * (`pnpm/10.4.1 npm/? node/v24.1.0 ...`), else npm. A new app has no lockfile to read it from.
@@ -869,31 +882,126 @@ function createAppInstallCommand({ name, isYarnBerry }) {
869
882
  function formatRunScript({ name }, script) {
870
883
  return name === "npm" || name === "bun" ? `${name} run ${script}` : `${name} ${script}`;
871
884
  }
885
+ // src/create/libraries.ts
886
+ /** The libraries, in the order create offers them. */
887
+ const LIBRARIES = [
888
+ {
889
+ name: "tanstack-query",
890
+ label: "TanStack Query: fetching and caching data",
891
+ group: "data"
892
+ },
893
+ {
894
+ name: "swr",
895
+ label: "SWR: fetching and caching data",
896
+ group: "data"
897
+ },
898
+ {
899
+ name: "msw",
900
+ label: "msw: a mock API in the browser"
901
+ },
902
+ {
903
+ name: "zustand",
904
+ label: "zustand: a store of global state",
905
+ group: "state"
906
+ },
907
+ {
908
+ name: "jotai",
909
+ label: "Jotai: atoms of global state",
910
+ group: "state"
911
+ },
912
+ {
913
+ name: "redux-toolkit",
914
+ label: "Redux Toolkit: a store of global state",
915
+ group: "state"
916
+ },
917
+ {
918
+ name: "react-hook-form",
919
+ label: "React Hook Form + Zod: a form, validated"
920
+ },
921
+ {
922
+ name: "vitest",
923
+ label: "Vitest + Testing Library: tests"
924
+ }
925
+ ];
926
+ const LIBRARY_NAMES = LIBRARIES.map(({ name }) => name);
927
+ /** What the libraries of each group do, as the refusal says it. */
928
+ const GROUP_JOBS = {
929
+ data: "fetch and cache data",
930
+ state: "hold global state"
931
+ };
932
+ /** The names a sentence lists: `a and b`, `a, b and c`. */
933
+ const listNames = (names) => `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`;
934
+ /** Why `libraries` cannot go together, or `undefined` when they can. */
935
+ function findLibraryConflict(libraries) {
936
+ for (const group of ["data", "state"]) {
937
+ const picked = LIBRARIES.filter((library) => library.group === group && libraries.includes(library.name));
938
+ if (picked.length < 2) continue;
939
+ const names = picked.map(({ label }) => label.split(":")[0]);
940
+ const all = names.length === 2 ? "both" : "all";
941
+ return `${listNames(names)} ${all} ${GROUP_JOBS[group]}: pick one.`;
942
+ }
943
+ }
872
944
  // package.json
873
- var version = "0.2.0-alpha.1";
945
+ var version = "0.2.0-alpha.3";
874
946
  // src/create/vike/vike.ts
875
947
  /** The versions the starter installs: the ones this package is tested with. */
876
948
  const VERSIONS = {
877
949
  "@emotion/server": "^11.11.0",
950
+ "@hookform/resolvers": "^7.0.6",
951
+ "@reduxjs/toolkit": "^2.14.0",
878
952
  "@soroush.tech/eslint-config": "workspace:*",
953
+ "@tanstack/react-query": "^5.107.1",
954
+ "@testing-library/dom": "^10.4.2",
955
+ "@testing-library/react": "^16.3.3",
879
956
  "@types/node": "^26.6.6",
880
957
  "@types/react": "^19.3.0",
881
958
  "@types/react-dom": "^19.3.0",
882
959
  "@vitejs/plugin-react": "^6.3.0",
883
960
  "@vitest/coverage-v8": "^5.1.0",
961
+ "jotai": "^3.0.2",
962
+ "jsdom": "^31.0.1",
963
+ "msw": "^3.0.5",
884
964
  "oxlint": "^1.93.0",
885
965
  "react": "^19.3.1",
886
966
  "react-dom": "^19.3.1",
967
+ "react-hook-form": "^7.92.0",
968
+ "react-redux": "^9.3.1",
969
+ "swr": "^2.5.1",
887
970
  "tsdown": "^0.23.7",
888
971
  "typescript": "~7.0.2",
889
972
  "vike": "0.4.270",
890
973
  "vite": "~8.3.8",
891
- "vitest": "^5.1.0"
974
+ "vitest": "^5.1.0",
975
+ "zod": "^4.6.7",
976
+ "zustand": "^5.1.0"
892
977
  };
893
978
  /** A version from this package's own manifest, as a range an app takes. */
894
979
  const toRange = (version) => /^\d/.test(version) ? `^${version}` : version;
895
980
  const pickVersions = (names) => Object.fromEntries(names.map((name) => [name, toRange(VERSIONS[name])]));
896
- function createPackageJson({ packageName, isTypeScript, version }) {
981
+ /** The packages each library installs: for the app's code, and for its development only. */
982
+ const LIBRARY_PACKAGES = {
983
+ "tanstack-query": { dependencies: ["@tanstack/react-query"] },
984
+ swr: { dependencies: ["swr"] },
985
+ msw: { devDependencies: ["msw"] },
986
+ zustand: { dependencies: ["zustand"] },
987
+ jotai: { dependencies: ["jotai"] },
988
+ "redux-toolkit": { dependencies: ["@reduxjs/toolkit", "react-redux"] },
989
+ "react-hook-form": { dependencies: [
990
+ "react-hook-form",
991
+ "zod",
992
+ "@hookform/resolvers"
993
+ ] },
994
+ vitest: { devDependencies: [
995
+ "vitest",
996
+ "@testing-library/react",
997
+ "@testing-library/dom",
998
+ "jsdom"
999
+ ] }
1000
+ };
1001
+ function createPackageJson({ packageName, isTypeScript, rendering, libraries, version }) {
1002
+ const renderer = rendering === "spa" ? [] : ["@emotion/server"];
1003
+ const libraryPackages = libraries.flatMap((library) => LIBRARY_PACKAGES[library].dependencies ?? []);
1004
+ const libraryDevPackages = libraries.flatMap((library) => LIBRARY_PACKAGES[library].devDependencies ?? []);
897
1005
  const packageJson = {
898
1006
  name: packageName,
899
1007
  private: true,
@@ -903,12 +1011,14 @@ function createPackageJson({ packageName, isTypeScript, version }) {
903
1011
  dev: "vite",
904
1012
  build: "vite build",
905
1013
  preview: "vite preview",
906
- ...isTypeScript ? { typecheck: "tsc --noEmit" } : {}
1014
+ ...isTypeScript ? { typecheck: "tsc --noEmit" } : {},
1015
+ ...libraries.includes("vitest") ? { test: "vitest run" } : {}
907
1016
  },
908
1017
  dependencies: {
909
1018
  "@soroush.tech/design-system": toRange(version),
910
1019
  ...pickVersions([
911
- "@emotion/server",
1020
+ ...renderer,
1021
+ ...libraryPackages,
912
1022
  "react",
913
1023
  "react-dom",
914
1024
  "vike"
@@ -916,6 +1026,7 @@ function createPackageJson({ packageName, isTypeScript, version }) {
916
1026
  },
917
1027
  devDependencies: pickVersions([
918
1028
  "@vitejs/plugin-react",
1029
+ ...libraryDevPackages,
919
1030
  "vite",
920
1031
  ...isTypeScript ? [
921
1032
  "@types/react",
@@ -926,7 +1037,16 @@ function createPackageJson({ packageName, isTypeScript, version }) {
926
1037
  };
927
1038
  return `${JSON.stringify(packageJson, null, 2)}\n`;
928
1039
  }
929
- const VITE_CONFIG = `import react from '@vitejs/plugin-react'
1040
+ /** The Vite config: with msw, its plugin serves the mock API's worker, in development and in the build. */
1041
+ const createViteConfig = ({ libraries }) => libraries.includes("msw") ? `import react from '@vitejs/plugin-react'
1042
+ import { msw } from 'msw/vite'
1043
+ import vike from 'vike/plugin'
1044
+ import { defineConfig } from 'vite'
1045
+
1046
+ export default defineConfig({
1047
+ plugins: [react(), vike(), msw({ mode: 'worker-only' })],
1048
+ })
1049
+ ` : `import react from '@vitejs/plugin-react'
930
1050
  import vike from 'vike/plugin'
931
1051
  import { defineConfig } from 'vite'
932
1052
 
@@ -953,7 +1073,7 @@ const TSCONFIG = `{
953
1073
  "include": ["src", "vite.config.ts"]
954
1074
  }
955
1075
  `;
956
- const GITIGNORE = `node_modules/
1076
+ const GITIGNORE$1 = `node_modules/
957
1077
  dist/
958
1078
  *.log
959
1079
  .DS_Store
@@ -984,13 +1104,14 @@ const ITEMS_LINK = ` <Link href="/items" underline="hover">
984
1104
  Items
985
1105
  </Link>
986
1106
  `;
987
- function createSources({ title, isTypeScript, scheme, hasSampleData }) {
988
- const t = (typeScriptOnly) => isTypeScript ? typeScriptOnly : "";
989
- const x = isTypeScript ? "ts" : "js";
990
- return {
991
- config: `${t("import type { Config } from 'vike/types'\n\n")}// The settings of every page: https://vike.dev/config
992
- export default {
993
- // Isomorphic: every page is HTML at build time, then the app moves between pages in the
1107
+ /** The layout's light and dark switch, in a page that has JavaScript. */
1108
+ const SCHEME_SWITCH = ` <Button size="sm" variant="outlined" onClick={() => setScheme(otherScheme)}>
1109
+ {otherScheme}
1110
+ </Button>
1111
+ `;
1112
+ /** The settings of each rendering, in +config. */
1113
+ const CONFIG_SETTINGS = {
1114
+ isomorphic: ` // Isomorphic: every page is HTML at build time, then the app moves between pages in the
994
1115
  // browser, with no reload.
995
1116
  prerender: true,
996
1117
  clientRouting: true,
@@ -998,7 +1119,140 @@ export default {
998
1119
  // +Layout is a setting of this app's own: the component every page renders inside.
999
1120
  meta: {
1000
1121
  Layout: { env: { server: true, client: true } },
1001
- },
1122
+ },`,
1123
+ spa: ` // SPA: every page is an empty HTML shell from the build, which the browser renders; the app
1124
+ // moves between pages with no reload.
1125
+ prerender: true,
1126
+ clientRouting: true,
1127
+ // The page and +Layout, a setting of this app's own, load in the browser only.
1128
+ meta: {
1129
+ Page: { env: { server: false, client: true } },
1130
+ Layout: { env: { server: false, client: true } },
1131
+ },`,
1132
+ ssg: ` // SSG: every page is HTML at build time, with no JavaScript in the browser: a link loads the
1133
+ // next page.
1134
+ prerender: true,
1135
+ // The page and +Layout, a setting of this app's own, load at build time only.
1136
+ meta: {
1137
+ Page: { env: { server: true, client: false } },
1138
+ Layout: { env: { server: true, client: false } },
1139
+ },`
1140
+ };
1141
+ /** What the second page says of how it got there. */
1142
+ const ABOUT_TEXT = {
1143
+ isomorphic: `A second page: it is HTML with its styles from the build, and the app moves to it without a
1144
+ reload.`,
1145
+ spa: `A second page: the browser renders it, with its styles, and the app moves to it without a
1146
+ reload.`,
1147
+ ssg: "A second page: it is HTML with its styles from the build, and a link loads it as a new page."
1148
+ };
1149
+ /** Indents each line by `spaces`: the layout's tree, which has no blank line. */
1150
+ const indentLines = (text, spaces) => text.split("\n").map((line) => `${" ".repeat(spaces)}${line}`).join("\n");
1151
+ /**
1152
+ * Where the layout keeps the scheme it switches - a zustand store, a Jotai atom or the Redux
1153
+ * store, else its own state - as the imports and the lines that read it.
1154
+ */
1155
+ function getSchemeHolder(holder, t, scheme) {
1156
+ if (holder === "zustand") return {
1157
+ imports: "import { useScheme } from '../state/scheme'\n",
1158
+ lines: " const { scheme, setScheme } = useScheme()\n"
1159
+ };
1160
+ if (holder === "jotai") return {
1161
+ imports: "import { useAtom } from 'jotai'\nimport { schemeAtom } from '../state/scheme'\n",
1162
+ lines: " const [scheme, setScheme] = useAtom(schemeAtom)\n"
1163
+ };
1164
+ if (holder === "redux-toolkit") return {
1165
+ imports: `import { useDispatch, useSelector } from 'react-redux'\nimport { schemeChanged${t(", type RootState")} } from '../state/store'\n`,
1166
+ lines: ` const scheme = useSelector((state${t(": RootState")}) => state.scheme)
1167
+ const dispatch = useDispatch()
1168
+ const setScheme = (next${t(": 'light' | 'dark'")}) => dispatch(schemeChanged(next))
1169
+ `
1170
+ };
1171
+ return {
1172
+ imports: "",
1173
+ lines: ` const [scheme, setScheme] = useState${t("<'light' | 'dark'>")}('${scheme}')\n`
1174
+ };
1175
+ }
1176
+ /**
1177
+ * The +Layout, the frame every page renders in: it holds the app's providers, the light and dark
1178
+ * switch when the page has JavaScript, and the query client of TanStack Query.
1179
+ */
1180
+ function createLayout({ title, isTypeScript, rendering, libraries, scheme, hasSampleData }) {
1181
+ const t = (typeScriptOnly) => isTypeScript ? typeScriptOnly : "";
1182
+ const x = isTypeScript ? "ts" : "js";
1183
+ const hasSwitch = rendering !== "ssg";
1184
+ const hasQuery = libraries.includes("tanstack-query");
1185
+ const holder = [
1186
+ "zustand",
1187
+ "jotai",
1188
+ "redux-toolkit"
1189
+ ].find((library) => libraries.includes(library));
1190
+ const schemeHolder = getSchemeHolder(holder, t, scheme);
1191
+ const imports = [
1192
+ hasQuery || hasSwitch && holder === void 0 ? `import { useState${t(", type ReactNode")} } from 'react'\n` : t("import type { ReactNode } from 'react'\n"),
1193
+ hasSwitch ? "import { Button } from '@soroush.tech/design-system/Button'\n" : "",
1194
+ "import { Flex } from '@soroush.tech/design-system/Flex'\n",
1195
+ "import { Link } from '@soroush.tech/design-system/Link'\n",
1196
+ "import { Typography } from '@soroush.tech/design-system/Typography'\n",
1197
+ "import { View } from '@soroush.tech/design-system/View'\n",
1198
+ hasQuery ? "import { QueryClient, QueryClientProvider } from '@tanstack/react-query'\n" : "",
1199
+ hasSwitch ? schemeHolder.imports : "",
1200
+ "import { Providers } from '../theme/Providers'\n"
1201
+ ].join("");
1202
+ const about = !hasSwitch ? `The frame every page renders in, inside the app's providers. A page has no JavaScript in the
1203
+ * browser, so it is drawn in the default scheme, which src/theme/Providers.${x} sets.` : holder ? `The frame every page renders in. The app's providers live here, in the app itself, so the
1204
+ * scheme, held in src/state/${holder === "redux-toolkit" ? "store" : "scheme"}.${x}, can switch the theme.` : `The frame every page renders in. The app's providers live here, in the app itself, so the
1205
+ * scheme it holds can switch the theme.`;
1206
+ const hooks = [hasQuery ? " const [queryClient] = useState(() => new QueryClient())\n" : "", hasSwitch ? `${schemeHolder.lines} const otherScheme = scheme === 'light' ? 'dark' : 'light'\n` : ""].join("");
1207
+ const frame = `<Providers${hasSwitch ? " scheme={scheme}" : ""}>
1208
+ <Flex
1209
+ as="header"
1210
+ flexDirection="row"
1211
+ alignItems="center"
1212
+ justifyContent="space-between"
1213
+ gap={2}
1214
+ px={3}
1215
+ py={2}
1216
+ bg="paper"
1217
+ >
1218
+ <Typography variant="h6" as="span">
1219
+ ${title}
1220
+ </Typography>
1221
+ <Flex as="nav" flexDirection="row" alignItems="center" gap={2}>
1222
+ <Link href="/" underline="hover">
1223
+ Home
1224
+ </Link>
1225
+ <Link href="/about" underline="hover">
1226
+ About
1227
+ </Link>
1228
+ ${`${hasSampleData ? ITEMS_LINK : ""}${libraries.includes("react-hook-form") ? FORM_LINK : ""}${hasSwitch ? SCHEME_SWITCH : ""}`.replaceAll(/^ {4}/gm, "")} </Flex>
1229
+ </Flex>
1230
+ <View as="main" px={3} py={4}>
1231
+ {children}
1232
+ </View>
1233
+ </Providers>`;
1234
+ const tree = hasQuery ? `<QueryClientProvider client={queryClient}>
1235
+ ${indentLines(frame, 2)}
1236
+ </QueryClientProvider>` : frame;
1237
+ return `${imports}
1238
+ /**
1239
+ * ${about}
1240
+ */
1241
+ export default function Layout({ children }${t(": { readonly children: ReactNode }")}) {
1242
+ ${hooks} return (
1243
+ ${indentLines(tree, 4)}
1244
+ )
1245
+ }
1246
+ `;
1247
+ }
1248
+ function createSources(facts) {
1249
+ const { title, isTypeScript, rendering } = facts;
1250
+ const t = (typeScriptOnly) => isTypeScript ? typeScriptOnly : "";
1251
+ const x = isTypeScript ? "ts" : "js";
1252
+ return {
1253
+ config: `${t("import type { Config } from 'vike/types'\n\n")}// The settings of every page: https://vike.dev/config
1254
+ export default {
1255
+ ${CONFIG_SETTINGS[rendering]}
1002
1256
  }${t(" satisfies Config")}
1003
1257
  `,
1004
1258
  PageShell: `import { StrictMode } from 'react'
@@ -1006,9 +1260,8 @@ import { CacheProvider, styleCache } from '@soroush.tech/design-system/engine'
1006
1260
  ${t("import type { PageContext } from 'vike/types'\n")}import { PageContextProvider } from './usePageContext'
1007
1261
 
1008
1262
  /**
1009
- * The page inside its +Layout, the same on the server and in the browser. The Emotion cache is the
1010
- * design system's, so the server can find the styles the page used, and every component of the
1011
- * page can read its pageContext.
1263
+ * The page inside its +Layout. The Emotion cache is the design system's, so the styles the page
1264
+ * uses are found where it is drawn, and every component of the page can read its pageContext.
1012
1265
  */
1013
1266
  export function PageShell({ pageContext }${t(": { readonly pageContext: PageContext }")}) {
1014
1267
  const { Page, config } = pageContext
@@ -1029,6 +1282,34 @@ export function PageShell({ pageContext }${t(": { readonly pageContext: PageCont
1029
1282
  </StrictMode>
1030
1283
  )
1031
1284
  }
1285
+ `,
1286
+ spaOnRenderHtml: `import { escapeInject } from 'vike/server'
1287
+ ${t("import type { OnRenderHtmlSync } from 'vike/types'\n")}
1288
+ /** The page's HTML shell, from the build: the browser renders the page in #root. */
1289
+ export const onRenderHtml${t(": OnRenderHtmlSync")} = () => {
1290
+ return escapeInject\`<!doctype html>
1291
+ <html lang="en">
1292
+ <head>
1293
+ <meta charset="UTF-8" />
1294
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
1295
+ <title>${title}</title>
1296
+ </head>
1297
+ <body>
1298
+ <div id="root"></div>
1299
+ </body>
1300
+ </html>\`
1301
+ }
1302
+ `,
1303
+ spaOnRenderClient: `import { createRoot${t(", type Root")} } from 'react-dom/client'
1304
+ ${t("import type { OnRenderClientSync } from 'vike/types'\n")}import { PageShell } from './PageShell'
1305
+
1306
+ let root${t(": Root | undefined")}
1307
+
1308
+ /** Draws the page in the browser, and each page the app moves to. */
1309
+ export const onRenderClient${t(": OnRenderClientSync")} = (pageContext) => {
1310
+ root ??= createRoot(document.getElementById('root')${t("!")})
1311
+ root.render(<PageShell pageContext={pageContext} />)
1312
+ }
1032
1313
  `,
1033
1314
  onRenderHtml: `import createEmotionServer from '@emotion/server/create-instance'
1034
1315
  import { renderToString } from 'react-dom/server'
@@ -1075,55 +1356,7 @@ export const onRenderClient${t(": OnRenderClientSync")} = (pageContext) => {
1075
1356
  }
1076
1357
  }
1077
1358
  `,
1078
- Layout: `import { useState${t(", type ReactNode")} } from 'react'
1079
- import { Button } from '@soroush.tech/design-system/Button'
1080
- import { Flex } from '@soroush.tech/design-system/Flex'
1081
- import { Link } from '@soroush.tech/design-system/Link'
1082
- import { Typography } from '@soroush.tech/design-system/Typography'
1083
- import { View } from '@soroush.tech/design-system/View'
1084
- import { Providers } from '../theme/Providers'
1085
-
1086
- /**
1087
- * The frame every page renders in. The app's providers live here, in the app itself, so the
1088
- * scheme it holds can switch the theme.
1089
- */
1090
- export default function Layout({ children }${t(": { readonly children: ReactNode }")}) {
1091
- const [scheme, setScheme] = useState${t("<'light' | 'dark'>")}('${scheme}')
1092
- const otherScheme = scheme === 'light' ? 'dark' : 'light'
1093
- return (
1094
- <Providers scheme={scheme}>
1095
- <Flex
1096
- as="header"
1097
- flexDirection="row"
1098
- alignItems="center"
1099
- justifyContent="space-between"
1100
- gap={2}
1101
- px={3}
1102
- py={2}
1103
- bg="paper"
1104
- >
1105
- <Typography variant="h6" as="span">
1106
- ${title}
1107
- </Typography>
1108
- <Flex as="nav" flexDirection="row" alignItems="center" gap={2}>
1109
- <Link href="/" underline="hover">
1110
- Home
1111
- </Link>
1112
- <Link href="/about" underline="hover">
1113
- About
1114
- </Link>
1115
- ${hasSampleData ? ITEMS_LINK : ""} <Button size="sm" variant="outlined" onClick={() => setScheme(otherScheme)}>
1116
- {otherScheme}
1117
- </Button>
1118
- </Flex>
1119
- </Flex>
1120
- <View as="main" px={3} py={4}>
1121
- {children}
1122
- </View>
1123
- </Providers>
1124
- )
1125
- }
1126
- `,
1359
+ Layout: createLayout(facts),
1127
1360
  home: `import { Button } from '@soroush.tech/design-system/Button'
1128
1361
  import { Flex } from '@soroush.tech/design-system/Flex'
1129
1362
  import { Typography } from '@soroush.tech/design-system/Typography'
@@ -1154,8 +1387,7 @@ export default function Page() {
1154
1387
  <Flex gap={2}>
1155
1388
  <Typography variant="h2">About</Typography>
1156
1389
  <Typography color="secondary">
1157
- A second page: it is HTML with its styles from the build, and the app moves to it without a
1158
- reload.
1390
+ ${ABOUT_TEXT[rendering]}
1159
1391
  </Typography>
1160
1392
  </Flex>
1161
1393
  )
@@ -1209,8 +1441,30 @@ export default function Page() {
1209
1441
  * The sample data pages: a list of items and a page for each, which read `src/data/items` in their
1210
1442
  * +data hooks, at build time.
1211
1443
  */
1212
- function createSampleDataFiles({ isTypeScript }) {
1444
+ function createSampleDataFiles({ isTypeScript, libraries }) {
1213
1445
  const t = (typeScriptOnly) => isTypeScript ? typeScriptOnly : "";
1446
+ const hasQuery = libraries.includes("tanstack-query");
1447
+ const hasSwr = libraries.includes("swr");
1448
+ const queryImport = (api, fetcher) => hasQuery ? `import { useQuery } from '@tanstack/react-query'\nimport { ${fetcher} } from '${api}'\n` : hasSwr ? `import useSWR from 'swr'\nimport { ${fetcher} } from '${api}'\n` : "";
1449
+ const listRead = hasQuery ? ` const { data: items } = useQuery({
1450
+ queryKey: ['items'],
1451
+ queryFn: fetchItems,
1452
+ initialData: useData${t("<Data>")}(),
1453
+ })` : hasSwr ? ` const initialItems = useData${t("<Data>")}()
1454
+ const { data: items = initialItems } = useSWR('items', fetchItems, {
1455
+ fallbackData: initialItems,
1456
+ })` : ` const items = useData${t("<Data>")}()`;
1457
+ const itemRead = hasQuery ? ` const initialItem = useData${t("<Data>")}()
1458
+ const { data: item } = useQuery({
1459
+ queryKey: ['items', initialItem.id],
1460
+ queryFn: () => fetchItem(initialItem.id),
1461
+ initialData: initialItem,
1462
+ })` : hasSwr ? ` const initialItem = useData${t("<Data>")}()
1463
+ const { data: item = initialItem } = useSWR(
1464
+ ['items', initialItem.id],
1465
+ () => fetchItem(initialItem.id),
1466
+ { fallbackData: initialItem }
1467
+ )` : ` const item = useData${t("<Data>")}()`;
1214
1468
  const x = isTypeScript ? "ts" : "js";
1215
1469
  const dataType = t("\nexport type Data = ReturnType<typeof data>\n");
1216
1470
  const items = `${t(`/** One sample item. */
@@ -1286,11 +1540,11 @@ ${dataType}`;
1286
1540
  const listPage = `import { Flex } from '@soroush.tech/design-system/Flex'
1287
1541
  import { Link } from '@soroush.tech/design-system/Link'
1288
1542
  import { Typography } from '@soroush.tech/design-system/Typography'
1289
- import { useData } from '../usePageContext'
1543
+ ${queryImport("../../data/api", "fetchItems")}import { useData } from '../usePageContext'
1290
1544
  ${t("import type { Data } from './+data'\n")}import { StatusChip } from './StatusChip'
1291
1545
 
1292
1546
  export default function Page() {
1293
- const items = useData${t("<Data>")}()
1547
+ ${listRead}
1294
1548
  return (
1295
1549
  <Flex gap={2}>
1296
1550
  <Typography variant="h2">Items</Typography>
@@ -1332,11 +1586,11 @@ export function onBeforePrerenderStart() {
1332
1586
  const itemPage = `import { Flex } from '@soroush.tech/design-system/Flex'
1333
1587
  import { Link } from '@soroush.tech/design-system/Link'
1334
1588
  import { Typography } from '@soroush.tech/design-system/Typography'
1335
- import { useData } from '../../usePageContext'
1589
+ ${queryImport("../../../data/api", "fetchItem")}import { useData } from '../../usePageContext'
1336
1590
  import { StatusChip } from '../StatusChip'
1337
1591
  ${t("import type { Data } from './+data'\n")}
1338
1592
  export default function Page() {
1339
- const item = useData${t("<Data>")}()
1593
+ ${itemRead}
1340
1594
  return (
1341
1595
  <Flex gap={2} alignItems="flex-start">
1342
1596
  <Typography variant="h2">{item.title}</Typography>
@@ -1378,31 +1632,343 @@ export default function Page() {
1378
1632
  }
1379
1633
  ];
1380
1634
  }
1381
- function createReadme({ title, isTypeScript, hasSampleData }) {
1635
+ /** How the README says each rendering works, and which files render the pages. */
1636
+ const README_RENDERING = {
1637
+ isomorphic: {
1638
+ summary: "prerendered at build time with its styles in the HTML, then moving between pages with no reload.",
1639
+ renderers: "`+onRenderHtml` and `+onRenderClient` render the pages, with the styles each page uses in its HTML."
1640
+ },
1641
+ spa: {
1642
+ summary: "a single-page app: each page is an HTML shell from the build, rendered in the browser, which moves between pages with no reload.",
1643
+ renderers: "`+onRenderHtml` writes the HTML shell of each page, and `+onRenderClient` renders the page in it."
1644
+ },
1645
+ ssg: {
1646
+ summary: "every page prerendered to HTML at build time, with its styles, and no JavaScript in the browser.",
1647
+ renderers: "`+onRenderHtml` renders the pages to HTML, with the styles each page uses."
1648
+ }
1649
+ };
1650
+ function createReadme({ title, isTypeScript, rendering, libraries, hasSampleData }) {
1382
1651
  const x = isTypeScript ? "ts" : "js";
1652
+ const { summary, renderers } = README_RENDERING[rendering];
1653
+ const sampleData = hasSampleData ? `- \`src/pages/items/\` lists the sample items of \`src/data/items.${x}\`, with a page for each.
1654
+ Their \`+data\` hooks read the data at build time: make them fetch your own.
1655
+ ` : "";
1656
+ const libraryLines = {
1657
+ "tanstack-query": `- [TanStack Query](https://tanstack.com/query): the query client lives in \`+Layout\`.${hasSampleData ? ` The items pages start on their build-time data, then query \`src/data/api.${x}\` in the browser.` : ""}\n`,
1658
+ msw: `- [msw](https://mswjs.io): \`src/mocks/handlers.${x}\` is a mock API, which answers in the browser while \`VITE_MSW\` in \`.env\` is true.\n`,
1659
+ zustand: `- [zustand](https://zustand.docs.pmnd.rs): \`src/state/scheme.${x}\` holds the color scheme, in a store.\n`,
1660
+ jotai: `- [Jotai](https://jotai.org): \`src/state/scheme.${x}\` holds the color scheme, in an atom.\n`,
1661
+ swr: `- [SWR](https://swr.vercel.app): fetches and caches data.${hasSampleData ? ` The items pages start on their build-time data, then fetch \`src/data/api.${x}\` in the browser.` : ""}\n`,
1662
+ "redux-toolkit": `- [Redux Toolkit](https://redux-toolkit.js.org): \`src/state/store.${x}\` holds the color scheme, in a slice of the store \`PageShell\` provides.\n`,
1663
+ "react-hook-form": `- [React Hook Form](https://react-hook-form.com) and [Zod](https://zod.dev): \`/form\` is a form whose values a Zod schema checks.\n`,
1664
+ vitest: `- [Vitest](https://vitest.dev) and [Testing Library](https://testing-library.com): \`npm run test\` runs \`src/pages/index/Page.test.${x}x\`.\n`
1665
+ };
1383
1666
  return `# ${title}
1384
1667
 
1385
- A [Vike](https://vike.dev) app on the [@soroush.tech design system](https://docs.soroush.tech),
1386
- prerendered at build time with its styles in the HTML, then moving between pages with no reload.
1668
+ A [Vike](https://vike.dev) app on the [@soroush.tech design system](https://docs.soroush.tech):
1669
+ ${summary}
1387
1670
 
1388
1671
  - \`npm run dev\` starts it, \`npm run build\` builds it, and \`npm run preview\` serves the build.
1389
1672
  - \`src/pages/\` holds the pages: a folder per route, each with its \`+Page\`.
1390
1673
  - \`src/pages/+Layout.${x}x\` is the frame every page renders in, inside the app's providers.
1391
1674
  - \`src/theme/themes.${x}\` holds the light and the dark theme: make them your own.
1392
- - \`src/pages/+onRenderHtml.${x}x\` and \`+onRenderClient.${x}x\` render the pages, with the styles each
1393
- page uses in its HTML.
1394
- ${hasSampleData ? `- \`src/pages/items/\` lists the sample items of \`src/data/items.${x}\`, with a page for each.
1395
- Their \`+data\` hooks read the data at build time: make them fetch your own.
1396
- ` : ""}
1675
+ - In \`src/pages/\`, ${renderers}
1676
+ ${sampleData}${libraries.map((library) => libraryLines[library]).join("")}
1397
1677
  Fonts: the theme names Space Grotesk and JetBrains Mono, and does not load them. See
1398
1678
  https://docs.soroush.tech/design-system/getting-started/installation/#fonts
1399
1679
  `;
1400
1680
  }
1681
+ /** The layout's link to the form page, when the app has React Hook Form. */
1682
+ const FORM_LINK = ` <Link href="/form" underline="hover">
1683
+ Form
1684
+ </Link>
1685
+ `;
1686
+ /**
1687
+ * The form page of React Hook Form: two fields of the design system's TextInput, which a Zod
1688
+ * schema checks before the form is sent.
1689
+ */
1690
+ function createFormPage(isTypeScript) {
1691
+ const t = (typeScriptOnly) => isTypeScript ? typeScriptOnly : "";
1692
+ return `import { useState } from 'react'
1693
+ import { zodResolver } from '@hookform/resolvers/zod'
1694
+ import { Controller, useForm } from 'react-hook-form'
1695
+ import { z } from 'zod'
1696
+ import { Button } from '@soroush.tech/design-system/Button'
1697
+ import { Flex } from '@soroush.tech/design-system/Flex'
1698
+ import { TextInput } from '@soroush.tech/design-system/TextInput'
1699
+ import { Typography } from '@soroush.tech/design-system/Typography'
1700
+
1701
+ /** What the form takes, and what it says when a value will not do. */
1702
+ const schema = z.object({
1703
+ name: z.string().trim().min(1, 'Your name, please.'),
1704
+ email: z.email('An email address, please.'),
1705
+ })
1706
+ ${t(`
1707
+ type Values = z.infer<typeof schema>
1708
+ `)}
1709
+ export default function Page() {
1710
+ const [sent, setSent] = useState${t("<Values | null>")}(null)
1711
+ const { control, handleSubmit } = useForm${t("<Values>")}({
1712
+ resolver: zodResolver(schema),
1713
+ defaultValues: { name: '', email: '' },
1714
+ })
1715
+ return (
1716
+ <Flex gap={2} alignItems="flex-start">
1717
+ <Typography variant="h2">Form</Typography>
1718
+ <Typography color="secondary">
1719
+ React Hook Form holds the values, and a Zod schema checks them when the form is sent.
1720
+ </Typography>
1721
+ <form noValidate onSubmit={handleSubmit(setSent)}>
1722
+ <Flex gap={2} alignItems="flex-start">
1723
+ <Controller
1724
+ name="name"
1725
+ control={control}
1726
+ render={({ field, fieldState }) => (
1727
+ <Flex gap={1}>
1728
+ <TextInput
1729
+ name={field.name}
1730
+ value={field.value}
1731
+ onChange={field.onChange}
1732
+ placeholder="Name"
1733
+ error={fieldState.invalid}
1734
+ inputProps={{ 'aria-label': 'Name', onBlur: field.onBlur }}
1735
+ />
1736
+ <Typography variant="caption" color="error">
1737
+ {fieldState.error?.message}
1738
+ </Typography>
1739
+ </Flex>
1740
+ )}
1741
+ />
1742
+ <Controller
1743
+ name="email"
1744
+ control={control}
1745
+ render={({ field, fieldState }) => (
1746
+ <Flex gap={1}>
1747
+ <TextInput
1748
+ name={field.name}
1749
+ value={field.value}
1750
+ onChange={field.onChange}
1751
+ type="email"
1752
+ placeholder="Email"
1753
+ error={fieldState.invalid}
1754
+ inputProps={{ 'aria-label': 'Email', onBlur: field.onBlur }}
1755
+ />
1756
+ <Typography variant="caption" color="error">
1757
+ {fieldState.error?.message}
1758
+ </Typography>
1759
+ </Flex>
1760
+ )}
1761
+ />
1762
+ <Button type="submit">Send</Button>
1763
+ </Flex>
1764
+ </form>
1765
+ {sent ? <Typography>Thanks, {sent.name}: the form was valid.</Typography> : null}
1766
+ </Flex>
1767
+ )
1768
+ }
1769
+ `;
1770
+ }
1771
+ /**
1772
+ * PageShell with Redux Toolkit: the store's provider wraps every page, so +Layout and the pages
1773
+ * read the store.
1774
+ */
1775
+ function withStore(pageShell) {
1776
+ const lines = pageShell.replace("import { CacheProvider, styleCache } from '@soroush.tech/design-system/engine'\n", "import { CacheProvider, styleCache } from '@soroush.tech/design-system/engine'\nimport { Provider as StoreProvider } from 'react-redux'\n").replace("import { PageContextProvider } from './usePageContext'\n", "import { store } from '../state/store'\nimport { PageContextProvider } from './usePageContext'\n").split("\n");
1777
+ const start = lines.findIndex((line) => line.trimStart().startsWith("<PageContextProvider"));
1778
+ const end = lines.findIndex((line) => line.trimStart() === "</PageContextProvider>");
1779
+ const indent = lines[start].slice(0, lines[start].indexOf("<"));
1780
+ return [
1781
+ ...lines.slice(0, start),
1782
+ `${indent}<StoreProvider store={store}>`,
1783
+ ...lines.slice(start, end + 1).map((line) => ` ${line}`),
1784
+ `${indent}</StoreProvider>`,
1785
+ ...lines.slice(end + 1)
1786
+ ].join("\n");
1787
+ }
1788
+ /**
1789
+ * The client renderer with msw: the mock API starts as the module loads, and the first page waits
1790
+ * for it, so no request leaves before the mock can answer it.
1791
+ */
1792
+ function withMocks(onRenderClient) {
1793
+ return onRenderClient.replaceAll("OnRenderClientSync", "OnRenderClientAsync").replace("import { PageShell } from './PageShell'\n", "import { startMocks } from '../mocks/start'\nimport { PageShell } from './PageShell'\n").replace(/^(let root.*\n)/m, "$1const mocks = startMocks()\n").replace("= (pageContext) => {\n", "= async (pageContext) => {\n await mocks\n");
1794
+ }
1795
+ /** The files each library adds: its setup, and the example that uses it. */
1796
+ function createLibraryFiles({ title, isTypeScript, libraries, scheme, hasSampleData }) {
1797
+ const t = (typeScriptOnly) => isTypeScript ? typeScriptOnly : "";
1798
+ const x = isTypeScript ? "ts" : "js";
1799
+ const files = [];
1800
+ const hasMocks = libraries.includes("msw");
1801
+ if (libraries.includes("zustand")) files.push({
1802
+ path: `src/state/scheme.${x}`,
1803
+ content: `import { create } from 'zustand'
1804
+ ${t(`
1805
+ interface SchemeState {
1806
+ scheme: 'light' | 'dark'
1807
+ setScheme: (scheme: 'light' | 'dark') => void
1808
+ }
1809
+ `)}
1810
+ /** The color scheme the app is drawn in: a zustand store, which any component can read. */
1811
+ export const useScheme = create${t("<SchemeState>()")}((set) => ({
1812
+ scheme: '${scheme}',
1813
+ setScheme: (scheme) => set({ scheme }),
1814
+ }))
1815
+ `
1816
+ });
1817
+ if (libraries.includes("jotai")) files.push({
1818
+ path: `src/state/scheme.${x}`,
1819
+ content: `import { atom } from 'jotai'
1820
+
1821
+ /** The color scheme the app is drawn in: a Jotai atom, which any component can read. */
1822
+ export const schemeAtom = atom${t("<'light' | 'dark'>")}('${scheme}')
1823
+ `
1824
+ });
1825
+ if (hasMocks) {
1826
+ const handlers = hasSampleData ? `import { http, HttpResponse } from 'msw'
1827
+ import { items } from '../data/items'
1828
+
1829
+ /** The mock API: what it answers, by method and path. Add a handler for each call the app makes. */
1830
+ export const handlers = [
1831
+ http.get('/api/items', () =>
1832
+ HttpResponse.json(items.map(({ id, title, status }) => ({ id, title, status })))
1833
+ ),
1834
+ http.get('/api/items/:id', ({ params }) => {
1835
+ const item = items.find(({ id }) => id === params.id)
1836
+ return item ? HttpResponse.json(item) : new HttpResponse(null, { status: 404 })
1837
+ }),
1838
+ ]
1839
+ ` : `import { http, HttpResponse } from 'msw'
1840
+
1841
+ /** The mock API: what it answers, by method and path. Add a handler for each call the app makes. */
1842
+ export const handlers = [
1843
+ http.get('/api/hello', () => HttpResponse.json({ message: 'Hello from the mock API' })),
1844
+ ]
1845
+ `;
1846
+ files.push({
1847
+ path: `src/mocks/handlers.${x}`,
1848
+ content: handlers
1849
+ }, {
1850
+ path: `src/mocks/browser.${x}`,
1851
+ content: `import { setupWorker } from 'msw/browser'
1852
+ import { handlers } from './handlers'
1853
+
1854
+ /** The mock API in the browser: a service worker answers the requests the handlers match. */
1855
+ export const worker = setupWorker(...handlers)
1856
+ `
1857
+ }, {
1858
+ path: `src/mocks/start.${x}`,
1859
+ content: `/**
1860
+ * Starts the mock API in the browser while VITE_MSW, in .env, is true. Set it to false once the
1861
+ * app's own API answers.
1862
+ */
1863
+ export async function startMocks() {
1864
+ if (import.meta.env.VITE_MSW !== 'true') return
1865
+ const { worker } = await import('./browser')
1866
+ await worker.start()
1867
+ }
1868
+ `
1869
+ }, {
1870
+ path: ".env",
1871
+ content: `# The mock API in src/mocks answers in the browser while this is true. Set it to false once
1872
+ # the app's own API answers.
1873
+ VITE_MSW=true
1874
+ `
1875
+ });
1876
+ }
1877
+ if (libraries.includes("redux-toolkit")) files.push({
1878
+ path: `src/state/store.${x}`,
1879
+ content: `import { configureStore, createSlice${t(", type PayloadAction")} } from '@reduxjs/toolkit'
1880
+
1881
+ /** The color scheme the app is drawn in: a slice of the store. */
1882
+ const schemeSlice = createSlice({
1883
+ name: 'scheme',
1884
+ initialState: '${scheme}'${t(" as 'light' | 'dark'")},
1885
+ reducers: {
1886
+ schemeChanged: (_scheme, action${t(": PayloadAction<'light' | 'dark'>")}) => action.payload,
1887
+ },
1888
+ })
1889
+
1890
+ export const { schemeChanged } = schemeSlice.actions
1891
+
1892
+ /** The app's Redux store, which PageShell provides to every page. */
1893
+ export const store = configureStore({ reducer: { scheme: schemeSlice.reducer } })
1894
+ ${t(`
1895
+ export type RootState = ReturnType<typeof store.getState>
1896
+ `)}`
1897
+ });
1898
+ if (libraries.includes("react-hook-form")) files.push({
1899
+ path: `src/pages/form/+Page.${x}x`,
1900
+ content: createFormPage(isTypeScript)
1901
+ });
1902
+ if (libraries.includes("vitest")) files.push({
1903
+ path: `vitest.config.${x}`,
1904
+ content: `import react from '@vitejs/plugin-react'
1905
+ import { defineConfig } from 'vitest/config'
1906
+
1907
+ // The tests render components in jsdom, with no Vike: a page is a component like any other.
1908
+ export default defineConfig({
1909
+ plugins: [react()],
1910
+ test: { environment: 'jsdom' },
1911
+ })
1912
+ `
1913
+ }, {
1914
+ path: `src/pages/index/Page.test.${x}x`,
1915
+ content: `import { render, screen } from '@testing-library/react'
1916
+ import { describe, expect, it } from 'vitest'
1917
+ import { Providers } from '../../theme/Providers'
1918
+ import Page from './+Page'
1919
+
1920
+ describe('the home page', () => {
1921
+ it('shows the app title', () => {
1922
+ render(
1923
+ <Providers>
1924
+ <Page />
1925
+ </Providers>
1926
+ )
1927
+ expect(screen.getByRole('heading', { name: '${title.replaceAll("'", String.raw`\'`)}' })).toBeTruthy()
1928
+ })
1929
+ })
1930
+ `
1931
+ });
1932
+ if ((libraries.includes("tanstack-query") || libraries.includes("swr")) && hasSampleData) files.push({
1933
+ path: `src/data/api.${x}`,
1934
+ content: hasMocks ? `${t("import type { Item } from './items'\n\n")}/** The items, from the API: while VITE_MSW is true, the mock API of src/mocks answers. */
1935
+ export async function fetchItems()${t(": Promise<Pick<Item, 'id' | 'title' | 'status'>[]>")} {
1936
+ const response = await fetch('/api/items')
1937
+ if (!response.ok) throw new Error(\`GET /api/items answered \${response.status}\`)
1938
+ return response.json()
1939
+ }
1940
+
1941
+ /** One item, from the API. */
1942
+ export async function fetchItem(id${t(": string")})${t(": Promise<Item>")} {
1943
+ const response = await fetch(\`/api/items/\${id}\`)
1944
+ if (!response.ok) throw new Error(\`GET /api/items/\${id} answered \${response.status}\`)
1945
+ return response.json()
1946
+ }
1947
+ ` : `import { items } from './items'
1948
+
1949
+ /** The items, as an API would answer: make it fetch from yours. */
1950
+ export async function fetchItems() {
1951
+ return items.map(({ id, title, status }) => ({ id, title, status }))
1952
+ }
1953
+
1954
+ /** One item, as an API would answer: make it fetch from yours. */
1955
+ export async function fetchItem(id${t(": string")}) {
1956
+ const item = items.find((candidate) => candidate.id === id)
1957
+ if (!item) throw new Error(\`There is no item \${id}.\`)
1958
+ return item
1959
+ }
1960
+ `
1961
+ });
1962
+ return files;
1963
+ }
1401
1964
  /** The files of the Vike app `facts` describe. */
1402
1965
  function createFiles(facts) {
1403
- const { isTypeScript, scheme } = facts;
1966
+ const { isTypeScript, rendering, scheme, libraries } = facts;
1404
1967
  const x = isTypeScript ? "ts" : "js";
1405
1968
  const sources = createSources(facts);
1969
+ const isSpa = rendering === "spa";
1970
+ const renderer = rendering === "ssg" ? void 0 : isSpa ? sources.spaOnRenderClient : sources.onRenderClient;
1971
+ const onRenderClient = renderer && libraries.includes("msw") ? withMocks(renderer) : renderer;
1406
1972
  return [
1407
1973
  {
1408
1974
  path: "package.json",
@@ -1410,7 +1976,7 @@ function createFiles(facts) {
1410
1976
  },
1411
1977
  {
1412
1978
  path: `vite.config.${x}`,
1413
- content: VITE_CONFIG
1979
+ content: createViteConfig(facts)
1414
1980
  },
1415
1981
  ...isTypeScript ? [{
1416
1982
  path: "tsconfig.json",
@@ -1418,7 +1984,7 @@ function createFiles(facts) {
1418
1984
  }] : [],
1419
1985
  {
1420
1986
  path: ".gitignore",
1421
- content: GITIGNORE
1987
+ content: GITIGNORE$1
1422
1988
  },
1423
1989
  {
1424
1990
  path: "README.md",
@@ -1446,7 +2012,7 @@ function createFiles(facts) {
1446
2012
  },
1447
2013
  {
1448
2014
  path: `src/pages/PageShell.${x}x`,
1449
- content: sources.PageShell
2015
+ content: libraries.includes("redux-toolkit") ? withStore(sources.PageShell) : sources.PageShell
1450
2016
  },
1451
2017
  {
1452
2018
  path: `src/pages/usePageContext.${x}x`,
@@ -1454,12 +2020,12 @@ function createFiles(facts) {
1454
2020
  },
1455
2021
  {
1456
2022
  path: `src/pages/+onRenderHtml.${x}x`,
1457
- content: sources.onRenderHtml
2023
+ content: isSpa ? sources.spaOnRenderHtml : sources.onRenderHtml
1458
2024
  },
1459
- {
2025
+ ...onRenderClient ? [{
1460
2026
  path: `src/pages/+onRenderClient.${x}x`,
1461
- content: sources.onRenderClient
1462
- },
2027
+ content: onRenderClient
2028
+ }] : [],
1463
2029
  {
1464
2030
  path: `src/pages/+Layout.${x}x`,
1465
2031
  content: sources.Layout
@@ -1476,15 +2042,102 @@ function createFiles(facts) {
1476
2042
  path: `src/pages/_error/+Page.${x}x`,
1477
2043
  content: sources.error
1478
2044
  },
1479
- ...facts.hasSampleData ? createSampleDataFiles(facts) : []
2045
+ ...facts.hasSampleData ? createSampleDataFiles(facts) : [],
2046
+ ...createLibraryFiles(facts)
1480
2047
  ];
1481
2048
  }
1482
- // src/create/starters.ts
1483
- /** The starters, by the name `--framework` takes. The first is the default. */
1484
- const STARTERS = { vike: {
2049
+ const vikeStarter = {
1485
2050
  title: "Vike",
1486
2051
  createFiles
1487
- } };
2052
+ };
2053
+ // src/create/starters.ts
2054
+ /** The renderings, in the order create offers them. The first is the default. */
2055
+ const RENDERINGS = [
2056
+ "isomorphic",
2057
+ "spa",
2058
+ "ssg"
2059
+ ];
2060
+ /** The starters, by the name `--framework` takes. The first is the default. */
2061
+ const STARTERS = { vike: vikeStarter };
2062
+ // src/create/workspace.ts
2063
+ /** The layouts, in the order create offers them. The first is the default. */
2064
+ const LAYOUTS = ["workspace", "standalone"];
2065
+ /** Where a workspace keeps the app, from its root. */
2066
+ const APP_FOLDER = "apps/web";
2067
+ /** The package name of the app in the workspace named `packageName`. */
2068
+ const toAppPackageName = (packageName) => `@${packageName}/web`;
2069
+ /** The command that runs `script` of the app's package, from the workspace's root. */
2070
+ function runInApp(packageManager, app, script) {
2071
+ switch (packageManager) {
2072
+ case "npm": return `npm run ${script} --workspace=${app}`;
2073
+ case "pnpm": return `pnpm --filter ${app} ${script}`;
2074
+ case "yarn": return `yarn workspace ${app} ${script}`;
2075
+ case "bun": return `bun run --filter ${app} ${script}`;
2076
+ }
2077
+ }
2078
+ const WORKSPACES = ["apps/*", "services/*"];
2079
+ const GITIGNORE = `node_modules/
2080
+ *.log
2081
+ .DS_Store
2082
+ `;
2083
+ function createRootFiles(facts) {
2084
+ const { packageName, title, isTypeScript, libraries, packageManager } = facts;
2085
+ const app = toAppPackageName(packageName);
2086
+ const scripts = [
2087
+ "dev",
2088
+ "build",
2089
+ "preview",
2090
+ ...isTypeScript ? ["typecheck"] : [],
2091
+ ...libraries.includes("vitest") ? ["test"] : []
2092
+ ];
2093
+ const isPnpm = packageManager === "pnpm";
2094
+ const packageJson = {
2095
+ name: packageName,
2096
+ private: true,
2097
+ ...isPnpm ? {} : { workspaces: WORKSPACES },
2098
+ scripts: Object.fromEntries(scripts.map((script) => [script, runInApp(packageManager, app, script)]))
2099
+ };
2100
+ const run = (script) => packageManager === "npm" || packageManager === "bun" ? `${packageManager} run ${script}` : `${packageManager} ${script}`;
2101
+ return [
2102
+ {
2103
+ path: "package.json",
2104
+ content: `${JSON.stringify(packageJson, null, 2)}\n`
2105
+ },
2106
+ ...isPnpm ? [{
2107
+ path: "pnpm-workspace.yaml",
2108
+ content: `packages:\n${WORKSPACES.map((glob) => ` - ${glob}\n`).join("")}`
2109
+ }] : [],
2110
+ {
2111
+ path: ".gitignore",
2112
+ content: GITIGNORE
2113
+ },
2114
+ {
2115
+ path: "README.md",
2116
+ content: `# ${title}
2117
+
2118
+ A workspace: each app and service is a package of its own, installed together from here.
2119
+
2120
+ - \`${APP_FOLDER}/\` is the web app, \`${app}\`: its README says how it is built.
2121
+ - \`services/\` is for back-end services, such as an API: add one as a folder with its own
2122
+ \`package.json\`.
2123
+
2124
+ From here, \`${run("dev")}\` starts the web app, \`${run("build")}\` builds it, and \`${run("preview")}\`
2125
+ serves the build.
2126
+ `
2127
+ },
2128
+ {
2129
+ path: "services/.gitkeep",
2130
+ content: ""
2131
+ }
2132
+ ];
2133
+ }
2134
+ /** The files of a workspace holding the app whose files are `appFiles`, in `apps/web`. */
2135
+ function createWorkspaceFiles(appFiles, facts) {
2136
+ return [...createRootFiles(facts), ...appFiles.map((file) => ({
2137
+ ...file,
2138
+ path: `${APP_FOLDER}/${file.path}`
2139
+ }))];
2140
+ }
1488
2141
  // src/create/create.ts
1489
2142
  const DEFAULT_NAME = "my-app";
1490
2143
  const APP_NAME = /^[A-Za-z0-9][A-Za-z0-9._~-]*$/;
@@ -1537,9 +2190,54 @@ function isInsideRepository(folder, io) {
1537
2190
  const { status, stdout } = io.run("git", ["rev-parse", "--is-inside-work-tree"], { cwd: folder });
1538
2191
  return status === 0 && stdout.trim() === "true";
1539
2192
  }
2193
+ const YES_OR_NO = [{
2194
+ value: "yes",
2195
+ label: "Yes"
2196
+ }, {
2197
+ value: "no",
2198
+ label: "No"
2199
+ }];
1540
2200
  async function askLanguage(io) {
1541
- const answer = await io.ask("TypeScript or JavaScript? (TypeScript) ");
1542
- return !/^j(s|avascript)?$/i.test(answer.trim());
2201
+ return await io.select("Language", [{
2202
+ value: "ts",
2203
+ label: "TypeScript (recommended)"
2204
+ }, {
2205
+ value: "js",
2206
+ label: "JavaScript"
2207
+ }]) === "ts";
2208
+ }
2209
+ /** Asks for the package manager, starting on the one that ran create. */
2210
+ async function askPackageManager(io, detected) {
2211
+ const choices = PACKAGE_MANAGERS.map((name) => ({
2212
+ value: name,
2213
+ label: name === detected ? `${name} (the one that ran create)` : name
2214
+ }));
2215
+ return await io.select("Package manager", choices, PACKAGE_MANAGERS.indexOf(detected));
2216
+ }
2217
+ /**
2218
+ * The package manager to install with, or why it cannot be used: one other than the one that ran
2219
+ * create must answer `--version`, which also says whether a yarn is Berry.
2220
+ */
2221
+ function resolvePackageManager(name, detected, io) {
2222
+ if (name === detected.name) return detected;
2223
+ const { status, stdout } = io.run(name, ["--version"], { cwd: io.cwd });
2224
+ if (status !== 0) return { refusal: `${name} is not installed: install it, or pick another package manager.` };
2225
+ return {
2226
+ name,
2227
+ isYarnBerry: name === "yarn" && Number.parseInt(stdout, 10) >= 2
2228
+ };
2229
+ }
2230
+ /** What the repository question says of each layout. */
2231
+ const LAYOUT_LABELS = {
2232
+ workspace: "Workspace (recommended): the app in apps/web, with room for more apps and services",
2233
+ standalone: "Standalone: the app alone"
2234
+ };
2235
+ async function askLayout(io) {
2236
+ const choices = LAYOUTS.map((value) => ({
2237
+ value,
2238
+ label: LAYOUT_LABELS[value]
2239
+ }));
2240
+ return await io.select("Repository", choices);
1543
2241
  }
1544
2242
  async function askTitle(io, name) {
1545
2243
  return (await io.ask(`App title? (${name}) `)).trim() || name;
@@ -1547,9 +2245,34 @@ async function askTitle(io, name) {
1547
2245
  async function askName(io) {
1548
2246
  return (await io.ask(`App name? (${DEFAULT_NAME}) `)).trim() || DEFAULT_NAME;
1549
2247
  }
2248
+ /** What the rendering question says of each one. */
2249
+ const RENDERING_LABELS = {
2250
+ isomorphic: "Isomorphic (recommended): HTML from the build, then no reload",
2251
+ spa: "SPA: rendered in the browser",
2252
+ ssg: "SSG: HTML only, no JavaScript"
2253
+ };
2254
+ async function askRendering(io) {
2255
+ const choices = RENDERINGS.map((value) => ({
2256
+ value,
2257
+ label: RENDERING_LABELS[value]
2258
+ }));
2259
+ return await io.select("Rendering", choices);
2260
+ }
2261
+ /** Asks for the libraries, again while two of one group are picked. */
2262
+ async function askLibraries(io) {
2263
+ const choices = LIBRARIES.map(({ name, label }) => ({
2264
+ value: name,
2265
+ label
2266
+ }));
2267
+ for (;;) {
2268
+ const libraries = await io.selectMany("Libraries", choices);
2269
+ const conflict = findLibraryConflict(libraries);
2270
+ if (!conflict) return libraries;
2271
+ io.write(`${conflict}\n`);
2272
+ }
2273
+ }
1550
2274
  async function askSampleData(io) {
1551
- const answer = await io.ask("Add sample data pages? (y/N) ");
1552
- return /^y(es)?$/i.test(answer.trim());
2275
+ return await io.select("Add sample data pages?", YES_OR_NO, 1) === "yes";
1553
2276
  }
1554
2277
  /** Whether to create the app: never on a dry run or with no terminal, else on --yes or a yes. */
1555
2278
  async function isApproved(options, isPreviewOnly, io) {
@@ -1562,8 +2285,7 @@ async function isApproved(options, isPreviewOnly, io) {
1562
2285
  return false;
1563
2286
  }
1564
2287
  if (options.isConfirmed) return true;
1565
- const answer = (await io.ask("Create it? (Y/n) ")).trim();
1566
- const isYes = answer === "" || /^y(es)?$/i.test(answer);
2288
+ const isYes = await io.select("Create it?", YES_OR_NO) === "yes";
1567
2289
  if (!isYes) io.write("Nothing was written.\n");
1568
2290
  return isYes;
1569
2291
  }
@@ -1627,32 +2349,54 @@ async function runCreate(options, io, designSystem, { starters = STARTERS, fileS
1627
2349
  io.write(`${nameRefusal}\n`);
1628
2350
  return 1;
1629
2351
  }
2352
+ const target = join(realpathSync(io.cwd), name);
2353
+ const folder = getFolderState(target, name);
2354
+ if (typeof folder === "object") {
2355
+ io.write(`${folder.refusal}\n`);
2356
+ return 1;
2357
+ }
1630
2358
  const title = (options.title ?? (canAsk ? await askTitle(io, name) : name)).trim() || name;
1631
2359
  if (isRefusedTitle(title)) {
1632
2360
  io.write(`${title} is not a title create can use: it cannot hold \` $ { } < > or \\.\n`);
1633
2361
  return 1;
1634
2362
  }
1635
2363
  const packageName = toPackageName(name);
1636
- const target = join(realpathSync(io.cwd), name);
1637
- const folder = getFolderState(target, name);
1638
- if (typeof folder === "object") {
1639
- io.write(`${folder.refusal}\n`);
2364
+ const isTypeScript = options.isTypeScript ?? (canAsk ? await askLanguage(io) : true);
2365
+ const detected = readPackageManager(userAgent);
2366
+ const packageManager = resolvePackageManager(options.packageManager ?? (canAsk ? await askPackageManager(io, detected.name) : detected.name), detected, io);
2367
+ if ("refusal" in packageManager) {
2368
+ io.write(`${packageManager.refusal}\n`);
1640
2369
  return 1;
1641
2370
  }
1642
- const isTypeScript = options.isTypeScript ?? (canAsk ? await askLanguage(io) : true);
2371
+ const isWorkspace = (options.layout ?? (canAsk ? await askLayout(io) : LAYOUTS[0])) === "workspace";
2372
+ const rendering = options.rendering ?? (canAsk ? await askRendering(io) : RENDERINGS[0]);
2373
+ const libraryRefusal = rendering === "ssg" && options.libraries?.length ? "An SSG app has no JavaScript in the browser, so it takes no library: leave out --with." : findLibraryConflict(options.libraries ?? []);
2374
+ if (libraryRefusal) {
2375
+ io.write(`${libraryRefusal}\n`);
2376
+ return 1;
2377
+ }
2378
+ const libraries = options.libraries ?? (canAsk && rendering !== "ssg" ? await askLibraries(io) : []);
1643
2379
  const scheme = options.scheme ?? (canAsk ? await askScheme(io) : "light");
1644
2380
  const hasSampleData = options.hasSampleData ?? (canAsk ? await askSampleData(io) : false);
1645
- const packageManager = readPackageManager(userAgent);
2381
+ const appFiles = starter.createFiles({
2382
+ name,
2383
+ packageName: isWorkspace ? toAppPackageName(packageName) : packageName,
2384
+ title,
2385
+ isTypeScript,
2386
+ rendering,
2387
+ libraries,
2388
+ scheme,
2389
+ hasSampleData,
2390
+ version: designSystem.version
2391
+ });
1646
2392
  const plan = {
1647
- creates: starter.createFiles({
1648
- name,
2393
+ creates: isWorkspace ? createWorkspaceFiles(appFiles, {
1649
2394
  packageName,
1650
2395
  title,
1651
2396
  isTypeScript,
1652
- scheme,
1653
- hasSampleData,
1654
- version: designSystem.version
1655
- }),
2397
+ libraries,
2398
+ packageManager: packageManager.name
2399
+ }) : appFiles,
1656
2400
  edits: [],
1657
2401
  skips: [],
1658
2402
  manual: [],
@@ -1660,7 +2404,8 @@ async function runCreate(options, io, designSystem, { starters = STARTERS, fileS
1660
2404
  };
1661
2405
  const language = isTypeScript ? "TypeScript" : "JavaScript";
1662
2406
  const packageNote = packageName === name ? "" : ` (package ${packageName})`;
1663
- io.write(`create will make ${name}${packageNote}, a ${starter.title} app in ${language}, in ./${name}:\n\n`);
2407
+ const renderingName = rendering === "isomorphic" ? rendering : rendering.toUpperCase();
2408
+ io.write(`create will make ${name}${packageNote}, a ${starter.title} app in ${language} (${renderingName}), ${isWorkspace ? "in a workspace, " : ""}in ./${name}:\n\n`);
1664
2409
  io.write(`${formatPlan(plan)}\n`);
1665
2410
  if (!await isApproved(options, isPreviewOnly, io)) return 0;
1666
2411
  return writeAndInstall({
@@ -1671,8 +2416,57 @@ async function runCreate(options, io, designSystem, { starters = STARTERS, fileS
1671
2416
  packageManager
1672
2417
  }, options, io, fileSystem);
1673
2418
  }
2419
+ // src/prompt.ts
2420
+ /** Stopped with Ctrl+C or Escape, before an answer. */
2421
+ var CancelledError = class extends Error {
2422
+ constructor() {
2423
+ super("Stopped before an answer.");
2424
+ this.name = "CancelledError";
2425
+ }
2426
+ };
2427
+ /** Reads a key as Node's `keypress` event names it. */
2428
+ function readChoiceKey(key) {
2429
+ if (!key) return "none";
2430
+ if (key.ctrl && key.name === "c" || key.name === "escape") return "cancel";
2431
+ if (key.name === "up" || key.name === "k") return "up";
2432
+ if (key.name === "down" || key.name === "j") return "down";
2433
+ if (key.name === "space") return "toggle";
2434
+ if (key.name === "return" || key.name === "enter") return "submit";
2435
+ return "none";
2436
+ }
2437
+ /** The state after `key`: the pointer wraps around the ends, and space picks or unpicks. */
2438
+ function updateChoice(state, key, choices) {
2439
+ const { cursor, picked } = state;
2440
+ if (key === "up") return {
2441
+ cursor: (cursor + choices.length - 1) % choices.length,
2442
+ picked
2443
+ };
2444
+ if (key === "down") return {
2445
+ cursor: (cursor + 1) % choices.length,
2446
+ picked
2447
+ };
2448
+ if (!picked) return state;
2449
+ const { value } = choices[cursor];
2450
+ const isPicked = picked.includes(value);
2451
+ return {
2452
+ cursor,
2453
+ picked: choices.map((choice) => choice.value).filter((candidate) => candidate === value ? !isPicked : picked.includes(candidate))
2454
+ };
2455
+ }
2456
+ /** The values a submitted choice answers with. */
2457
+ const getAnswer = ({ cursor, picked }, choices) => picked ? [...picked] : [choices[cursor].value];
2458
+ /** The question and its choices, as drawn while the person picks. Ends with a line break. */
2459
+ function formatChoice(question, { cursor, picked }, choices) {
2460
+ return `? ${question} (${picked ? "space to pick, enter when done" : "arrows to move, enter to pick"})\n${choices.map(({ value, label }, index) => {
2461
+ return `${index === cursor ? ">" : " "} ${picked ? picked.includes(value) ? "[x] " : "[ ] " : ""}${label}`;
2462
+ }).join("\n")}\n`;
2463
+ }
2464
+ /** The question with its answer, as it stays once picked. Ends with a line break. */
2465
+ function formatAnswer(question, values, choices) {
2466
+ return `? ${question}: ${choices.filter(({ value }) => values.includes(value)).map(({ label }) => label).join(", ") || "none"}\n`;
2467
+ }
1674
2468
  // src/main.ts
1675
- const BIN = "npx @soroush.tech/design-system";
2469
+ const BIN = "npx @soroush.design/cli";
1676
2470
  /** The help with no command: the commands, and how to get each one's own help. */
1677
2471
  const USAGE = `Usage: ${BIN} <command> [options]
1678
2472
 
@@ -1708,11 +2502,17 @@ an empty one. Its package.json takes the name in lowercase: testApp is test-app.
1708
2502
  the options do not say, shows every file first, and writes nothing until you say yes.
1709
2503
 
1710
2504
  Options:
1711
- -y, --yes create without asking: TypeScript, light, no sample data
2505
+ -y, --yes create without asking: TypeScript, a workspace, light, no sample data
1712
2506
  --dry-run show the files and exit
1713
2507
  --title <text> what the app's pages call it: the name when not given
1714
2508
  --framework <name> the app's framework: ${[`${defaultFramework} (the default)`, ...otherFrameworks].join(", ")}
1715
2509
  --ts, --js TypeScript (the default) or JavaScript
2510
+ --pm <name> the package manager: npm, pnpm, yarn or bun; the one that ran create
2511
+ when not given
2512
+ --layout <name> workspace (the default): the app in apps/web, with room for more
2513
+ apps and services; or standalone: the app alone
2514
+ --render <name> how pages render: isomorphic (the default), spa or ssg
2515
+ --with <names> the libraries to add, by comma: ${LIBRARY_NAMES.join(", ")}
1716
2516
  --scheme <name> the default color scheme: light (the default) or dark
1717
2517
  --sample-data add a list of sample items, and a page for each
1718
2518
  --no-git do not run git init
@@ -1741,6 +2541,10 @@ const OPTIONS = {
1741
2541
  title: { type: "string" },
1742
2542
  ts: { type: "boolean" },
1743
2543
  js: { type: "boolean" },
2544
+ pm: { type: "string" },
2545
+ layout: { type: "string" },
2546
+ render: { type: "string" },
2547
+ with: { type: "string" },
1744
2548
  "sample-data": { type: "boolean" },
1745
2549
  "no-git": { type: "boolean" }
1746
2550
  };
@@ -1752,6 +2556,10 @@ const OWN_OPTIONS = {
1752
2556
  "title",
1753
2557
  "ts",
1754
2558
  "js",
2559
+ "pm",
2560
+ "layout",
2561
+ "render",
2562
+ "with",
1755
2563
  "sample-data",
1756
2564
  "no-git"
1757
2565
  ]
@@ -1768,9 +2576,19 @@ function findMisuse(command, extra, used) {
1768
2576
  }
1769
2577
  /**
1770
2578
  * Reads the command line and runs the command, for `designSystem`: the package of
1771
- * `@soroush.tech/design-system` the command installs. Returns the exit code.
2579
+ * `@soroush.tech/design-system` the command installs. Returns the exit code: 130 when the person
2580
+ * stops it at a question, which is before anything is written.
1772
2581
  */
1773
2582
  async function main(argv, io, designSystem) {
2583
+ try {
2584
+ return await runCommandLine(argv, io, designSystem);
2585
+ } catch (error) {
2586
+ if (!(error instanceof CancelledError)) throw error;
2587
+ io.write("Stopped: nothing was written.\n");
2588
+ return 130;
2589
+ }
2590
+ }
2591
+ async function runCommandLine(argv, io, designSystem) {
1774
2592
  let parsed;
1775
2593
  try {
1776
2594
  parsed = parseArgs({
@@ -1808,6 +2626,28 @@ async function main(argv, io, designSystem) {
1808
2626
  io.write("--ts and --js do not go together: give one.\n");
1809
2627
  return 1;
1810
2628
  }
2629
+ const libraries = values.with?.split(",").map((name) => name.trim()).filter(Boolean);
2630
+ const unknownLibrary = libraries?.find((name) => !LIBRARY_NAMES.includes(name));
2631
+ if (unknownLibrary !== void 0) {
2632
+ io.write(`--with takes ${LIBRARY_NAMES.join(", ")}, not ${unknownLibrary}.\n`);
2633
+ return 1;
2634
+ }
2635
+ const { render } = values;
2636
+ if (render !== void 0 && !RENDERINGS.includes(render)) {
2637
+ io.write(`--render is ${RENDERINGS.join(", ")}, not ${render}.\n`);
2638
+ return 1;
2639
+ }
2640
+ const { layout } = values;
2641
+ if (layout !== void 0 && !LAYOUTS.includes(layout)) {
2642
+ io.write(`--layout is ${LAYOUTS.join(", ")}, not ${layout}.
2643
+ `);
2644
+ return 1;
2645
+ }
2646
+ const { pm } = values;
2647
+ if (pm !== void 0 && !PACKAGE_MANAGERS.includes(pm)) {
2648
+ io.write(`--pm is ${PACKAGE_MANAGERS.join(", ")}, not ${pm}.\n`);
2649
+ return 1;
2650
+ }
1811
2651
  const isConfirmed = Boolean(values.yes);
1812
2652
  const isDryRun = Boolean(values["dry-run"]);
1813
2653
  if (command === "create") {
@@ -1817,6 +2657,10 @@ async function main(argv, io, designSystem) {
1817
2657
  title: values.title,
1818
2658
  framework: values.framework,
1819
2659
  isTypeScript,
2660
+ packageManager: pm,
2661
+ layout,
2662
+ rendering: render,
2663
+ libraries,
1820
2664
  scheme,
1821
2665
  hasSampleData: values["sample-data"],
1822
2666
  isConfirmed,
@@ -1841,6 +2685,52 @@ function toWindowsCommandLine(command, args) {
1841
2685
  for (const part of [command, ...args]) if (!PLAIN_ARGUMENT.test(part)) throw new Error(`init does not run the argument ${part}`);
1842
2686
  return [command, ...args.map((arg) => `"${arg}"`)].join(" ");
1843
2687
  }
2688
+ const HIDE_CURSOR = "\x1B[?25l";
2689
+ const SHOW_CURSOR = "\x1B[?25h";
2690
+ const eraseLines = (count) => count > 0 ? `\u001B[${count}A\r\u001B[J` : "";
2691
+ /**
2692
+ * Draws a choice on the terminal and redraws it on each key, until Enter answers it or Ctrl+C or
2693
+ * Escape stops it. The terminal is in raw mode only while the choice is open.
2694
+ */
2695
+ function runChoice(stdin, stdout, question, choices, start) {
2696
+ return new Promise((resolve, reject) => {
2697
+ let state = start;
2698
+ let drawnLines = 0;
2699
+ const draw = (text) => {
2700
+ stdout.write(eraseLines(drawnLines) + text);
2701
+ drawnLines = text.split("\n").length - 1;
2702
+ };
2703
+ const wasRaw = Boolean(stdin.isRaw);
2704
+ const close = (text) => {
2705
+ stdin.off("keypress", onKeypress);
2706
+ stdin.setRawMode?.(wasRaw);
2707
+ stdin.pause();
2708
+ draw(text);
2709
+ stdout.write(SHOW_CURSOR);
2710
+ };
2711
+ function onKeypress(_text, key) {
2712
+ const action = readChoiceKey(key);
2713
+ if (action === "none") return;
2714
+ if (action === "cancel") {
2715
+ close(`? ${question}\n`);
2716
+ reject(new CancelledError());
2717
+ } else if (action === "submit") {
2718
+ const answer = getAnswer(state, choices);
2719
+ close(formatAnswer(question, answer, choices));
2720
+ resolve(answer);
2721
+ } else {
2722
+ state = updateChoice(state, action, choices);
2723
+ draw(formatChoice(question, state, choices));
2724
+ }
2725
+ }
2726
+ emitKeypressEvents(stdin);
2727
+ stdin.setRawMode?.(true);
2728
+ stdin.on("keypress", onKeypress);
2729
+ stdin.resume();
2730
+ stdout.write(HIDE_CURSOR);
2731
+ draw(formatChoice(question, state, choices));
2732
+ });
2733
+ }
1844
2734
  function createNodeIo({ stdin = process.stdin, stdout = process.stdout, platform = process.platform, cwd = process.cwd() } = {}) {
1845
2735
  return {
1846
2736
  cwd,
@@ -1859,6 +2749,17 @@ function createNodeIo({ stdin = process.stdin, stdout = process.stdout, platform
1859
2749
  prompt.close();
1860
2750
  }
1861
2751
  },
2752
+ select: async (question, choices, initial = 0) => {
2753
+ const [value] = await runChoice(stdin, stdout, question, choices, {
2754
+ cursor: initial,
2755
+ picked: void 0
2756
+ });
2757
+ return value;
2758
+ },
2759
+ selectMany: (question, choices, initial = []) => runChoice(stdin, stdout, question, choices, {
2760
+ cursor: 0,
2761
+ picked: initial
2762
+ }),
1862
2763
  run: (command, args, { cwd: directory, env = {}, showOutput = false }) => {
1863
2764
  const options = {
1864
2765
  cwd: directory,