@soroush.design/cli 0.1.0-alpha.3 → 0.2.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,9 +1,60 @@
1
1
  # @soroush.design/cli
2
2
 
3
- The command line of the [`@soroush.tech`](https://docs.soroush.tech) design system. Today it has
4
- one command, `init`, which sets the design system up in an existing React app.
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.
5
6
 
6
- ## Use it
7
+ ## Start a new app: `create`
8
+
9
+ ```sh
10
+ npx @soroush.tech/design-system create my-app
11
+ ```
12
+
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, TypeScript or JavaScript, the
15
+ default color scheme, whether to add sample data pages - then shows every file and the install, and writes nothing before a yes.
16
+ It installs with the package manager you ran it with (`npx`, `pnpm dlx`, `yarn dlx`, `bunx`), with
17
+ no scripts, and runs `git init` with no commit, unless the folder is already in a repository. When
18
+ a write or the install fails, it takes the new app away.
19
+
20
+ | Option | What it does |
21
+ | -------------------- | --------------------------------------------------------- |
22
+ | `-y`, `--yes` | Create without asking: TypeScript and light, unless given |
23
+ | `--dry-run` | Show the files and exit |
24
+ | `--framework <name>` | The app's framework: `vike`, the default and only one yet |
25
+ | `--ts`, `--js` | TypeScript (the default) or JavaScript |
26
+ | `--scheme <name>` | The default color scheme: `light` or `dark` |
27
+ | `--sample-data` | Add the sample data pages |
28
+ | `--no-git` | Do not run `git init` |
29
+
30
+ ### The Vike app
31
+
32
+ A [Vike](https://vike.dev) app, isomorphic: every page is prerendered to HTML at build time, with
33
+ the styles it uses, so it is drawn styled before any script runs. Then the app takes over in the
34
+ browser and moves between pages without a reload.
35
+
36
+ - `src/pages/` holds the pages - a home page, a second page and a 404 page - built from the design
37
+ system's components and theme tokens only.
38
+ - `src/pages/+Layout` is the frame every page renders in. It renders `<Providers>`, and holds a
39
+ light and dark switch.
40
+ - `src/theme/themes` holds a `light` and a `dark` theme, as `init` writes them: make them your own.
41
+ - `src/pages/+onRenderHtml` and `+onRenderClient` render the pages with the design system's
42
+ Emotion cache. There is no renderer package to install.
43
+ - `npm run dev` starts it, `npm run build` builds it, and `npm run preview` serves the build.
44
+
45
+ With sample data pages, it also shows how data gets onto a page, with no data library:
46
+
47
+ - `src/data/items` holds six sample items.
48
+ - `/items` lists them, and `/items/<id>` shows one. Each page's `+data` reads the items at build
49
+ time, and the build prerenders one page per item. Moving between them in the browser loads only
50
+ their data, with no reload.
51
+ - A page reads its data with `useData()`, from `src/pages/usePageContext`. Make the `+data` hooks
52
+ fetch your own data, and remove `src/data/items`.
53
+
54
+ The switch does not remember the scheme across a reload, and the theme's fonts are not loaded: see
55
+ the [fonts guide](https://docs.soroush.tech/design-system/getting-started/installation/#fonts).
56
+
57
+ ## Set up an existing app: `init`
7
58
 
8
59
  Run it in your app's folder, or in a workspace's root that holds one app:
9
60
 
@@ -12,8 +63,8 @@ npx @soroush.tech/design-system init
12
63
  ```
13
64
 
14
65
  The design system ships this command line, so that installs the version you ask for. Run on its
15
- own, `npx @soroush.design/cli init` does the same with the design system version it was released
16
- next to.
66
+ own, `npx @soroush.design/cli init` (or `create`) does the same with the design system version it
67
+ was released next to.
17
68
 
18
69
  In PowerShell, quote the package name: `@` starts a splat there.
19
70
 
@@ -21,7 +72,7 @@ In PowerShell, quote the package name: `@` starts a splat there.
21
72
  npx '@soroush.tech/design-system' init
22
73
  ```
23
74
 
24
- ## Options
75
+ ### Options of `init`
25
76
 
26
77
  | Option | What it does |
27
78
  | ----------------- | -------------------------------------------- |
@@ -31,7 +82,7 @@ npx '@soroush.tech/design-system' init
31
82
  | `--scheme <name>` | The default color scheme: `light` or `dark` |
32
83
  | `-h`, `--help` | Show the help |
33
84
 
34
- ## What `init` does
85
+ ### What `init` does
35
86
 
36
87
  In a client-rendered React app, whatever builds it (Vite, webpack, Rspack, Parcel, Create React
37
88
  App), in TypeScript or JavaScript:
package/dist/bin.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { n as main, t as createNodeIo } from "./io-BzBblzfn.mjs";
2
+ import { n as main, t as createNodeIo } from "./io-BuZk1Ebr.mjs";
3
3
  // ../design-system/package.json
4
4
  var name = "@soroush.tech/design-system";
5
- var version = "2.2.0";
5
+ var version = "2.3.0";
6
6
  var peerDependencies = {
7
7
  "react": "^18.0.0 || ^19.0.0",
8
8
  "react-dom": "^18.0.0 || ^19.0.0"
package/dist/index.d.mts CHANGED
@@ -52,9 +52,26 @@ interface PackageJson {
52
52
  export declare function readDesignSystemPackage(fromFile: string): PackageJson;
53
53
  /**
54
54
  * Reads the command line and runs the command, for `designSystem`: the package of
55
- * `@soroush.tech/design-system` that init installs. Returns the exit code.
55
+ * `@soroush.tech/design-system` the command installs. Returns the exit code.
56
56
  */
57
57
  declare function main(argv: readonly string[], io: Io, designSystem: PackageJson): Promise<number>;
58
+ interface CreateOptions {
59
+ /** The app's name, and its folder's: asked for, or `my-app`, when missing. */
60
+ name: string | undefined;
61
+ /** The starter, by its name in `STARTERS`: the first one when missing. */
62
+ framework: string | undefined;
63
+ /** TypeScript or JavaScript: asked for, or TypeScript, when missing. */
64
+ isTypeScript: boolean | undefined;
65
+ scheme: Scheme | undefined;
66
+ /** Adds the pages that read sample data: asked for, or not, when missing. */
67
+ hasSampleData: boolean | undefined;
68
+ /** Creates without asking. */
69
+ isConfirmed: boolean;
70
+ /** Prints the plan and exits. */
71
+ isDryRun: boolean;
72
+ /** Runs `git init` in the new folder, unless it is inside a repository already. */
73
+ isGit: boolean;
74
+ }
58
75
  interface InitOptions {
59
76
  /** Applies without asking. */
60
77
  isConfirmed: boolean;
@@ -64,4 +81,4 @@ interface InitOptions {
64
81
  isForced: boolean;
65
82
  scheme: Scheme | undefined;
66
83
  }
67
- export { type InitOptions, type Io, type PackageJson, main as default };
84
+ export { type CreateOptions, type InitOptions, type Io, type PackageJson, main as default };
package/dist/index.mjs CHANGED
@@ -1,4 +1 @@
1
- import { n as main, r as readDesignSystemPackage, t as createNodeIo } from "./io-BzBblzfn.mjs";
2
- // src/index.ts
3
- var src_default = main;
4
- export { createNodeIo, src_default as default, readDesignSystemPackage };
1
+ export { t as createNodeIo, n as default, r as readDesignSystemPackage } from "./io-BuZk1Ebr.mjs";
@@ -11,6 +11,10 @@ const nodeFileSystem = {
11
11
  removeFile: (path) => rmSync(path),
12
12
  createDirectory: (path) => mkdirSync(path),
13
13
  removeDirectory: (path) => rmdirSync(path),
14
+ removeTree: (path) => rmSync(path, {
15
+ recursive: true,
16
+ force: true
17
+ }),
14
18
  isSymbolicLink: (path) => {
15
19
  try {
16
20
  return lstatSync(path).isSymbolicLink();
@@ -90,6 +94,14 @@ function applyPlan(plan, root, fileSystem = nodeFileSystem) {
90
94
  throw new ApplyError(error.message, isUndone);
91
95
  }
92
96
  }
97
+ // src/closing.ts
98
+ const SETUP_DOCS$1 = "https://docs.soroush.tech/design-system/getting-started/installation/";
99
+ const FONTS_STEP = ` - Fonts: the theme names Space Grotesk and JetBrains Mono, and does not load them. To add them,
100
+ see ${SETUP_DOCS$1}#fonts`;
101
+ const AGENT_STEPS = `For a coding agent, if you use one (any agent):
102
+ - The house-style skill: npx skills add soroush-tech/design-system
103
+ - The MCP server, for any MCP client: https://mcp.soroush.design/mcp
104
+ `;
93
105
  // src/plan/rootEdit.ts
94
106
  const RENDER_CALL = /\.render\s*\(/g;
95
107
  const CLOSERS = {
@@ -496,20 +508,31 @@ export default themes
496
508
  }
497
509
  /**
498
510
  * The providers the app's root renders inside: the theme, and the package's base page styles.
499
- * It holds no JSX, so it needs none of the app's JSX settings.
511
+ * `scheme` picks the theme, `scheme` by default, so an app can switch it. It holds no JSX, so it
512
+ * needs none of the app's JSX settings.
500
513
  */
501
514
  function createProvidersSource({ isTypeScript, scheme, themesImport }) {
515
+ const typeImport = isTypeScript ? `import type { ReactNode } from 'react'
516
+ ` : "";
517
+ const props = isTypeScript ? `{
518
+ children,
519
+ scheme = '${scheme}',
520
+ }: {
521
+ readonly children?: ReactNode
522
+ /** The theme to draw with, by its name in themes. */
523
+ readonly scheme?: keyof typeof themes
524
+ }` : `{ children, scheme = '${scheme}' }`;
502
525
  return `${MARKER} The app's root renders inside Providers.
503
526
  import { createElement } from 'react'
504
- ${isTypeScript ? `import type { ReactNode } from 'react'\n` : ""}import { Global, globalStyles } from '@soroush.tech/design-system/engine'
527
+ ${typeImport}import { Global, globalStyles } from '@soroush.tech/design-system/engine'
505
528
  import { ThemeProvider } from '@soroush.tech/design-system/theme'
506
529
  import themes from '${themesImport}'
507
530
 
508
531
  /** Gives every component its theme, and draws the page's base styles. */
509
- export function Providers(${isTypeScript ? "{ children }: { readonly children?: ReactNode }" : "{ children }"}) {
532
+ export function Providers(${props}) {
510
533
  return createElement(
511
534
  ThemeProvider,
512
- { theme: themes.${scheme} },
535
+ { theme: themes[scheme] },
513
536
  createElement(Global, { styles: globalStyles }),
514
537
  children
515
538
  )
@@ -537,7 +560,7 @@ function toImportSpecifier(fromFile, toFile, style) {
537
560
  return specifier.startsWith(".") ? specifier : `./${specifier}`;
538
561
  }
539
562
  // src/plan/planInit.ts
540
- const SETUP_DOCS$1 = "https://docs.soroush.tech/design-system/getting-started/installation/";
563
+ const SETUP_DOCS = "https://docs.soroush.tech/design-system/getting-started/installation/";
541
564
  /** The command that adds the design system with the app's own package manager, running no scripts. */
542
565
  function createInstallCommand({ name, isYarnBerry }, version) {
543
566
  const spec = `@soroush.tech/design-system@${version.includes("-") ? version : `^${version}`}`;
@@ -579,7 +602,7 @@ function planInit(facts) {
579
602
  providersPath,
580
603
  style
581
604
  })) planRootEdit(plan, facts, providersPath, style);
582
- else plan.manual.push(`Set up the theme by hand: ${SETUP_DOCS$1}`);
605
+ else plan.manual.push(`Set up the theme by hand: ${SETUP_DOCS}`);
583
606
  if (facts.needsParcelPackageExports) plan.manual.push("Parcel finds @soroush.tech/design-system/theme and the other subpaths only once it reads package exports. Add to package.json: \"@parcel/resolver-default\": { \"packageExports\": true }");
584
607
  if (!facts.hasDesignSystem) plan.install = createInstallCommand(facts.packageManager, facts.version);
585
608
  return plan;
@@ -647,9 +670,7 @@ function isPlanEmpty(plan) {
647
670
  return plan.creates.length === 0 && plan.edits.length === 0 && !plan.install;
648
671
  }
649
672
  // src/init.ts
650
- const SETUP_DOCS = "https://docs.soroush.tech/design-system/getting-started/installation/";
651
- const FONTS_DOCS = `${SETUP_DOCS}#fonts`;
652
- function formatClosing({ creates, manual }) {
673
+ function formatClosing$1({ creates, manual }) {
653
674
  const themes = creates.find((file) => /\/themes\.[jt]s$/.test(file.path));
654
675
  const themesStep = themes ? `\n - Make the themes your own in ${themes.path}.` : "";
655
676
  const steps = manual.map((step) => ` - ${step}`).join("\n");
@@ -657,18 +678,14 @@ function formatClosing({ creates, manual }) {
657
678
  ${manual.length > 0 ? `\nStill left to you:\n${steps}\n` : ""}
658
679
  Next:
659
680
  - Use a component: import { Button } from '@soroush.tech/design-system/Button'${themesStep}
660
- - Fonts: the theme names Space Grotesk and JetBrains Mono, and does not load them. To add them,
661
- see ${FONTS_DOCS}
681
+ ${FONTS_STEP}
662
682
 
663
- For a coding agent, if you use one (any agent):
664
- - The house-style skill: npx skills add soroush-tech/design-system
665
- - The MCP server, for any MCP client: https://mcp.soroush.design/mcp
666
- `;
683
+ ${AGENT_STEPS}`;
667
684
  }
668
685
  /** Why init refuses this app, or `undefined` when it can set it up. */
669
686
  function findRefusal(root, packageJson, reactRange) {
670
687
  const framework = findUnsupportedFramework(packageJson);
671
- if (framework) return `This looks like a ${framework} app. init sets up client-rendered React apps for now, so it changes nothing here. To set it up by hand, see ${SETUP_DOCS}`;
688
+ if (framework) return `This looks like a ${framework} app. init sets up client-rendered React apps for now, so it changes nothing here. To set it up by hand, see ${SETUP_DOCS$1}`;
672
689
  const reactVersion = findReactVersion(root, packageJson);
673
690
  if (!reactVersion) return "init found no React in this app. Add react and react-dom first.";
674
691
  if (!satisfiesRange(reactVersion, reactRange)) return `This app has React ${reactVersion}, and the design system needs React ${reactRange}. init changes nothing, and never upgrades React.`;
@@ -710,6 +727,7 @@ function findApp(cwd) {
710
727
  folder
711
728
  };
712
729
  }
730
+ /** Asks for the default color scheme: light, unless the answer is dark. */
713
731
  async function askScheme(io) {
714
732
  const answer = await io.ask("Default color scheme, light or dark? (light) ");
715
733
  return /^d(ark)?$/i.test(answer.trim()) ? "dark" : "light";
@@ -742,7 +760,7 @@ async function planWithScheme(facts, canAsk, io) {
742
760
  }) : plan;
743
761
  }
744
762
  /** Whether to apply the plan: never on a dry run or with no terminal, else on --yes or a yes. */
745
- async function isApproved(options, isPreviewOnly, io) {
763
+ async function isApproved$1(options, isPreviewOnly, io) {
746
764
  if (options.isDryRun) {
747
765
  io.write("Dry run: nothing was changed.\n");
748
766
  return false;
@@ -779,7 +797,7 @@ function applyAndInstall(plan, root, io, fileSystem) {
779
797
  return 1;
780
798
  }
781
799
  }
782
- io.write(formatClosing(plan));
800
+ io.write(formatClosing$1(plan));
783
801
  return 0;
784
802
  }
785
803
  /**
@@ -814,25 +832,887 @@ async function runInit(options, io, designSystem, fileSystem = nodeFileSystem) {
814
832
  }
815
833
  const appName = packageJson.name ?? "this app";
816
834
  io.write(`init will set up @soroush.tech/design-system in ${appName}:\n\n${formatPlan(plan)}\n`);
817
- if (!await isApproved(options, isPreviewOnly, io)) return 0;
835
+ if (!await isApproved$1(options, isPreviewOnly, io)) return 0;
818
836
  return applyAndInstall(plan, root, io, fileSystem);
819
837
  }
838
+ // src/create/packageManager.ts
839
+ /**
840
+ * The package manager that ran `create`, from the user agent it gives the commands it starts
841
+ * (`pnpm/10.4.1 npm/? node/v24.1.0 ...`), else npm. A new app has no lockfile to read it from.
842
+ */
843
+ function readPackageManager(userAgent) {
844
+ const match = /^(npm|pnpm|yarn|bun)\/(\d+)/.exec(userAgent ?? "");
845
+ if (!match) return {
846
+ name: "npm",
847
+ isYarnBerry: false
848
+ };
849
+ const name = match[1];
850
+ return {
851
+ name,
852
+ isYarnBerry: name === "yarn" && Number(match[2]) >= 2
853
+ };
854
+ }
855
+ /** The command that installs a new app's dependencies, running no scripts. */
856
+ function createAppInstallCommand({ name, isYarnBerry }) {
857
+ if (name === "yarn" && isYarnBerry) return {
858
+ command: "yarn",
859
+ args: ["install"],
860
+ env: { YARN_ENABLE_SCRIPTS: "false" }
861
+ };
862
+ return {
863
+ command: name,
864
+ args: ["install", "--ignore-scripts"],
865
+ env: {}
866
+ };
867
+ }
868
+ /** The command that runs a package script, as the developer types it. */
869
+ function formatRunScript({ name }, script) {
870
+ return name === "npm" || name === "bun" ? `${name} run ${script}` : `${name} ${script}`;
871
+ }
872
+ // src/create/vike/vike.ts
873
+ /** The versions the starter installs: the ones this package is tested with. */
874
+ const VERSIONS = {
875
+ "@emotion/server": "^11.11.0",
876
+ "@soroush.tech/eslint-config": "workspace:*",
877
+ "@types/node": "^26.6.6",
878
+ "@types/react": "^19.3.0",
879
+ "@types/react-dom": "^19.3.0",
880
+ "@vitejs/plugin-react": "^6.3.0",
881
+ "@vitest/coverage-v8": "^5.1.0",
882
+ "oxlint": "^1.93.0",
883
+ "react": "^19.3.1",
884
+ "react-dom": "^19.3.1",
885
+ "tsdown": "^0.23.7",
886
+ "typescript": "~7.0.2",
887
+ "vike": "0.4.270",
888
+ "vite": "~8.3.8",
889
+ "vitest": "^5.1.0"
890
+ };
891
+ /** A version from this package's own manifest, as a range an app takes. */
892
+ const toRange = (version) => /^\d/.test(version) ? `^${version}` : version;
893
+ const pickVersions = (names) => Object.fromEntries(names.map((name) => [name, toRange(VERSIONS[name])]));
894
+ function createPackageJson({ name, isTypeScript, version }) {
895
+ const packageJson = {
896
+ name,
897
+ private: true,
898
+ version: "0.0.0",
899
+ type: "module",
900
+ scripts: {
901
+ dev: "vite",
902
+ build: "vite build",
903
+ preview: "vite preview",
904
+ ...isTypeScript ? { typecheck: "tsc --noEmit" } : {}
905
+ },
906
+ dependencies: {
907
+ "@soroush.tech/design-system": toRange(version),
908
+ ...pickVersions([
909
+ "@emotion/server",
910
+ "react",
911
+ "react-dom",
912
+ "vike"
913
+ ])
914
+ },
915
+ devDependencies: pickVersions([
916
+ "@vitejs/plugin-react",
917
+ "vite",
918
+ ...isTypeScript ? [
919
+ "@types/react",
920
+ "@types/react-dom",
921
+ "typescript"
922
+ ] : []
923
+ ])
924
+ };
925
+ return `${JSON.stringify(packageJson, null, 2)}\n`;
926
+ }
927
+ const VITE_CONFIG = `import react from '@vitejs/plugin-react'
928
+ import vike from 'vike/plugin'
929
+ import { defineConfig } from 'vite'
930
+
931
+ export default defineConfig({
932
+ plugins: [react(), vike()],
933
+ })
934
+ `;
935
+ const TSCONFIG = `{
936
+ "compilerOptions": {
937
+ "target": "ES2022",
938
+ "lib": ["ES2023", "DOM", "DOM.Iterable"],
939
+ "module": "ESNext",
940
+ "moduleResolution": "bundler",
941
+ "verbatimModuleSyntax": true,
942
+ "moduleDetection": "force",
943
+ "noEmit": true,
944
+ "strict": true,
945
+ "noUnusedLocals": true,
946
+ "noUnusedParameters": true,
947
+ "skipLibCheck": true,
948
+ "jsx": "react-jsx",
949
+ "types": ["vite/client"]
950
+ },
951
+ "include": ["src", "vite.config.ts"]
952
+ }
953
+ `;
954
+ const GITIGNORE = `node_modules/
955
+ dist/
956
+ *.log
957
+ .DS_Store
958
+ `;
959
+ const VIKE_TYPES = `// Types for what this app adds to Vike: each page's component, and the +Layout around it.
960
+ import type { ReactNode } from 'react'
961
+
962
+ type Layout = (props: { children: ReactNode }) => ReactNode
963
+
964
+ declare global {
965
+ namespace Vike {
966
+ interface PageContext {
967
+ Page: () => ReactNode
968
+ }
969
+ interface Config {
970
+ Layout?: Layout
971
+ }
972
+ interface ConfigResolved {
973
+ Layout?: Layout
974
+ }
975
+ }
976
+ }
977
+
978
+ export {}
979
+ `;
980
+ /** The layout's link to the sample data pages, when the app has them. */
981
+ const ITEMS_LINK = ` <Link href="/items" underline="hover">
982
+ Items
983
+ </Link>
984
+ `;
985
+ function createSources({ name, isTypeScript, scheme, hasSampleData }) {
986
+ const t = (typeScriptOnly) => isTypeScript ? typeScriptOnly : "";
987
+ const x = isTypeScript ? "ts" : "js";
988
+ return {
989
+ config: `${t("import type { Config } from 'vike/types'\n\n")}// The settings of every page: https://vike.dev/config
990
+ export default {
991
+ // Isomorphic: every page is HTML at build time, then the app moves between pages in the
992
+ // browser, with no reload.
993
+ prerender: true,
994
+ clientRouting: true,
995
+ hydrationCanBeAborted: true,
996
+ // +Layout is a setting of this app's own: the component every page renders inside.
997
+ meta: {
998
+ Layout: { env: { server: true, client: true } },
999
+ },
1000
+ }${t(" satisfies Config")}
1001
+ `,
1002
+ PageShell: `import { StrictMode } from 'react'
1003
+ import { CacheProvider, styleCache } from '@soroush.tech/design-system/engine'
1004
+ ${t("import type { PageContext } from 'vike/types'\n")}import { PageContextProvider } from './usePageContext'
1005
+
1006
+ /**
1007
+ * The page inside its +Layout, the same on the server and in the browser. The Emotion cache is the
1008
+ * design system's, so the server can find the styles the page used, and every component of the
1009
+ * page can read its pageContext.
1010
+ */
1011
+ export function PageShell({ pageContext }${t(": { readonly pageContext: PageContext }")}) {
1012
+ const { Page, config } = pageContext
1013
+ const { Layout } = config
1014
+ return (
1015
+ <StrictMode>
1016
+ <CacheProvider value={styleCache}>
1017
+ <PageContextProvider pageContext={pageContext}>
1018
+ {Layout ? (
1019
+ <Layout>
1020
+ <Page />
1021
+ </Layout>
1022
+ ) : (
1023
+ <Page />
1024
+ )}
1025
+ </PageContextProvider>
1026
+ </CacheProvider>
1027
+ </StrictMode>
1028
+ )
1029
+ }
1030
+ `,
1031
+ onRenderHtml: `import createEmotionServer from '@emotion/server/create-instance'
1032
+ import { renderToString } from 'react-dom/server'
1033
+ import { styleCache } from '@soroush.tech/design-system/engine'
1034
+ import { dangerouslySkipEscape, escapeInject } from 'vike/server'
1035
+ ${t("import type { OnRenderHtmlSync } from 'vike/types'\n")}import { PageShell } from './PageShell'
1036
+
1037
+ /**
1038
+ * Renders the page to HTML - at build time, as the app is prerendered - with the styles it uses
1039
+ * in the head, so it is drawn styled before any script runs.
1040
+ */
1041
+ export const onRenderHtml${t(": OnRenderHtmlSync")} = (pageContext) => {
1042
+ const { extractCriticalToChunks, constructStyleTagsFromChunks } = createEmotionServer(styleCache)
1043
+ const html = renderToString(<PageShell pageContext={pageContext} />)
1044
+ const styles = constructStyleTagsFromChunks(extractCriticalToChunks(html))
1045
+ return escapeInject\`<!doctype html>
1046
+ <html lang="en">
1047
+ <head>
1048
+ <meta charset="UTF-8" />
1049
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
1050
+ <title>${name}</title>
1051
+ \${dangerouslySkipEscape(styles)}
1052
+ </head>
1053
+ <body>
1054
+ <div id="root">\${dangerouslySkipEscape(html)}</div>
1055
+ </body>
1056
+ </html>\`
1057
+ }
1058
+ `,
1059
+ onRenderClient: `import { createRoot, hydrateRoot${t(", type Root")} } from 'react-dom/client'
1060
+ ${t("import type { OnRenderClientSync } from 'vike/types'\n")}import { PageShell } from './PageShell'
1061
+
1062
+ let root${t(": Root | undefined")}
1063
+
1064
+ /** Takes over the page the server drew, then draws each page the app moves to. */
1065
+ export const onRenderClient${t(": OnRenderClientSync")} = (pageContext) => {
1066
+ const page = <PageShell pageContext={pageContext} />
1067
+ const container = document.getElementById('root')${t("!")}
1068
+ if (pageContext.isHydration) {
1069
+ root = hydrateRoot(container, page)
1070
+ } else {
1071
+ root ??= createRoot(container)
1072
+ root.render(page)
1073
+ }
1074
+ }
1075
+ `,
1076
+ Layout: `import { useState${t(", type ReactNode")} } from 'react'
1077
+ import { Button } from '@soroush.tech/design-system/Button'
1078
+ import { Flex } from '@soroush.tech/design-system/Flex'
1079
+ import { Link } from '@soroush.tech/design-system/Link'
1080
+ import { Typography } from '@soroush.tech/design-system/Typography'
1081
+ import { View } from '@soroush.tech/design-system/View'
1082
+ import { Providers } from '../theme/Providers'
1083
+
1084
+ /**
1085
+ * The frame every page renders in. The app's providers live here, in the app itself, so the
1086
+ * scheme it holds can switch the theme.
1087
+ */
1088
+ export default function Layout({ children }${t(": { readonly children: ReactNode }")}) {
1089
+ const [scheme, setScheme] = useState${t("<'light' | 'dark'>")}('${scheme}')
1090
+ const otherScheme = scheme === 'light' ? 'dark' : 'light'
1091
+ return (
1092
+ <Providers scheme={scheme}>
1093
+ <Flex
1094
+ as="header"
1095
+ flexDirection="row"
1096
+ alignItems="center"
1097
+ justifyContent="space-between"
1098
+ gap={2}
1099
+ px={3}
1100
+ py={2}
1101
+ bg="paper"
1102
+ >
1103
+ <Typography variant="h6" as="span">
1104
+ ${name}
1105
+ </Typography>
1106
+ <Flex as="nav" flexDirection="row" alignItems="center" gap={2}>
1107
+ <Link href="/" underline="hover">
1108
+ Home
1109
+ </Link>
1110
+ <Link href="/about" underline="hover">
1111
+ About
1112
+ </Link>
1113
+ ${hasSampleData ? ITEMS_LINK : ""} <Button size="sm" variant="outlined" onClick={() => setScheme(otherScheme)}>
1114
+ {otherScheme}
1115
+ </Button>
1116
+ </Flex>
1117
+ </Flex>
1118
+ <View as="main" px={3} py={4}>
1119
+ {children}
1120
+ </View>
1121
+ </Providers>
1122
+ )
1123
+ }
1124
+ `,
1125
+ home: `import { Button } from '@soroush.tech/design-system/Button'
1126
+ import { Flex } from '@soroush.tech/design-system/Flex'
1127
+ import { Typography } from '@soroush.tech/design-system/Typography'
1128
+
1129
+ export default function Page() {
1130
+ return (
1131
+ <Flex gap={2} alignItems="flex-start">
1132
+ <Typography variant="h2">${name}</Typography>
1133
+ <Typography color="secondary">
1134
+ A Vike app on the design system. Edit src/pages/index/+Page.${x}x, and make the themes your
1135
+ own in src/theme/themes.${x}.
1136
+ </Typography>
1137
+ <Flex flexDirection="row" gap={1}>
1138
+ <Button href="https://docs.soroush.tech">Components</Button>
1139
+ <Button href="https://vike.dev" variant="outlined">
1140
+ Vike
1141
+ </Button>
1142
+ </Flex>
1143
+ </Flex>
1144
+ )
1145
+ }
1146
+ `,
1147
+ about: `import { Flex } from '@soroush.tech/design-system/Flex'
1148
+ import { Typography } from '@soroush.tech/design-system/Typography'
1149
+
1150
+ export default function Page() {
1151
+ return (
1152
+ <Flex gap={2}>
1153
+ <Typography variant="h2">About</Typography>
1154
+ <Typography color="secondary">
1155
+ A second page: it is HTML with its styles from the build, and the app moves to it without a
1156
+ reload.
1157
+ </Typography>
1158
+ </Flex>
1159
+ )
1160
+ }
1161
+ `,
1162
+ usePageContext: `import { createContext, useContext${t(", type ReactNode")} } from 'react'
1163
+ ${t("import type { PageContext } from 'vike/types'\n")}
1164
+ const Context = createContext${t("<PageContext | undefined>")}(undefined)
1165
+
1166
+ /** Gives every component of the page its pageContext: https://vike.dev/pageContext */
1167
+ export function PageContextProvider({
1168
+ pageContext,
1169
+ children,
1170
+ }${t(`: {
1171
+ readonly pageContext: PageContext
1172
+ readonly children: ReactNode
1173
+ }`)}) {
1174
+ return <Context.Provider value={pageContext}>{children}</Context.Provider>
1175
+ }
1176
+
1177
+ /** The pageContext of the page on screen: its URL, its route's parameters, its data. */
1178
+ export function usePageContext() {
1179
+ const pageContext = useContext(Context)
1180
+ if (!pageContext) throw new Error('usePageContext runs only inside a page.')
1181
+ return pageContext
1182
+ }
1183
+
1184
+ /** What the page's +data returned: https://vike.dev/data */
1185
+ export function useData${t("<Data>")}() {
1186
+ return usePageContext().data${t(" as Data")}
1187
+ }
1188
+ `,
1189
+ error: `import { Flex } from '@soroush.tech/design-system/Flex'
1190
+ import { Link } from '@soroush.tech/design-system/Link'
1191
+ import { Typography } from '@soroush.tech/design-system/Typography'
1192
+
1193
+ /** Shown for a page that does not exist, and when a page fails to render. */
1194
+ export default function Page() {
1195
+ return (
1196
+ <Flex gap={2} alignItems="flex-start">
1197
+ <Typography variant="h2">Page not found</Typography>
1198
+ <Typography color="secondary">This page does not exist, or it could not be shown.</Typography>
1199
+ <Link href="/">Back home</Link>
1200
+ </Flex>
1201
+ )
1202
+ }
1203
+ `
1204
+ };
1205
+ }
1206
+ /**
1207
+ * The sample data pages: a list of items and a page for each, which read `src/data/items` in their
1208
+ * +data hooks, at build time.
1209
+ */
1210
+ function createSampleDataFiles({ isTypeScript }) {
1211
+ const t = (typeScriptOnly) => isTypeScript ? typeScriptOnly : "";
1212
+ const x = isTypeScript ? "ts" : "js";
1213
+ const dataType = t("\nexport type Data = ReturnType<typeof data>\n");
1214
+ const items = `${t(`/** One sample item. */
1215
+ export interface Item {
1216
+ id: string
1217
+ title: string
1218
+ summary: string
1219
+ status: 'todo' | 'doing' | 'done'
1220
+ }
1221
+
1222
+ `)}/**
1223
+ * Sample data, so the items pages have something to show: each page's +data reads it at build
1224
+ * time. Make the +data hooks fetch your own data instead, and remove this file.
1225
+ */
1226
+ export const items${t(": readonly Item[]")} = [
1227
+ {
1228
+ id: 'theme',
1229
+ title: 'Make the theme your own',
1230
+ summary: 'Change the colors and fonts of both themes in src/theme/themes.${x}.',
1231
+ status: 'doing',
1232
+ },
1233
+ {
1234
+ id: 'fonts',
1235
+ title: 'Load the fonts',
1236
+ summary: 'The theme names Space Grotesk and JetBrains Mono, and does not load them.',
1237
+ status: 'todo',
1238
+ },
1239
+ {
1240
+ id: 'pages',
1241
+ title: 'Add a page',
1242
+ summary: 'A folder in src/pages with a +Page in it is a new route.',
1243
+ status: 'todo',
1244
+ },
1245
+ {
1246
+ id: 'data',
1247
+ title: 'Read your own data',
1248
+ summary: 'Each +data here reads this file. Make it fetch from your API, at build time.',
1249
+ status: 'todo',
1250
+ },
1251
+ {
1252
+ id: 'build',
1253
+ title: 'Build it',
1254
+ summary: 'The build prerenders every page, these items among them, to HTML with its styles.',
1255
+ status: 'done',
1256
+ },
1257
+ {
1258
+ id: 'deploy',
1259
+ title: 'Deploy it',
1260
+ summary: 'The build is static files in dist/client, which any static host serves.',
1261
+ status: 'todo',
1262
+ },
1263
+ ]
1264
+ `;
1265
+ const statusChip = `import { Chip } from '@soroush.tech/design-system/Chip'
1266
+ ${t("import type { Item } from '../../data/items'\n")}
1267
+ const COLORS = { todo: 'default', doing: 'primary', done: 'success' }${t(" as const")}
1268
+
1269
+ /** An item's status, in its palette color. */
1270
+ export function StatusChip({ status }${t(": { readonly status: Item['status'] }")}) {
1271
+ return <Chip label={status} size="sm" variant="outlined" color={COLORS[status]} />
1272
+ }
1273
+ `;
1274
+ const listData = `import { items } from '../../data/items'
1275
+
1276
+ /**
1277
+ * The list page's data: what it shows of each item. It runs at build time, as the page is
1278
+ * prerendered. https://vike.dev/data
1279
+ */
1280
+ export function data() {
1281
+ return items.map(({ id, title, status }) => ({ id, title, status }))
1282
+ }
1283
+ ${dataType}`;
1284
+ const listPage = `import { Flex } from '@soroush.tech/design-system/Flex'
1285
+ import { Link } from '@soroush.tech/design-system/Link'
1286
+ import { Typography } from '@soroush.tech/design-system/Typography'
1287
+ import { useData } from '../usePageContext'
1288
+ ${t("import type { Data } from './+data'\n")}import { StatusChip } from './StatusChip'
1289
+
1290
+ export default function Page() {
1291
+ const items = useData${t("<Data>")}()
1292
+ return (
1293
+ <Flex gap={2}>
1294
+ <Typography variant="h2">Items</Typography>
1295
+ <Typography color="secondary">
1296
+ Sample data from src/data/items.${x}, which this page's +data reads at build time.
1297
+ </Typography>
1298
+ <Flex gap={1}>
1299
+ {items.map((item) => (
1300
+ <Flex key={item.id} flexDirection="row" alignItems="center" gap={2}>
1301
+ <Link href={\`/items/\${item.id}\`}>{item.title}</Link>
1302
+ <StatusChip status={item.status} />
1303
+ </Flex>
1304
+ ))}
1305
+ </Flex>
1306
+ </Flex>
1307
+ )
1308
+ }
1309
+ `;
1310
+ const itemData = `import { render } from 'vike/abort'
1311
+ ${t("import type { PageContextServer } from 'vike/types'\n")}import { items } from '../../../data/items'
1312
+
1313
+ /**
1314
+ * One item's data, by the id in the URL, or the 404 page for an id with no item. It runs at build
1315
+ * time, for each URL +onBeforePrerenderStart lists. https://vike.dev/data
1316
+ */
1317
+ export function data(pageContext${t(": PageContextServer")}) {
1318
+ const item = items.find(({ id }) => id === pageContext.routeParams.id)
1319
+ if (!item) throw render(404)
1320
+ return item
1321
+ }
1322
+ ${dataType}`;
1323
+ const itemPrerender = `import { items } from '../../../data/items'
1324
+
1325
+ /** The URLs of this route the build prerenders: one per item. https://vike.dev/onBeforePrerenderStart */
1326
+ export function onBeforePrerenderStart() {
1327
+ return items.map(({ id }) => \`/items/\${id}\`)
1328
+ }
1329
+ `;
1330
+ const itemPage = `import { Flex } from '@soroush.tech/design-system/Flex'
1331
+ import { Link } from '@soroush.tech/design-system/Link'
1332
+ import { Typography } from '@soroush.tech/design-system/Typography'
1333
+ import { useData } from '../../usePageContext'
1334
+ import { StatusChip } from '../StatusChip'
1335
+ ${t("import type { Data } from './+data'\n")}
1336
+ export default function Page() {
1337
+ const item = useData${t("<Data>")}()
1338
+ return (
1339
+ <Flex gap={2} alignItems="flex-start">
1340
+ <Typography variant="h2">{item.title}</Typography>
1341
+ <StatusChip status={item.status} />
1342
+ <Typography color="secondary">{item.summary}</Typography>
1343
+ <Link href="/items">All items</Link>
1344
+ </Flex>
1345
+ )
1346
+ }
1347
+ `;
1348
+ return [
1349
+ {
1350
+ path: `src/data/items.${x}`,
1351
+ content: items
1352
+ },
1353
+ {
1354
+ path: `src/pages/items/StatusChip.${x}x`,
1355
+ content: statusChip
1356
+ },
1357
+ {
1358
+ path: `src/pages/items/+data.${x}`,
1359
+ content: listData
1360
+ },
1361
+ {
1362
+ path: `src/pages/items/+Page.${x}x`,
1363
+ content: listPage
1364
+ },
1365
+ {
1366
+ path: `src/pages/items/@id/+data.${x}`,
1367
+ content: itemData
1368
+ },
1369
+ {
1370
+ path: `src/pages/items/@id/+onBeforePrerenderStart.${x}`,
1371
+ content: itemPrerender
1372
+ },
1373
+ {
1374
+ path: `src/pages/items/@id/+Page.${x}x`,
1375
+ content: itemPage
1376
+ }
1377
+ ];
1378
+ }
1379
+ function createReadme({ name, isTypeScript, hasSampleData }) {
1380
+ const x = isTypeScript ? "ts" : "js";
1381
+ return `# ${name}
1382
+
1383
+ A [Vike](https://vike.dev) app on the [@soroush.tech design system](https://docs.soroush.tech),
1384
+ prerendered at build time with its styles in the HTML, then moving between pages with no reload.
1385
+
1386
+ - \`npm run dev\` starts it, \`npm run build\` builds it, and \`npm run preview\` serves the build.
1387
+ - \`src/pages/\` holds the pages: a folder per route, each with its \`+Page\`.
1388
+ - \`src/pages/+Layout.${x}x\` is the frame every page renders in, inside the app's providers.
1389
+ - \`src/theme/themes.${x}\` holds the light and the dark theme: make them your own.
1390
+ - \`src/pages/+onRenderHtml.${x}x\` and \`+onRenderClient.${x}x\` render the pages, with the styles each
1391
+ page uses in its HTML.
1392
+ ${hasSampleData ? `- \`src/pages/items/\` lists the sample items of \`src/data/items.${x}\`, with a page for each.
1393
+ Their \`+data\` hooks read the data at build time: make them fetch your own.
1394
+ ` : ""}
1395
+ Fonts: the theme names Space Grotesk and JetBrains Mono, and does not load them. See
1396
+ https://docs.soroush.tech/design-system/getting-started/installation/#fonts
1397
+ `;
1398
+ }
1399
+ /** The files of the Vike app `facts` describe. */
1400
+ function createFiles(facts) {
1401
+ const { isTypeScript, scheme } = facts;
1402
+ const x = isTypeScript ? "ts" : "js";
1403
+ const sources = createSources(facts);
1404
+ return [
1405
+ {
1406
+ path: "package.json",
1407
+ content: createPackageJson(facts)
1408
+ },
1409
+ {
1410
+ path: `vite.config.${x}`,
1411
+ content: VITE_CONFIG
1412
+ },
1413
+ ...isTypeScript ? [{
1414
+ path: "tsconfig.json",
1415
+ content: TSCONFIG
1416
+ }] : [],
1417
+ {
1418
+ path: ".gitignore",
1419
+ content: GITIGNORE
1420
+ },
1421
+ {
1422
+ path: "README.md",
1423
+ content: createReadme(facts)
1424
+ },
1425
+ ...isTypeScript ? [{
1426
+ path: "src/vike.d.ts",
1427
+ content: VIKE_TYPES
1428
+ }] : [],
1429
+ {
1430
+ path: `src/theme/themes.${x}`,
1431
+ content: createThemesSource({ isTypeScript })
1432
+ },
1433
+ {
1434
+ path: `src/theme/Providers.${x}`,
1435
+ content: createProvidersSource({
1436
+ isTypeScript,
1437
+ scheme,
1438
+ themesImport: "./themes"
1439
+ })
1440
+ },
1441
+ {
1442
+ path: `src/pages/+config.${x}`,
1443
+ content: sources.config
1444
+ },
1445
+ {
1446
+ path: `src/pages/PageShell.${x}x`,
1447
+ content: sources.PageShell
1448
+ },
1449
+ {
1450
+ path: `src/pages/usePageContext.${x}x`,
1451
+ content: sources.usePageContext
1452
+ },
1453
+ {
1454
+ path: `src/pages/+onRenderHtml.${x}x`,
1455
+ content: sources.onRenderHtml
1456
+ },
1457
+ {
1458
+ path: `src/pages/+onRenderClient.${x}x`,
1459
+ content: sources.onRenderClient
1460
+ },
1461
+ {
1462
+ path: `src/pages/+Layout.${x}x`,
1463
+ content: sources.Layout
1464
+ },
1465
+ {
1466
+ path: `src/pages/index/+Page.${x}x`,
1467
+ content: sources.home
1468
+ },
1469
+ {
1470
+ path: `src/pages/about/+Page.${x}x`,
1471
+ content: sources.about
1472
+ },
1473
+ {
1474
+ path: `src/pages/_error/+Page.${x}x`,
1475
+ content: sources.error
1476
+ },
1477
+ ...facts.hasSampleData ? createSampleDataFiles(facts) : []
1478
+ ];
1479
+ }
1480
+ // src/create/starters.ts
1481
+ /** The starters, by the name `--framework` takes. The first is the default. */
1482
+ const STARTERS = { vike: {
1483
+ title: "Vike",
1484
+ createFiles
1485
+ } };
1486
+ // src/create/create.ts
1487
+ const DEFAULT_NAME = "my-app";
1488
+ const APP_NAME = /^[a-z0-9][a-z0-9._~-]*$/;
1489
+ const MAX_NAME_LENGTH = 214;
1490
+ /** Why `name` cannot name a new app, or `undefined` when it can. */
1491
+ function findNameRefusal(name) {
1492
+ if (APP_NAME.test(name) && name.length <= MAX_NAME_LENGTH) return void 0;
1493
+ return `${name} is not a name create can use: it names the folder and the package, so it takes lowercase letters, digits, and . _ ~ -, and starts with a letter or a digit.`;
1494
+ }
1495
+ /**
1496
+ * The state of the folder the app goes in: `missing` or `empty`, the two create writes in, or why
1497
+ * it refuses it. It never writes in a folder that holds anything.
1498
+ */
1499
+ function getFolderState(target, name) {
1500
+ let stats;
1501
+ try {
1502
+ stats = lstatSync(target);
1503
+ } catch {
1504
+ return "missing";
1505
+ }
1506
+ if (!stats.isDirectory()) return { refusal: `${name} exists, and is not a folder.` };
1507
+ if (readdirSync(target).length > 0) return { refusal: `The folder ${name} is not empty. create writes only in a new or empty one.` };
1508
+ return "empty";
1509
+ }
1510
+ /**
1511
+ * Takes the new app away after a failure: the folder create made, or what it wrote in the empty
1512
+ * one it was given. Returns whether that worked.
1513
+ */
1514
+ function removeApp(target, wasMissing, fileSystem) {
1515
+ try {
1516
+ if (wasMissing) fileSystem.removeTree(target);
1517
+ else for (const entry of readdirSync(target)) fileSystem.removeTree(join(target, entry));
1518
+ return true;
1519
+ } catch {
1520
+ return false;
1521
+ }
1522
+ }
1523
+ /** Whether `folder` is inside a git work tree. */
1524
+ function isInsideRepository(folder, io) {
1525
+ const { status, stdout } = io.run("git", ["rev-parse", "--is-inside-work-tree"], { cwd: folder });
1526
+ return status === 0 && stdout.trim() === "true";
1527
+ }
1528
+ async function askLanguage(io) {
1529
+ const answer = await io.ask("TypeScript or JavaScript? (TypeScript) ");
1530
+ return !/^j(s|avascript)?$/i.test(answer.trim());
1531
+ }
1532
+ async function askName(io) {
1533
+ return (await io.ask(`App name? (${DEFAULT_NAME}) `)).trim() || DEFAULT_NAME;
1534
+ }
1535
+ async function askSampleData(io) {
1536
+ const answer = await io.ask("Add sample data pages? (y/N) ");
1537
+ return /^y(es)?$/i.test(answer.trim());
1538
+ }
1539
+ /** Whether to create the app: never on a dry run or with no terminal, else on --yes or a yes. */
1540
+ async function isApproved(options, isPreviewOnly, io) {
1541
+ if (options.isDryRun) {
1542
+ io.write("Dry run: nothing was written.\n");
1543
+ return false;
1544
+ }
1545
+ if (isPreviewOnly) {
1546
+ io.write("Preview only: there is no terminal to answer in. Run again with --yes to create.\n");
1547
+ return false;
1548
+ }
1549
+ if (options.isConfirmed) return true;
1550
+ const answer = (await io.ask("Create it? (Y/n) ")).trim();
1551
+ const isYes = answer === "" || /^y(es)?$/i.test(answer);
1552
+ if (!isYes) io.write("Nothing was written.\n");
1553
+ return isYes;
1554
+ }
1555
+ function formatClosing(name, plan, packageManager) {
1556
+ const themes = plan.creates.find((file) => /\/themes\.[jt]s$/.test(file.path));
1557
+ const themesStep = themes ? ` - Make the themes your own in ${themes.path}.\n` : "";
1558
+ return `
1559
+ Done: ${name} is ready. Start it with:
1560
+ cd ${name}
1561
+ ${formatRunScript(packageManager, "dev")}
1562
+
1563
+ Next:
1564
+ ${themesStep}${FONTS_STEP}
1565
+
1566
+ ${AGENT_STEPS}`;
1567
+ }
1568
+ /** Writes the app, installs it, then starts its repository. Returns the exit code. */
1569
+ function writeAndInstall({ name, target, wasMissing, plan, packageManager }, options, io, fileSystem) {
1570
+ const fail = (reason) => {
1571
+ const outcome = removeApp(target, wasMissing, fileSystem) ? `${name} was taken away.` : `It could not take ${name} away: remove that folder yourself.`;
1572
+ io.write(`create stopped: ${reason}. ${outcome}\n`);
1573
+ return 1;
1574
+ };
1575
+ try {
1576
+ if (wasMissing) mkdirSync(target);
1577
+ applyPlan(plan, target, fileSystem);
1578
+ } catch (error) {
1579
+ return fail(error.message);
1580
+ }
1581
+ const { command, args, env } = plan.install;
1582
+ io.write(`\nInstalling with ${command}:\n`);
1583
+ if (io.run(command, args, {
1584
+ cwd: target,
1585
+ env,
1586
+ showOutput: true
1587
+ }).status !== 0) return fail("the install failed");
1588
+ if (options.isGit && !isInsideRepository(target, io)) {
1589
+ if (io.run("git", ["init"], { cwd: target }).status !== 0) io.write("\ngit init failed, so the app has no repository. Run git init there yourself.\n");
1590
+ }
1591
+ io.write(formatClosing(name, plan, packageManager));
1592
+ return 0;
1593
+ }
1594
+ /**
1595
+ * Starts a new app on the design system, in a new or empty folder in `io.cwd`: asks what it is
1596
+ * not told, plans with the starter, shows the plan, and writes and installs only after a yes.
1597
+ * `designSystem` is the package it installs. Returns the exit code.
1598
+ */
1599
+ async function runCreate(options, io, designSystem, { starters = STARTERS, fileSystem = nodeFileSystem, userAgent = process.env.npm_config_user_agent } = {}) {
1600
+ const isPreviewOnly = options.isDryRun || !io.isInteractive && !options.isConfirmed;
1601
+ const canAsk = !isPreviewOnly && !options.isConfirmed;
1602
+ const framework = options.framework ?? Object.keys(starters)[0];
1603
+ const starter = framework && Object.hasOwn(starters, framework) ? starters[framework] : void 0;
1604
+ if (!starter) {
1605
+ const names = Object.keys(starters).join(", ") || "none yet";
1606
+ io.write(`create has no starter for ${framework ?? "any framework"}. It has: ${names}.\n`);
1607
+ return 1;
1608
+ }
1609
+ const name = options.name ?? (canAsk ? await askName(io) : DEFAULT_NAME);
1610
+ const nameRefusal = findNameRefusal(name);
1611
+ if (nameRefusal) {
1612
+ io.write(`${nameRefusal}\n`);
1613
+ return 1;
1614
+ }
1615
+ const target = join(realpathSync(io.cwd), name);
1616
+ const folder = getFolderState(target, name);
1617
+ if (typeof folder === "object") {
1618
+ io.write(`${folder.refusal}\n`);
1619
+ return 1;
1620
+ }
1621
+ const isTypeScript = options.isTypeScript ?? (canAsk ? await askLanguage(io) : true);
1622
+ const scheme = options.scheme ?? (canAsk ? await askScheme(io) : "light");
1623
+ const hasSampleData = options.hasSampleData ?? (canAsk ? await askSampleData(io) : false);
1624
+ const packageManager = readPackageManager(userAgent);
1625
+ const plan = {
1626
+ creates: starter.createFiles({
1627
+ name,
1628
+ isTypeScript,
1629
+ scheme,
1630
+ hasSampleData,
1631
+ version: designSystem.version
1632
+ }),
1633
+ edits: [],
1634
+ skips: [],
1635
+ manual: [],
1636
+ install: createAppInstallCommand(packageManager)
1637
+ };
1638
+ const language = isTypeScript ? "TypeScript" : "JavaScript";
1639
+ io.write(`create will make ${name}, a ${starter.title} app in ${language}, in ./${name}:\n\n`);
1640
+ io.write(`${formatPlan(plan)}\n`);
1641
+ if (!await isApproved(options, isPreviewOnly, io)) return 0;
1642
+ return writeAndInstall({
1643
+ name,
1644
+ target,
1645
+ wasMissing: folder === "missing",
1646
+ plan,
1647
+ packageManager
1648
+ }, options, io, fileSystem);
1649
+ }
820
1650
  // src/main.ts
821
- const USAGE = `Usage: npx @soroush.tech/design-system init [options]
1651
+ const USAGE = `Usage: npx @soroush.tech/design-system <command> [options]
1652
+
1653
+ Commands:
1654
+ init set up @soroush.tech/design-system in the React app in this folder
1655
+ create [name] start a new app on the design system, in a new folder
822
1656
 
823
- Sets up @soroush.tech/design-system in the React app in this folder. It shows every change
824
- first, and writes nothing until you say yes.
1657
+ Each shows every change first, and writes nothing until you say yes.
825
1658
 
826
1659
  Options:
827
1660
  -y, --yes apply without asking
828
1661
  --dry-run show the changes and exit
829
- --force run outside git, or with uncommitted changes
830
1662
  --scheme <name> the default color scheme: light or dark
831
1663
  -h, --help show this help
1664
+
1665
+ Options of init:
1666
+ --force run outside git, or with uncommitted changes
1667
+
1668
+ Options of create:
1669
+ --framework <name> the app's framework
1670
+ --ts, --js TypeScript (the default) or JavaScript
1671
+ --sample-data add pages that read sample data
1672
+ --no-git do not run git init
832
1673
  `;
1674
+ const OPTIONS = {
1675
+ yes: {
1676
+ type: "boolean",
1677
+ short: "y"
1678
+ },
1679
+ "dry-run": { type: "boolean" },
1680
+ scheme: { type: "string" },
1681
+ help: {
1682
+ type: "boolean",
1683
+ short: "h"
1684
+ },
1685
+ force: { type: "boolean" },
1686
+ framework: { type: "string" },
1687
+ ts: { type: "boolean" },
1688
+ js: { type: "boolean" },
1689
+ "sample-data": { type: "boolean" },
1690
+ "no-git": { type: "boolean" }
1691
+ };
1692
+ /** The options only one command takes. */
1693
+ const OWN_OPTIONS = {
1694
+ init: ["force"],
1695
+ create: [
1696
+ "framework",
1697
+ "ts",
1698
+ "js",
1699
+ "sample-data",
1700
+ "no-git"
1701
+ ]
1702
+ };
1703
+ /** Why the command line is wrong for `command`, or `undefined` when it is right. */
1704
+ function findMisuse(command, extra, used) {
1705
+ const others = Object.entries(OWN_OPTIONS).filter(([name]) => name !== command);
1706
+ for (const [other, options] of others) {
1707
+ const option = used.find((name) => options.includes(name));
1708
+ if (option) return `--${option} is an option of ${other}, not of ${command}.`;
1709
+ }
1710
+ const maxPositionals = command === "create" ? 1 : 0;
1711
+ return extra.length > maxPositionals ? `Unknown command: ${command} ${extra.join(" ")}` : void 0;
1712
+ }
833
1713
  /**
834
1714
  * Reads the command line and runs the command, for `designSystem`: the package of
835
- * `@soroush.tech/design-system` that init installs. Returns the exit code.
1715
+ * `@soroush.tech/design-system` the command installs. Returns the exit code.
836
1716
  */
837
1717
  async function main(argv, io, designSystem) {
838
1718
  let parsed;
@@ -840,19 +1720,7 @@ async function main(argv, io, designSystem) {
840
1720
  parsed = parseArgs({
841
1721
  args: [...argv],
842
1722
  allowPositionals: true,
843
- options: {
844
- yes: {
845
- type: "boolean",
846
- short: "y"
847
- },
848
- "dry-run": { type: "boolean" },
849
- force: { type: "boolean" },
850
- scheme: { type: "string" },
851
- help: {
852
- type: "boolean",
853
- short: "h"
854
- }
855
- }
1723
+ options: OPTIONS
856
1724
  });
857
1725
  } catch (error) {
858
1726
  io.write(`${error.message}\n\n${USAGE}`);
@@ -864,19 +1732,43 @@ async function main(argv, io, designSystem) {
864
1732
  return 0;
865
1733
  }
866
1734
  const [command, ...extra] = positionals;
867
- if (command !== "init" || extra.length > 0) {
1735
+ if (!command || !Object.hasOwn(OWN_OPTIONS, command)) {
868
1736
  const unknown = command ? `Unknown command: ${positionals.join(" ")}\n\n` : "";
869
1737
  io.write(unknown + USAGE);
870
1738
  return 1;
871
1739
  }
1740
+ const misuse = findMisuse(command, extra, Object.keys(values));
1741
+ if (misuse) {
1742
+ io.write(`${misuse}\n\n${USAGE}`);
1743
+ return 1;
1744
+ }
872
1745
  const { scheme } = values;
873
1746
  if (scheme !== void 0 && scheme !== "light" && scheme !== "dark") {
874
1747
  io.write(`--scheme is light or dark, not ${scheme}.\n`);
875
1748
  return 1;
876
1749
  }
1750
+ if (values.ts && values.js) {
1751
+ io.write("--ts and --js do not go together: give one.\n");
1752
+ return 1;
1753
+ }
1754
+ const isConfirmed = Boolean(values.yes);
1755
+ const isDryRun = Boolean(values["dry-run"]);
1756
+ if (command === "create") {
1757
+ const isTypeScript = values.ts || values.js ? Boolean(values.ts) : void 0;
1758
+ return runCreate({
1759
+ name: extra[0],
1760
+ framework: values.framework,
1761
+ isTypeScript,
1762
+ scheme,
1763
+ hasSampleData: values["sample-data"],
1764
+ isConfirmed,
1765
+ isDryRun,
1766
+ isGit: !values["no-git"]
1767
+ }, io, designSystem);
1768
+ }
877
1769
  return runInit({
878
- isConfirmed: Boolean(values.yes),
879
- isDryRun: Boolean(values["dry-run"]),
1770
+ isConfirmed,
1771
+ isDryRun,
880
1772
  isForced: Boolean(values.force),
881
1773
  scheme
882
1774
  }, io, designSystem);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@soroush.design/cli",
3
- "version": "0.1.0-alpha.3",
4
- "description": "The command line of the @soroush.tech design system: init sets it up in an existing React app, showing every change first.",
3
+ "version": "0.2.0-alpha.0",
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",
7
7
  "init",
@@ -39,13 +39,19 @@
39
39
  "access": "public"
40
40
  },
41
41
  "devDependencies": {
42
+ "@emotion/server": "^11.11.0",
42
43
  "@types/node": "^26.6.6",
43
44
  "@types/react": "^19.3.0",
44
45
  "@types/react-dom": "^19.3.0",
46
+ "@vitejs/plugin-react": "^6.3.0",
45
47
  "@vitest/coverage-v8": "^5.1.0",
46
48
  "oxlint": "^1.93.0",
49
+ "react": "^19.3.1",
50
+ "react-dom": "^19.3.1",
47
51
  "tsdown": "^0.23.7",
48
52
  "typescript": "~7.0.2",
53
+ "vike": "0.4.270",
54
+ "vite": "~8.3.8",
49
55
  "vitest": "^5.1.0",
50
56
  "@soroush.tech/eslint-config": "0.0.0"
51
57
  },
@@ -55,7 +61,7 @@
55
61
  "typecheck": "tsc --noEmit",
56
62
  "test": "vitest run",
57
63
  "test:coverage": "vitest run --coverage",
58
- "test:types": "pnpm --filter @soroush.tech/design-system build && tsc -p type-tests/init/tsconfig.json"
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"
59
65
  },
60
66
  "module": "./dist/index.mjs"
61
67
  }