@soroush.design/cli 0.2.0-alpha.2 → 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.
package/README.md CHANGED
@@ -1,124 +1,21 @@
1
1
  # @soroush.design/cli
2
2
 
3
- The command line of the [`@soroush.tech`](https://docs.soroush.tech) design system. It has two
4
- commands: `create` starts a new app on the design system, and `init` sets the design system up in
5
- an existing React app.
3
+ The command line of the [`@soroush.tech`](https://docs.soroush.tech) design system.
6
4
 
7
- ## Start a new app: `create`
5
+ - **`create`** starts a new app: a working boilerplate on the design system, with its theme, its
6
+ providers and a few pages in place, ready to build on.
7
+ - **`init`** sets the design system up in a React app you already have.
8
8
 
9
9
  ```sh
10
10
  npx @soroush.design/cli create my-app
11
+ npx @soroush.design/cli init
11
12
  ```
12
13
 
13
- It makes the app in a new folder, `my-app`, or in an empty one, and never writes in a folder that
14
- holds anything. It asks for what you did not give it - the name and the title typed, then the
15
- language, the package manager, the default color scheme and the sample data pages picked with the
16
- arrow keys - then shows every file and the install, and writes nothing before a yes. The package
17
- manager starts on the one you ran it with (`npx`, `pnpm dlx`, `yarn dlx`, `bunx`). It installs with
18
- no scripts, and runs `git init` with no commit, unless the folder is already in a repository. When
19
- a write or the install fails, it takes the new app away.
14
+ Each shows every change first, and writes nothing until you say yes. `--help` after a command
15
+ lists its options.
20
16
 
21
- | Option | What it does |
22
- | -------------------- | ----------------------------------------------------------------- |
23
- | `-y`, `--yes` | Create without asking: TypeScript and light, unless given |
24
- | `--dry-run` | Show the files and exit |
25
- | `--title <text>` | What the app's pages call it: the name when not given |
26
- | `--framework <name>` | The app's framework: `vike`, the default and only one yet |
27
- | `--ts`, `--js` | TypeScript (the default) or JavaScript |
28
- | `--pm <name>` | `npm`, `pnpm`, `yarn` or `bun`: the one that ran it, if not given |
29
- | `--render <name>` | `isomorphic` (the default), `spa` or `ssg` |
30
- | `--scheme <name>` | The default color scheme: `light` or `dark` |
31
- | `--sample-data` | Add the sample data pages |
32
- | `--no-git` | Do not run `git init` |
33
- | `-h`, `--help` | Show the options of `create` |
34
-
35
- ### The Vike app
36
-
37
- A [Vike](https://vike.dev) app, rendered the way you pick:
38
-
39
- - **Isomorphic** (the default): every page is prerendered to HTML at build time, with the styles
40
- it uses, so it is drawn styled before any script runs. Then the app takes over in the browser
41
- and moves between pages without a reload.
42
- - **SPA**: every page is an empty HTML shell from the build, and the browser renders it, with its
43
- styles. It moves between pages without a reload.
44
- - **SSG**: every page is prerendered to HTML with its styles, and ships no JavaScript: a link loads
45
- the next page. It has no light and dark switch, since that needs JavaScript.
46
-
47
- All three build to static files that any static host serves.
48
-
49
- - `src/pages/` holds the pages - a home page, a second page and a 404 page - built from the design
50
- system's components and theme tokens only.
51
- - `src/pages/+Layout` is the frame every page renders in. It renders `<Providers>`, and holds a
52
- light and dark switch.
53
- - `src/theme/themes` holds a `light` and a `dark` theme, as `init` writes them: make them your own.
54
- - `src/pages/+onRenderHtml` and `+onRenderClient` render the pages with the design system's
55
- Emotion cache. There is no renderer package to install.
56
- - `npm run dev` starts it, `npm run build` builds it, and `npm run preview` serves the build.
57
-
58
- With sample data pages, it also shows how data gets onto a page, with no data library:
59
-
60
- - `src/data/items` holds six sample items.
61
- - `/items` lists them, and `/items/<id>` shows one. Each page's `+data` reads the items at build
62
- time, and the build prerenders one page per item. Moving between them in the browser loads only
63
- their data, with no reload.
64
- - A page reads its data with `useData()`, from `src/pages/usePageContext`. Make the `+data` hooks
65
- fetch your own data, and remove `src/data/items`.
66
-
67
- The switch does not remember the scheme across a reload, and the theme's fonts are not loaded: see
68
- the [fonts guide](https://docs.soroush.tech/design-system/getting-started/installation/#fonts).
69
-
70
- ## Set up an existing app: `init`
71
-
72
- Run it in your app's folder, or in a workspace's root that holds one app:
73
-
74
- ```sh
75
- npx @soroush.tech/design-system init
76
- ```
77
-
78
- The design system ships this command line, so that installs the version you ask for. Run on its
79
- own, `npx @soroush.design/cli init` (or `create`) does the same with the design system version it
80
- was released next to.
81
-
82
- In PowerShell, quote the package name: `@` starts a splat there.
83
-
84
- ```powershell
85
- npx '@soroush.tech/design-system' init
86
- ```
87
-
88
- ### Options of `init`
89
-
90
- | Option | What it does |
91
- | ----------------- | -------------------------------------------- |
92
- | `-y`, `--yes` | Apply without asking |
93
- | `--dry-run` | Show the changes and exit |
94
- | `--force` | Run outside git, or with uncommitted changes |
95
- | `--scheme <name>` | The default color scheme: `light` or `dark` |
96
- | `-h`, `--help` | Show the options of `init` |
97
-
98
- ### What `init` does
99
-
100
- In a client-rendered React app, whatever builds it (Vite, webpack, Rspack, Parcel, Create React
101
- App), in TypeScript or JavaScript:
102
-
103
- - It writes `src/theme/themes` (a `light` and a `dark` theme, each a `createTheme(baseTheme,
104
- {...})` call you edit) and `src/theme/Providers` (`ThemeProvider` with the base page styles).
105
- - It wraps what your root renders in `<Providers>`.
106
- - It installs `@soroush.tech/design-system` with your own package manager.
107
-
108
- It is careful with your app:
109
-
110
- - It shows every change first - the files, each edit as a diff, the install - and writes nothing
111
- before a yes.
112
- - It runs only in a git repository with no uncommitted change, unless `--force`.
113
- - It never overwrites a file, and edits the root only when it has the standard shape: one
114
- `createRoot(...).render(` or `ReactDOM.render(` call. Otherwise it prints the lines to add.
115
- - When a write fails, it takes back every change it made. The install runs last, with no scripts.
116
- - A second run finds its own files and changes nothing.
117
- - It checks your React against the design system's peer range, and never upgrades React.
118
- - It reaches no network but the install.
119
-
120
- Next.js, Vike and React Router apps are refused for now, with a pointer to the
121
- [setup guide](https://docs.soroush.tech/design-system/getting-started/installation/).
17
+ **Documentation:** [docs.soroush.tech/cli](https://docs.soroush.tech/cli/) - every question and
18
+ option, the app `create` makes, and what `init` changes.
122
19
 
123
20
  ## License
124
21
 
package/dist/bin.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { n as main, r as version$1, t as createNodeIo } from "./io-uDtjQuG6.mjs";
2
+ import { n as main, r as version$1, t as createNodeIo } from "./io-Bybgct-f.mjs";
3
3
  // ../design-system/package.json
4
4
  var name = "@soroush.tech/design-system";
5
5
  var version = "2.2.0";
package/dist/index.d.mts CHANGED
@@ -74,12 +74,19 @@ export declare function readDesignSystemPackage(fromFile: string): PackageJson;
74
74
  * stops it at a question, which is before anything is written.
75
75
  */
76
76
  declare function main(argv: readonly string[], io: Io, designSystem: PackageJson): Promise<number>;
77
+ /** A library `create` can add to a new app, with its wiring and a small example. */
78
+ type Library = 'tanstack-query' | 'swr' | 'msw' | 'zustand' | 'jotai' | 'redux-toolkit' | 'react-hook-form' | 'vitest';
77
79
  /**
78
80
  * How the app's pages are rendered: `isomorphic`, prerendered to HTML at build time and then
79
81
  * moving between pages in the browser; `spa`, rendered in the browser only; `ssg`, HTML only, with
80
82
  * no JavaScript in the browser.
81
83
  */
82
84
  type Rendering = 'isomorphic' | 'spa' | 'ssg';
85
+ /**
86
+ * How the repository holds the app: `workspace`, as `apps/web` of a workspace that has room for
87
+ * more apps and services; `standalone`, the app alone at the root.
88
+ */
89
+ type Layout = 'workspace' | 'standalone';
83
90
  interface CreateOptions {
84
91
  /** The app's folder: asked for, or `my-app`, when missing. */
85
92
  name: string | undefined;
@@ -91,8 +98,12 @@ interface CreateOptions {
91
98
  isTypeScript: boolean | undefined;
92
99
  /** The package manager to install with: asked for, or the one that ran create, when missing. */
93
100
  packageManager: PackageManagerName | undefined;
101
+ /** How the repository holds the app: asked for, or a workspace, when missing. */
102
+ layout: Layout | undefined;
94
103
  /** How the pages are rendered: asked for, or isomorphic, when missing. */
95
104
  rendering: Rendering | undefined;
105
+ /** The libraries to add: asked for, or none, when missing. */
106
+ libraries: readonly Library[] | undefined;
96
107
  scheme: Scheme | undefined;
97
108
  /** Adds the pages that read sample data: asked for, or not, when missing. */
98
109
  hasSampleData: boolean | undefined;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- export { t as createNodeIo, n as default, i as readDesignSystemPackage } from "./io-uDtjQuG6.mjs";
1
+ export { t as createNodeIo, n as default, i as readDesignSystemPackage } from "./io-Bybgct-f.mjs";
@@ -882,32 +882,126 @@ function createAppInstallCommand({ name, isYarnBerry }) {
882
882
  function formatRunScript({ name }, script) {
883
883
  return name === "npm" || name === "bun" ? `${name} run ${script}` : `${name} ${script}`;
884
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
+ }
885
944
  // package.json
886
- var version = "0.2.0-alpha.2";
945
+ var version = "0.2.0-alpha.3";
887
946
  // src/create/vike/vike.ts
888
947
  /** The versions the starter installs: the ones this package is tested with. */
889
948
  const VERSIONS = {
890
949
  "@emotion/server": "^11.11.0",
950
+ "@hookform/resolvers": "^7.0.6",
951
+ "@reduxjs/toolkit": "^2.14.0",
891
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",
892
956
  "@types/node": "^26.6.6",
893
957
  "@types/react": "^19.3.0",
894
958
  "@types/react-dom": "^19.3.0",
895
959
  "@vitejs/plugin-react": "^6.3.0",
896
960
  "@vitest/coverage-v8": "^5.1.0",
961
+ "jotai": "^3.0.2",
962
+ "jsdom": "^31.0.1",
963
+ "msw": "^3.0.5",
897
964
  "oxlint": "^1.93.0",
898
965
  "react": "^19.3.1",
899
966
  "react-dom": "^19.3.1",
967
+ "react-hook-form": "^7.92.0",
968
+ "react-redux": "^9.3.1",
969
+ "swr": "^2.5.1",
900
970
  "tsdown": "^0.23.7",
901
971
  "typescript": "~7.0.2",
902
972
  "vike": "0.4.270",
903
973
  "vite": "~8.3.8",
904
- "vitest": "^5.1.0"
974
+ "vitest": "^5.1.0",
975
+ "zod": "^4.6.7",
976
+ "zustand": "^5.1.0"
905
977
  };
906
978
  /** A version from this package's own manifest, as a range an app takes. */
907
979
  const toRange = (version) => /^\d/.test(version) ? `^${version}` : version;
908
980
  const pickVersions = (names) => Object.fromEntries(names.map((name) => [name, toRange(VERSIONS[name])]));
909
- function createPackageJson({ packageName, isTypeScript, rendering, 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 }) {
910
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 ?? []);
911
1005
  const packageJson = {
912
1006
  name: packageName,
913
1007
  private: true,
@@ -917,12 +1011,14 @@ function createPackageJson({ packageName, isTypeScript, rendering, version }) {
917
1011
  dev: "vite",
918
1012
  build: "vite build",
919
1013
  preview: "vite preview",
920
- ...isTypeScript ? { typecheck: "tsc --noEmit" } : {}
1014
+ ...isTypeScript ? { typecheck: "tsc --noEmit" } : {},
1015
+ ...libraries.includes("vitest") ? { test: "vitest run" } : {}
921
1016
  },
922
1017
  dependencies: {
923
1018
  "@soroush.tech/design-system": toRange(version),
924
1019
  ...pickVersions([
925
1020
  ...renderer,
1021
+ ...libraryPackages,
926
1022
  "react",
927
1023
  "react-dom",
928
1024
  "vike"
@@ -930,6 +1026,7 @@ function createPackageJson({ packageName, isTypeScript, rendering, version }) {
930
1026
  },
931
1027
  devDependencies: pickVersions([
932
1028
  "@vitejs/plugin-react",
1029
+ ...libraryDevPackages,
933
1030
  "vite",
934
1031
  ...isTypeScript ? [
935
1032
  "@types/react",
@@ -940,7 +1037,16 @@ function createPackageJson({ packageName, isTypeScript, rendering, version }) {
940
1037
  };
941
1038
  return `${JSON.stringify(packageJson, null, 2)}\n`;
942
1039
  }
943
- 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'
944
1050
  import vike from 'vike/plugin'
945
1051
  import { defineConfig } from 'vite'
946
1052
 
@@ -967,7 +1073,7 @@ const TSCONFIG = `{
967
1073
  "include": ["src", "vite.config.ts"]
968
1074
  }
969
1075
  `;
970
- const GITIGNORE = `node_modules/
1076
+ const GITIGNORE$1 = `node_modules/
971
1077
  dist/
972
1078
  *.log
973
1079
  .DS_Store
@@ -1040,7 +1146,107 @@ const ABOUT_TEXT = {
1040
1146
  reload.`,
1041
1147
  ssg: "A second page: it is HTML with its styles from the build, and a link loads it as a new page."
1042
1148
  };
1043
- function createSources({ title, isTypeScript, rendering, scheme, hasSampleData }) {
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;
1044
1250
  const t = (typeScriptOnly) => isTypeScript ? typeScriptOnly : "";
1045
1251
  const x = isTypeScript ? "ts" : "js";
1046
1252
  return {
@@ -1150,64 +1356,7 @@ export const onRenderClient${t(": OnRenderClientSync")} = (pageContext) => {
1150
1356
  }
1151
1357
  }
1152
1358
  `,
1153
- Layout: `${rendering === "ssg" ? `${t("import type { ReactNode } from 'react'\n")}import { Flex } from '@soroush.tech/design-system/Flex'
1154
- import { Link } from '@soroush.tech/design-system/Link'
1155
- import { Typography } from '@soroush.tech/design-system/Typography'
1156
- import { View } from '@soroush.tech/design-system/View'
1157
- import { Providers } from '../theme/Providers'
1158
-
1159
- /**
1160
- * The frame every page renders in, inside the app's providers. A page has no JavaScript in the
1161
- * browser, so it is drawn in the default scheme, which src/theme/Providers.${x} sets.
1162
- */
1163
- export default function Layout({ children }${t(": { readonly children: ReactNode }")}) {
1164
- return (
1165
- <Providers>` : `import { useState${t(", type ReactNode")} } from 'react'
1166
- import { Button } from '@soroush.tech/design-system/Button'
1167
- import { Flex } from '@soroush.tech/design-system/Flex'
1168
- import { Link } from '@soroush.tech/design-system/Link'
1169
- import { Typography } from '@soroush.tech/design-system/Typography'
1170
- import { View } from '@soroush.tech/design-system/View'
1171
- import { Providers } from '../theme/Providers'
1172
-
1173
- /**
1174
- * The frame every page renders in. The app's providers live here, in the app itself, so the
1175
- * scheme it holds can switch the theme.
1176
- */
1177
- export default function Layout({ children }${t(": { readonly children: ReactNode }")}) {
1178
- const [scheme, setScheme] = useState${t("<'light' | 'dark'>")}('${scheme}')
1179
- const otherScheme = scheme === 'light' ? 'dark' : 'light'
1180
- return (
1181
- <Providers scheme={scheme}>`}
1182
- <Flex
1183
- as="header"
1184
- flexDirection="row"
1185
- alignItems="center"
1186
- justifyContent="space-between"
1187
- gap={2}
1188
- px={3}
1189
- py={2}
1190
- bg="paper"
1191
- >
1192
- <Typography variant="h6" as="span">
1193
- ${title}
1194
- </Typography>
1195
- <Flex as="nav" flexDirection="row" alignItems="center" gap={2}>
1196
- <Link href="/" underline="hover">
1197
- Home
1198
- </Link>
1199
- <Link href="/about" underline="hover">
1200
- About
1201
- </Link>
1202
- ${hasSampleData ? ITEMS_LINK : ""}${rendering === "ssg" ? "" : SCHEME_SWITCH} </Flex>
1203
- </Flex>
1204
- <View as="main" px={3} py={4}>
1205
- {children}
1206
- </View>
1207
- </Providers>
1208
- )
1209
- }
1210
- `,
1359
+ Layout: createLayout(facts),
1211
1360
  home: `import { Button } from '@soroush.tech/design-system/Button'
1212
1361
  import { Flex } from '@soroush.tech/design-system/Flex'
1213
1362
  import { Typography } from '@soroush.tech/design-system/Typography'
@@ -1292,8 +1441,30 @@ export default function Page() {
1292
1441
  * The sample data pages: a list of items and a page for each, which read `src/data/items` in their
1293
1442
  * +data hooks, at build time.
1294
1443
  */
1295
- function createSampleDataFiles({ isTypeScript }) {
1444
+ function createSampleDataFiles({ isTypeScript, libraries }) {
1296
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>")}()`;
1297
1468
  const x = isTypeScript ? "ts" : "js";
1298
1469
  const dataType = t("\nexport type Data = ReturnType<typeof data>\n");
1299
1470
  const items = `${t(`/** One sample item. */
@@ -1369,11 +1540,11 @@ ${dataType}`;
1369
1540
  const listPage = `import { Flex } from '@soroush.tech/design-system/Flex'
1370
1541
  import { Link } from '@soroush.tech/design-system/Link'
1371
1542
  import { Typography } from '@soroush.tech/design-system/Typography'
1372
- import { useData } from '../usePageContext'
1543
+ ${queryImport("../../data/api", "fetchItems")}import { useData } from '../usePageContext'
1373
1544
  ${t("import type { Data } from './+data'\n")}import { StatusChip } from './StatusChip'
1374
1545
 
1375
1546
  export default function Page() {
1376
- const items = useData${t("<Data>")}()
1547
+ ${listRead}
1377
1548
  return (
1378
1549
  <Flex gap={2}>
1379
1550
  <Typography variant="h2">Items</Typography>
@@ -1415,11 +1586,11 @@ export function onBeforePrerenderStart() {
1415
1586
  const itemPage = `import { Flex } from '@soroush.tech/design-system/Flex'
1416
1587
  import { Link } from '@soroush.tech/design-system/Link'
1417
1588
  import { Typography } from '@soroush.tech/design-system/Typography'
1418
- import { useData } from '../../usePageContext'
1589
+ ${queryImport("../../../data/api", "fetchItem")}import { useData } from '../../usePageContext'
1419
1590
  import { StatusChip } from '../StatusChip'
1420
1591
  ${t("import type { Data } from './+data'\n")}
1421
1592
  export default function Page() {
1422
- const item = useData${t("<Data>")}()
1593
+ ${itemRead}
1423
1594
  return (
1424
1595
  <Flex gap={2} alignItems="flex-start">
1425
1596
  <Typography variant="h2">{item.title}</Typography>
@@ -1476,9 +1647,22 @@ const README_RENDERING = {
1476
1647
  renderers: "`+onRenderHtml` renders the pages to HTML, with the styles each page uses."
1477
1648
  }
1478
1649
  };
1479
- function createReadme({ title, isTypeScript, rendering, hasSampleData }) {
1650
+ function createReadme({ title, isTypeScript, rendering, libraries, hasSampleData }) {
1480
1651
  const x = isTypeScript ? "ts" : "js";
1481
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
+ };
1482
1666
  return `# ${title}
1483
1667
 
1484
1668
  A [Vike](https://vike.dev) app on the [@soroush.tech design system](https://docs.soroush.tech):
@@ -1489,20 +1673,302 @@ ${summary}
1489
1673
  - \`src/pages/+Layout.${x}x\` is the frame every page renders in, inside the app's providers.
1490
1674
  - \`src/theme/themes.${x}\` holds the light and the dark theme: make them your own.
1491
1675
  - In \`src/pages/\`, ${renderers}
1492
- ${hasSampleData ? `- \`src/pages/items/\` lists the sample items of \`src/data/items.${x}\`, with a page for each.
1493
- Their \`+data\` hooks read the data at build time: make them fetch your own.
1494
- ` : ""}
1676
+ ${sampleData}${libraries.map((library) => libraryLines[library]).join("")}
1495
1677
  Fonts: the theme names Space Grotesk and JetBrains Mono, and does not load them. See
1496
1678
  https://docs.soroush.tech/design-system/getting-started/installation/#fonts
1497
1679
  `;
1498
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
+ }
1499
1964
  /** The files of the Vike app `facts` describe. */
1500
1965
  function createFiles(facts) {
1501
- const { isTypeScript, rendering, scheme } = facts;
1966
+ const { isTypeScript, rendering, scheme, libraries } = facts;
1502
1967
  const x = isTypeScript ? "ts" : "js";
1503
1968
  const sources = createSources(facts);
1504
1969
  const isSpa = rendering === "spa";
1505
- const onRenderClient = rendering === "ssg" ? void 0 : isSpa ? sources.spaOnRenderClient : sources.onRenderClient;
1970
+ const renderer = rendering === "ssg" ? void 0 : isSpa ? sources.spaOnRenderClient : sources.onRenderClient;
1971
+ const onRenderClient = renderer && libraries.includes("msw") ? withMocks(renderer) : renderer;
1506
1972
  return [
1507
1973
  {
1508
1974
  path: "package.json",
@@ -1510,7 +1976,7 @@ function createFiles(facts) {
1510
1976
  },
1511
1977
  {
1512
1978
  path: `vite.config.${x}`,
1513
- content: VITE_CONFIG
1979
+ content: createViteConfig(facts)
1514
1980
  },
1515
1981
  ...isTypeScript ? [{
1516
1982
  path: "tsconfig.json",
@@ -1518,7 +1984,7 @@ function createFiles(facts) {
1518
1984
  }] : [],
1519
1985
  {
1520
1986
  path: ".gitignore",
1521
- content: GITIGNORE
1987
+ content: GITIGNORE$1
1522
1988
  },
1523
1989
  {
1524
1990
  path: "README.md",
@@ -1546,7 +2012,7 @@ function createFiles(facts) {
1546
2012
  },
1547
2013
  {
1548
2014
  path: `src/pages/PageShell.${x}x`,
1549
- content: sources.PageShell
2015
+ content: libraries.includes("redux-toolkit") ? withStore(sources.PageShell) : sources.PageShell
1550
2016
  },
1551
2017
  {
1552
2018
  path: `src/pages/usePageContext.${x}x`,
@@ -1576,7 +2042,8 @@ function createFiles(facts) {
1576
2042
  path: `src/pages/_error/+Page.${x}x`,
1577
2043
  content: sources.error
1578
2044
  },
1579
- ...facts.hasSampleData ? createSampleDataFiles(facts) : []
2045
+ ...facts.hasSampleData ? createSampleDataFiles(facts) : [],
2046
+ ...createLibraryFiles(facts)
1580
2047
  ];
1581
2048
  }
1582
2049
  const vikeStarter = {
@@ -1592,6 +2059,85 @@ const RENDERINGS = [
1592
2059
  ];
1593
2060
  /** The starters, by the name `--framework` takes. The first is the default. */
1594
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
+ }
1595
2141
  // src/create/create.ts
1596
2142
  const DEFAULT_NAME = "my-app";
1597
2143
  const APP_NAME = /^[A-Za-z0-9][A-Za-z0-9._~-]*$/;
@@ -1681,6 +2227,18 @@ function resolvePackageManager(name, detected, io) {
1681
2227
  isYarnBerry: name === "yarn" && Number.parseInt(stdout, 10) >= 2
1682
2228
  };
1683
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);
2241
+ }
1684
2242
  async function askTitle(io, name) {
1685
2243
  return (await io.ask(`App title? (${name}) `)).trim() || name;
1686
2244
  }
@@ -1700,6 +2258,19 @@ async function askRendering(io) {
1700
2258
  }));
1701
2259
  return await io.select("Rendering", choices);
1702
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
+ }
1703
2274
  async function askSampleData(io) {
1704
2275
  return await io.select("Add sample data pages?", YES_OR_NO, 1) === "yes";
1705
2276
  }
@@ -1797,20 +2368,35 @@ async function runCreate(options, io, designSystem, { starters = STARTERS, fileS
1797
2368
  io.write(`${packageManager.refusal}\n`);
1798
2369
  return 1;
1799
2370
  }
2371
+ const isWorkspace = (options.layout ?? (canAsk ? await askLayout(io) : LAYOUTS[0])) === "workspace";
1800
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) : []);
1801
2379
  const scheme = options.scheme ?? (canAsk ? await askScheme(io) : "light");
1802
2380
  const hasSampleData = options.hasSampleData ?? (canAsk ? await askSampleData(io) : false);
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
+ });
1803
2392
  const plan = {
1804
- creates: starter.createFiles({
1805
- name,
2393
+ creates: isWorkspace ? createWorkspaceFiles(appFiles, {
1806
2394
  packageName,
1807
2395
  title,
1808
2396
  isTypeScript,
1809
- rendering,
1810
- scheme,
1811
- hasSampleData,
1812
- version: designSystem.version
1813
- }),
2397
+ libraries,
2398
+ packageManager: packageManager.name
2399
+ }) : appFiles,
1814
2400
  edits: [],
1815
2401
  skips: [],
1816
2402
  manual: [],
@@ -1819,7 +2405,7 @@ async function runCreate(options, io, designSystem, { starters = STARTERS, fileS
1819
2405
  const language = isTypeScript ? "TypeScript" : "JavaScript";
1820
2406
  const packageNote = packageName === name ? "" : ` (package ${packageName})`;
1821
2407
  const renderingName = rendering === "isomorphic" ? rendering : rendering.toUpperCase();
1822
- io.write(`create will make ${name}${packageNote}, a ${starter.title} app in ${language} (${renderingName}), in ./${name}:\n\n`);
2408
+ io.write(`create will make ${name}${packageNote}, a ${starter.title} app in ${language} (${renderingName}), ${isWorkspace ? "in a workspace, " : ""}in ./${name}:\n\n`);
1823
2409
  io.write(`${formatPlan(plan)}\n`);
1824
2410
  if (!await isApproved(options, isPreviewOnly, io)) return 0;
1825
2411
  return writeAndInstall({
@@ -1916,14 +2502,17 @@ an empty one. Its package.json takes the name in lowercase: testApp is test-app.
1916
2502
  the options do not say, shows every file first, and writes nothing until you say yes.
1917
2503
 
1918
2504
  Options:
1919
- -y, --yes create without asking: TypeScript, light, no sample data
2505
+ -y, --yes create without asking: TypeScript, a workspace, light, no sample data
1920
2506
  --dry-run show the files and exit
1921
2507
  --title <text> what the app's pages call it: the name when not given
1922
2508
  --framework <name> the app's framework: ${[`${defaultFramework} (the default)`, ...otherFrameworks].join(", ")}
1923
2509
  --ts, --js TypeScript (the default) or JavaScript
1924
2510
  --pm <name> the package manager: npm, pnpm, yarn or bun; the one that ran create
1925
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
1926
2514
  --render <name> how pages render: isomorphic (the default), spa or ssg
2515
+ --with <names> the libraries to add, by comma: ${LIBRARY_NAMES.join(", ")}
1927
2516
  --scheme <name> the default color scheme: light (the default) or dark
1928
2517
  --sample-data add a list of sample items, and a page for each
1929
2518
  --no-git do not run git init
@@ -1953,7 +2542,9 @@ const OPTIONS = {
1953
2542
  ts: { type: "boolean" },
1954
2543
  js: { type: "boolean" },
1955
2544
  pm: { type: "string" },
2545
+ layout: { type: "string" },
1956
2546
  render: { type: "string" },
2547
+ with: { type: "string" },
1957
2548
  "sample-data": { type: "boolean" },
1958
2549
  "no-git": { type: "boolean" }
1959
2550
  };
@@ -1966,7 +2557,9 @@ const OWN_OPTIONS = {
1966
2557
  "ts",
1967
2558
  "js",
1968
2559
  "pm",
2560
+ "layout",
1969
2561
  "render",
2562
+ "with",
1970
2563
  "sample-data",
1971
2564
  "no-git"
1972
2565
  ]
@@ -2033,11 +2626,23 @@ async function runCommandLine(argv, io, designSystem) {
2033
2626
  io.write("--ts and --js do not go together: give one.\n");
2034
2627
  return 1;
2035
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
+ }
2036
2635
  const { render } = values;
2037
2636
  if (render !== void 0 && !RENDERINGS.includes(render)) {
2038
2637
  io.write(`--render is ${RENDERINGS.join(", ")}, not ${render}.\n`);
2039
2638
  return 1;
2040
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
+ }
2041
2646
  const { pm } = values;
2042
2647
  if (pm !== void 0 && !PACKAGE_MANAGERS.includes(pm)) {
2043
2648
  io.write(`--pm is ${PACKAGE_MANAGERS.join(", ")}, not ${pm}.\n`);
@@ -2053,7 +2658,9 @@ async function runCommandLine(argv, io, designSystem) {
2053
2658
  framework: values.framework,
2054
2659
  isTypeScript,
2055
2660
  packageManager: pm,
2661
+ layout,
2056
2662
  rendering: render,
2663
+ libraries,
2057
2664
  scheme,
2058
2665
  hasSampleData: values["sample-data"],
2059
2666
  isConfirmed,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soroush.design/cli",
3
- "version": "0.2.0-alpha.2",
3
+ "version": "0.2.0-alpha.3",
4
4
  "description": "The command line of the @soroush.tech design system: init sets it up in an existing React app, and create starts a new one, each showing every change first.",
5
5
  "keywords": [
6
6
  "cli",
@@ -40,19 +40,32 @@
40
40
  },
41
41
  "devDependencies": {
42
42
  "@emotion/server": "^11.11.0",
43
+ "@hookform/resolvers": "^7.0.6",
44
+ "@reduxjs/toolkit": "^2.14.0",
45
+ "@tanstack/react-query": "^5.107.1",
46
+ "@testing-library/dom": "^10.4.2",
47
+ "@testing-library/react": "^16.3.3",
43
48
  "@types/node": "^26.6.6",
44
49
  "@types/react": "^19.3.0",
45
50
  "@types/react-dom": "^19.3.0",
46
51
  "@vitejs/plugin-react": "^6.3.0",
47
52
  "@vitest/coverage-v8": "^5.1.0",
53
+ "jotai": "^3.0.2",
54
+ "jsdom": "^31.0.1",
55
+ "msw": "^3.0.5",
48
56
  "oxlint": "^1.93.0",
49
57
  "react": "^19.3.1",
50
58
  "react-dom": "^19.3.1",
59
+ "react-hook-form": "^7.92.0",
60
+ "react-redux": "^9.3.1",
61
+ "swr": "^2.5.1",
51
62
  "tsdown": "^0.23.7",
52
63
  "typescript": "~7.0.2",
53
64
  "vike": "0.4.270",
54
65
  "vite": "~8.3.8",
55
66
  "vitest": "^5.1.0",
67
+ "zod": "^4.6.7",
68
+ "zustand": "^5.1.0",
56
69
  "@soroush.tech/eslint-config": "0.0.0"
57
70
  },
58
71
  "scripts": {
@@ -61,7 +74,7 @@
61
74
  "typecheck": "tsc --noEmit",
62
75
  "test": "vitest run",
63
76
  "test:coverage": "vitest run --coverage",
64
- "test:types": "pnpm --filter @soroush.tech/design-system build && tsc -p type-tests/init/tsconfig.json && tsc -p type-tests/tsconfig.create-vike.json && tsc -p type-tests/tsconfig.create-vike-spa.json && tsc -p type-tests/tsconfig.create-vike-ssg.json"
77
+ "test:types": "pnpm --filter @soroush.tech/design-system build && tsc -p type-tests/init/tsconfig.json && tsc -p type-tests/tsconfig.create-vike.json && tsc -p type-tests/tsconfig.create-vike-spa.json && tsc -p type-tests/tsconfig.create-vike-ssg.json && tsc -p type-tests/tsconfig.create-vike-libraries.json && tsc -p type-tests/tsconfig.create-vike-jotai.json && tsc -p type-tests/tsconfig.create-vike-more.json"
65
78
  },
66
79
  "module": "./dist/index.mjs"
67
80
  }