create-better-t-stack 1.1.0 → 1.2.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/dist/index.js +64 -64
- package/package.json +1 -1
- package/template/base/apps/server/package.json +0 -2
- package/template/base/apps/server/tsconfig.json +1 -1
- package/template/{with-prisma-sqlite/apps/server/src/with-auth-lib/context.ts → with-auth/apps/server/src/lib/with-elysia-context.ts} +4 -4
- package/template/{with-drizzle-sqlite/apps/server/src/with-auth-lib/context.ts → with-auth/apps/server/src/lib/with-hono-context.ts} +3 -3
- package/template/with-auth/apps/server/src/with-elysia-index.ts +38 -0
- package/template/with-auth/apps/server/src/{index.ts → with-hono-index.ts} +3 -2
- package/template/with-elysia/apps/server/src/index.ts +27 -0
- package/template/with-elysia/apps/server/src/lib/context.ts +13 -0
- package/template/{base → with-hono}/apps/server/src/index.ts +2 -2
- package/template/{base → with-hono}/apps/server/src/lib/context.ts +2 -2
- package/template/with-drizzle-postgres/apps/server/src/routers/todo.ts +0 -44
- package/template/with-drizzle-postgres/apps/server/src/with-auth-lib/context.ts +0 -18
- package/template/with-drizzle-postgres/apps/server/src/with-auth-lib/trpc.ts +0 -24
- package/template/with-drizzle-sqlite/apps/server/src/with-auth-lib/trpc.ts +0 -24
- package/template/with-prisma-postgres/apps/server/src/with-auth-lib/context.ts +0 -18
- package/template/with-prisma-postgres/apps/server/src/with-auth-lib/trpc.ts +0 -24
- package/template/with-prisma-sqlite/apps/server/src/with-auth-lib/trpc.ts +0 -24
- package/template/{with-drizzle-postgres/apps/server/src/with-auth-lib → with-auth/apps/server/src/with-drizzle-postgres-lib}/auth.ts +1 -1
- /package/template/{with-drizzle-sqlite/apps/server/src/with-auth-lib → with-auth/apps/server/src/with-drizzle-sqlite-lib}/auth.ts +0 -0
- /package/template/{with-prisma-postgres/apps/server/src/with-auth-lib → with-auth/apps/server/src/with-prisma-postgres-lib}/auth.ts +0 -0
- /package/template/{with-prisma-sqlite/apps/server/src/with-auth-lib → with-auth/apps/server/src/with-prisma-sqlite-lib}/auth.ts +0 -0
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{cancel as
|
|
2
|
+
import{cancel as tr,intro as ar,log as $,outro as rr,spinner as or}from"@clack/prompts";import{Command as ir}from"commander";import E from"picocolors";import ee from"node:path";import{fileURLToPath as tt}from"node:url";var z=()=>{let e=process.env.npm_config_user_agent;return e?.startsWith("pnpm")?"pnpm":e?.startsWith("bun")?"bun":"npm"};var at=tt(import.meta.url),rt=ee.dirname(at),y=ee.join(rt,"../"),c={projectName:"my-better-t-app",database:"sqlite",orm:"drizzle",auth:!0,addons:[],examples:[],git:!0,packageManager:z(),noInstall:!1,turso:!1,backendFramework:"hono",runtime:"bun"},q={"better-auth":"^1.2.4","drizzle-orm":"^0.38.4","drizzle-kit":"^0.30.5","@libsql/client":"^0.14.0",postgres:"^3.4.5","@prisma/client":"^6.5.0",prisma:"^6.5.0","vite-plugin-pwa":"^0.21.2","@vite-pwa/assets-generator":"^0.2.6","@tauri-apps/cli":"^2.4.0","@biomejs/biome":"1.9.4",husky:"^9.1.7","lint-staged":"^15.5.0","@hono/node-server":"^1.14.0",tsx:"^4.19.2","@types/node":"^22.13.11","@types/bun":"^1.2.6","@elysiajs/node":"^1.2.6","@elysiajs/cors":"^1.2.0","@elysiajs/trpc":"^1.1.0",elysia:"^1.2.25","@hono/trpc-server":"^0.3.4",hono:"^4.7.5"};import Kt from"node:path";import{cancel as Xt,spinner as Yt}from"@clack/prompts";import Zt from"fs-extra";import Ce from"picocolors";import S from"node:path";import k from"fs-extra";import ot from"node:path";import te from"fs-extra";var h=e=>{let{dependencies:a=[],devDependencies:t=[],projectDir:r}=e,o=ot.join(r,"package.json"),i=te.readJSONSync(o);i.dependencies||(i.dependencies={}),i.devDependencies||(i.devDependencies={});for(let s of a){let n=q[s];i.dependencies[s]=n}for(let s of t){let n=q[s];i.devDependencies[s]=n}te.writeJSONSync(o,i,{spaces:2})};import U from"node:path";import{log as it,spinner as st}from"@clack/prompts";import{execa as nt}from"execa";import V from"fs-extra";import ae from"picocolors";async function re(e,a){let t=st(),r=U.join(e,"apps/client");try{t.start("Setting up Tauri desktop app support..."),h({devDependencies:["@tauri-apps/cli"],projectDir:r});let o=U.join(r,"package.json");if(await V.pathExists(o)){let n=await V.readJson(o);n.scripts={...n.scripts,tauri:"tauri","desktop:dev":"tauri dev","desktop:build":"tauri build"},await V.writeJson(o,n,{spaces:2})}let i,s;switch(a){case"npm":i="npx",s=["@tauri-apps/cli@latest"];break;case"pnpm":i="pnpm",s=["dlx","@tauri-apps/cli@latest"];break;case"bun":i="bunx",s=["@tauri-apps/cli@latest"];break;default:i="npx",s=["@tauri-apps/cli@latest"]}s=[...s,"init",`--app-name=${U.basename(e)}`,`--window-title=${U.basename(e)}`,"--frontend-dist=dist","--dev-url=http://localhost:3001",`--before-dev-command=${a} run dev`,`--before-build-command=${a} run build`],await nt(i,s,{cwd:r,env:{CI:"true"}}),t.stop("Tauri desktop app support configured successfully!")}catch(o){throw t.stop(ae.red("Failed to set up Tauri")),o instanceof Error&&it.error(ae.red(o.message)),o}}async function oe(e,a,t){a.includes("pwa")&&await lt(e),a.includes("tauri")&&await re(e,t),a.includes("biome")&&await ct(e),a.includes("husky")&&await pt(e)}async function ct(e){let a=S.join(y,"template/with-biome");await k.pathExists(a)&&await k.copy(a,e,{overwrite:!0}),h({devDependencies:["@biomejs/biome"],projectDir:e});let t=S.join(e,"package.json");if(await k.pathExists(t)){let r=await k.readJson(t);r.scripts={...r.scripts,check:"biome check --write ."},await k.writeJson(t,r,{spaces:2})}}async function pt(e){let a=S.join(y,"template/with-husky");await k.pathExists(a)&&await k.copy(a,e,{overwrite:!0}),h({devDependencies:["husky","lint-staged"],projectDir:e});let t=S.join(e,"package.json");if(await k.pathExists(t)){let r=await k.readJson(t);r.scripts={...r.scripts,prepare:"husky"},r["lint-staged"]={"*.{js,ts,cjs,mjs,d.cts,d.mts,jsx,tsx,json,jsonc}":["biome check --write ."]},await k.writeJson(t,r,{spaces:2})}}async function lt(e){let a=S.join(y,"template/with-pwa");await k.pathExists(a)&&await k.copy(a,e,{overwrite:!0});let t=S.join(e,"apps/client");h({dependencies:["vite-plugin-pwa"],devDependencies:["@vite-pwa/assets-generator"],projectDir:t});let r=S.join(t,"package.json");if(await k.pathExists(r)){let o=await k.readJson(r);o.scripts={...o.scripts,"generate-pwa-assets":"pwa-assets-generator"},await k.writeJson(r,o,{spaces:2})}}import ie from"node:path";import{log as se}from"@clack/prompts";import ne from"picocolors";function ce(e=32){let a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="",r=a.length;for(let o=0;o<e;o++)t+=a.charAt(Math.floor(Math.random()*r));return t}async function pe(e,a){if(!a)return;let t=ie.join(e,"apps/server"),r=ie.join(e,"apps/client");try{h({dependencies:["better-auth"],projectDir:t}),h({dependencies:["better-auth"],projectDir:r})}catch(o){throw se.error(ne.red("Failed to configure authentication")),o instanceof Error&&se.error(ne.red(o.message)),o}}import dt from"node:path";async function le(e,a,t){let r=dt.join(e,"apps/server"),o=[],i=[];a==="hono"?(o.push("hono","@hono/trpc-server"),t==="node"&&(o.push("@hono/node-server"),i.push("tsx","@types/node"))):a==="elysia"&&(o.push("elysia","@elysiajs/cors","@elysiajs/trpc"),t==="node"&&(o.push("@elysiajs/node"),i.push("tsx","@types/node"))),t==="bun"&&i.push("@types/bun"),h({dependencies:o,devDependencies:i,projectDir:r})}import ut from"node:path";import mt from"fs-extra";async function de(e,a){let t=ut.join(e,"README.md"),r=ft(a);try{await mt.writeFile(t,r)}catch(o){console.error("Failed to create README.md file:",o)}}function ft(e){let{projectName:a,packageManager:t,database:r,auth:o,addons:i=[],orm:s="drizzle",runtime:n="bun"}=e,u=t==="npm"?"npm run":t;return`# ${a}
|
|
3
3
|
|
|
4
4
|
This project was created with [Better-T-Stack](https://github.com/better-t-stack/Better-T-Stack), a modern TypeScript stack that combines React, TanStack Router, Hono, tRPC, and more.
|
|
5
5
|
|
|
6
6
|
## Features
|
|
7
7
|
|
|
8
|
-
${
|
|
8
|
+
${ht(r,o,i,s,n)}
|
|
9
9
|
|
|
10
10
|
## Getting Started
|
|
11
11
|
|
|
@@ -15,12 +15,12 @@ First, install the dependencies:
|
|
|
15
15
|
${t} install
|
|
16
16
|
\`\`\`
|
|
17
17
|
|
|
18
|
-
${
|
|
18
|
+
${gt(r,o,u,s)}
|
|
19
19
|
|
|
20
20
|
Then, run the development server:
|
|
21
21
|
|
|
22
22
|
\`\`\`bash
|
|
23
|
-
${
|
|
23
|
+
${u} dev
|
|
24
24
|
\`\`\`
|
|
25
25
|
|
|
26
26
|
Open [http://localhost:3001](http://localhost:3001) in your browser to see the client application.
|
|
@@ -37,11 +37,11 @@ ${a}/
|
|
|
37
37
|
|
|
38
38
|
## Available Scripts
|
|
39
39
|
|
|
40
|
-
${
|
|
41
|
-
`}function
|
|
42
|
-
`)}function
|
|
40
|
+
${wt(u,r,s,o)}
|
|
41
|
+
`}function ht(e,a,t,r,o){let i=["- **TypeScript** - For type safety and improved developer experience","- **TanStack Router** - File-based routing with full type safety","- **TailwindCSS** - Utility-first CSS for rapid UI development","- **shadcn/ui** - Reusable UI components","- **Hono** - Lightweight, performant server framework","- **tRPC** - End-to-end type-safe APIs",`- **${o==="bun"?"Bun":"Node.js"}** - Runtime environment`];e!=="none"&&i.push(`- **${r==="drizzle"?"Drizzle":"Prisma"}** - TypeScript-first ORM`,`- **${e==="sqlite"?"SQLite/Turso":"PostgreSQL"}** - Database engine`),a&&i.push("- **Authentication** - Email & password authentication with Better Auth");for(let s of t)s==="pwa"?i.push("- **PWA** - Progressive Web App support"):s==="tauri"?i.push("- **Tauri** - Build native desktop applications"):s==="biome"?i.push("- **Biome** - Linting and formatting"):s==="husky"&&i.push("- **Husky** - Git hooks for code quality");return i.join(`
|
|
42
|
+
`)}function gt(e,a,t,r){if(e==="none")return"";let o=`## Database Setup
|
|
43
43
|
|
|
44
|
-
`;return e==="sqlite"?
|
|
44
|
+
`;return e==="sqlite"?o+=`This project uses SQLite${r==="drizzle"?" with Drizzle ORM":" with Prisma"}.
|
|
45
45
|
|
|
46
46
|
1. Start the local SQLite database:
|
|
47
47
|
\`\`\`bash
|
|
@@ -49,29 +49,29 @@ cd apps/server && ${t} db:local
|
|
|
49
49
|
\`\`\`
|
|
50
50
|
|
|
51
51
|
2. Update your \`.env\` file in the \`apps/server\` directory with the appropriate connection details if needed.
|
|
52
|
-
`:e==="postgres"&&(
|
|
52
|
+
`:e==="postgres"&&(o+=`This project uses PostgreSQL${r==="drizzle"?" with Drizzle ORM":" with Prisma"}.
|
|
53
53
|
|
|
54
54
|
1. Make sure you have a PostgreSQL database set up.
|
|
55
55
|
2. Update your \`apps/server/.env\` file with your PostgreSQL connection details.
|
|
56
|
-
`),
|
|
57
|
-
${a?"4":"3"}. ${
|
|
56
|
+
`),o+=`
|
|
57
|
+
${a?"4":"3"}. ${r==="prisma"?`Generate the Prisma client and push the schema:
|
|
58
58
|
\`\`\`bash
|
|
59
59
|
${t} db:push
|
|
60
60
|
\`\`\``:`Apply the schema to your database:
|
|
61
61
|
\`\`\`bash
|
|
62
62
|
${t} db:push
|
|
63
63
|
\`\`\``}
|
|
64
|
-
`,
|
|
64
|
+
`,o}function wt(e,a,t,r){let o=`- \`${e} dev\`: Start both client and server in development mode
|
|
65
65
|
- \`${e} build\`: Build both client and server
|
|
66
66
|
- \`${e} dev:client\`: Start only the client
|
|
67
67
|
- \`${e} dev:server\`: Start only the server
|
|
68
|
-
- \`${e} check-types\`: Check TypeScript types across all apps`;return a!=="none"&&(
|
|
68
|
+
- \`${e} check-types\`: Check TypeScript types across all apps`;return a!=="none"&&(o+=`
|
|
69
69
|
- \`${e} db:push\`: Push schema changes to database
|
|
70
|
-
- \`${e} db:studio\`: Open database studio UI`,a==="sqlite"&&t==="drizzle"&&(
|
|
71
|
-
- \`cd apps/server && ${e} db:local\`: Start the local SQLite database`)),
|
|
72
|
-
`);return a.length<=1?[]:a.slice(1).map(
|
|
70
|
+
- \`${e} db:studio\`: Open database studio UI`,a==="sqlite"&&t==="drizzle"&&(o+=`
|
|
71
|
+
- \`cd apps/server && ${e} db:local\`: Start the local SQLite database`)),o}import fe from"node:path";import{log as Ot,spinner as Ft}from"@clack/prompts";import St from"fs-extra";import he from"picocolors";import bt from"node:os";import ue from"node:path";import{cancel as H,confirm as yt,isCancel as W,log as I,select as kt,spinner as Q,text as Pt}from"@clack/prompts";import{$ as x}from"execa";import jt from"fs-extra";import j from"picocolors";async function vt(){try{return(await x`turso --version`).exitCode===0}catch{return!1}}async function xt(){try{return!(await x`turso auth whoami`).stdout.includes("You are not logged in")}catch{return!1}}async function Tt(){let e=Q();try{return e.start("Logging in to Turso..."),await x`turso auth login`,e.stop("Logged in to Turso successfully!"),!0}catch(a){throw e.stop(j.red("Failed to log in to Turso")),a}}async function $t(e){let a=Q();try{if(a.start("Installing Turso CLI..."),e)await x`brew install tursodatabase/tap/turso`;else{let{stdout:t}=await x`curl -sSfL https://get.tur.so/install.sh`;await x`bash -c '${t}'`}return a.stop("Turso CLI installed successfully!"),!0}catch(t){throw t instanceof Error&&t.message.includes("User force closed")?(a.stop(),I.warn(j.yellow("Turso CLI installation cancelled by user")),new Error("Installation cancelled")):(a.stop(j.red("Failed to install Turso CLI")),t)}}async function Et(){try{let{stdout:e}=await x`turso group list`,a=e.trim().split(`
|
|
72
|
+
`);return a.length<=1?[]:a.slice(1).map(r=>{let[o,i,s,n]=r.trim().split(/\s{2,}/);return{name:o,locations:i,version:s,status:n}})}catch(e){return console.error("Error fetching Turso groups:",e),[]}}async function Ct(){let e=await Et();if(e.length===0)return null;if(e.length===1)return e[0].name;let a=e.map(r=>({value:r.name,label:`${r.name} (${r.locations})`})),t=await kt({message:"Select a Turso database group:",options:a});return W(t)&&(H(j.red("Operation cancelled")),process.exit(0)),t}async function Dt(e,a){try{a?await x`turso db create ${e} --group ${a}`:await x`turso db create ${e}`}catch(o){throw o instanceof Error&&o.message.includes("already exists")?new Error("DATABASE_EXISTS"):o}let{stdout:t}=await x`turso db show ${e} --url`,{stdout:r}=await x`turso db tokens create ${e}`;return{dbUrl:t.trim(),authToken:r.trim()}}async function L(e,a){let t=ue.join(e,"apps/server",".env"),r=a?`TURSO_CONNECTION_URL="${a.dbUrl}"
|
|
73
73
|
TURSO_AUTH_TOKEN="${a.authToken}"`:`TURSO_CONNECTION_URL=
|
|
74
|
-
TURSO_AUTH_TOKEN=`;await
|
|
74
|
+
TURSO_AUTH_TOKEN=`;await jt.writeFile(t,r)}function B(){I.info(`Manual Turso Setup Instructions:
|
|
75
75
|
|
|
76
76
|
1. Visit https://turso.tech and create an account
|
|
77
77
|
2. Create a new database from the dashboard
|
|
@@ -79,65 +79,65 @@ TURSO_AUTH_TOKEN=`;await wt.writeFile(t,o)}function U(){I.info(`Manual Turso Set
|
|
|
79
79
|
4. Add these credentials to the .env file in apps/server/.env
|
|
80
80
|
|
|
81
81
|
TURSO_CONNECTION_URL=your_database_url
|
|
82
|
-
TURSO_AUTH_TOKEN=your_auth_token`)}async function
|
|
83
|
-
CORS_ORIGIN=http://localhost:3001`),a.auth&&(
|
|
84
|
-
BETTER_AUTH_SECRET=${
|
|
85
|
-
BETTER_AUTH_URL=http://localhost:3000`)),a.database!=="none"){if(a.orm==="prisma"&&!
|
|
86
|
-
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/mydb?schema=public"`;
|
|
87
|
-
TURSO_CONNECTION_URL=http://127.0.0.1:8080`))}await
|
|
88
|
-
`),await
|
|
82
|
+
TURSO_AUTH_TOKEN=your_auth_token`)}async function me(e,a){if(!a){await L(e),I.info(j.blue("Skipping Turso setup. Setting up empty configuration.")),B();return}let t=bt.platform(),r=t==="darwin";if(!(t!=="win32")){I.warn(j.yellow("Automatic Turso setup is not supported on Windows.")),await L(e),B();return}try{if(!await vt()){let P=await yt({message:"Would you like to install Turso CLI?",initialValue:!0});if(W(P)&&(H(j.red("Operation cancelled")),process.exit(0)),!P){await L(e),B();return}await $t(r)}await xt()||await Tt();let n=await Ct(),u=!1,f="",b=ue.basename(e);for(;!u;){let P=await Pt({message:"Enter a name for your database:",defaultValue:b,initialValue:b,placeholder:b});W(P)&&(H(j.red("Operation cancelled")),process.exit(0)),f=P;let C=Q();try{C.start(`Creating Turso database "${f}"${n?` in group "${n}"`:""}...`);let D=await Dt(f,n);await L(e,D),C.stop("Turso database configured successfully!"),u=!0}catch(D){if(D instanceof Error&&D.message==="DATABASE_EXISTS")C.stop(j.yellow(`Database "${j.red(f)}" already exists`)),b=`${f}-${Math.floor(Math.random()*1e3)}`;else throw C.stop(j.red("Failed to create Turso database")),D}}}catch(i){I.error(j.red(`Error during Turso setup: ${i}`)),await L(e),B(),I.success("Setup completed with manual configuration required.")}}async function ge(e,a,t,r=!0){let o=Ft(),i=fe.join(e,"apps/server");if(a==="none"){await St.remove(fe.join(i,"src/db"));return}try{a==="sqlite"?(t==="drizzle"?h({dependencies:["drizzle-orm","@libsql/client"],devDependencies:["drizzle-kit"],projectDir:i}):t==="prisma"&&h({dependencies:["@prisma/client"],devDependencies:["prisma"],projectDir:i}),r&&await me(e,!0)):a==="postgres"&&(t==="drizzle"?h({dependencies:["drizzle-orm","postgres"],devDependencies:["drizzle-kit"],projectDir:i}):t==="prisma"&&h({dependencies:["@prisma/client"],devDependencies:["prisma"],projectDir:i}))}catch(s){throw o.stop(he.red("Failed to set up database")),s instanceof Error&&Ot.error(he.red(s.message)),s}}import _ from"node:path";import R from"fs-extra";async function we(e,a){let t=_.join(e,"apps/server"),r=_.join(e,"apps/client"),o=_.join(t,".env"),i="";if(await R.pathExists(o)&&(i=await R.readFile(o,"utf8")),i.includes("CORS_ORIGIN")||(i+=`
|
|
83
|
+
CORS_ORIGIN=http://localhost:3001`),a.auth&&(i.includes("BETTER_AUTH_SECRET")||(i+=`
|
|
84
|
+
BETTER_AUTH_SECRET=${ce()}`),i.includes("BETTER_AUTH_URL")||(i+=`
|
|
85
|
+
BETTER_AUTH_URL=http://localhost:3000`)),a.database!=="none"){if(a.orm==="prisma"&&!i.includes("DATABASE_URL")){let u=a.database==="sqlite"?"":`
|
|
86
|
+
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/mydb?schema=public"`;i+=u}a.database==="sqlite"&&!a.turso&&(i.includes("TURSO_CONNECTION_URL")||(i+=`
|
|
87
|
+
TURSO_CONNECTION_URL=http://127.0.0.1:8080`))}await R.writeFile(o,i.trim());let s=_.join(r,".env"),n="";await R.pathExists(s)&&(n=await R.readFile(s,"utf8")),n.includes("VITE_SERVER_URL")||(n+=`VITE_SERVER_URL=http://localhost:3000
|
|
88
|
+
`),await R.writeFile(s,n.trim())}import T from"node:path";import w from"fs-extra";async function be(e,a,t,r){a.includes("todo")?await At(e,t,r):await Rt(e,t)}async function At(e,a,t){let r=T.join(y,"template/examples/todo");if(await w.pathExists(r)){let o=T.join(r,"apps/client/src/routes"),i=T.join(e,"apps/client/src/routes");if(await w.copy(o,i,{overwrite:!0}),a!=="none"){let s=T.join(r,`apps/server/src/routers/with-${a}-todo.ts`),n=T.join(e,"apps/server/src/routers/todo.ts");await w.pathExists(s)&&await w.copy(s,n,{overwrite:!0})}await It(e,t),await Nt(e)}}async function It(e,a){let t=T.join(e,"apps/client/src/components/header.tsx");if(await w.pathExists(t)){let r=await w.readFile(t,"utf8");a?r=r.replace(/const links = \[\s*{ to: "\/", label: "Home" },\s*{ to: "\/dashboard", label: "Dashboard" },/,`const links = [
|
|
89
89
|
{ to: "/", label: "Home" },
|
|
90
90
|
{ to: "/dashboard", label: "Dashboard" },
|
|
91
|
-
{ to: "/todos", label: "Todos" },`):
|
|
91
|
+
{ to: "/todos", label: "Todos" },`):r=r.replace(/const links = \[\s*{ to: "\/", label: "Home" },/,`const links = [
|
|
92
92
|
{ to: "/", label: "Home" },
|
|
93
|
-
{ to: "/todos", label: "Todos" },`),await
|
|
93
|
+
{ to: "/todos", label: "Todos" },`),await w.writeFile(t,r)}}async function Rt(e,a){if(a==="drizzle"){let r=T.join(e,"apps/server/src/db/schema/todo.ts");await w.pathExists(r)&&await w.remove(r)}else if(a==="prisma"){let r=T.join(e,"apps/server/prisma/schema/todo.prisma");await w.pathExists(r)&&await w.remove(r)}let t=T.join(e,"apps/server/src/routers/todo.ts");await w.pathExists(t)&&await w.remove(t),await Lt(e)}async function Lt(e){let a=T.join(e,"apps/server/src/routers/index.ts");if(await w.pathExists(a)){let t=await w.readFile(a,"utf8");t=t.replace(/import { todoRouter } from ".\/todo";/,""),t=t.replace(/todo: todoRouter,/,""),await w.writeFile(a,t)}}async function Nt(e){let a=T.join(e,"apps/client/src/routes/index.tsx");if(await w.pathExists(a)){let t=await w.readFile(a,"utf8");t=t.replace(/<div id="buttons"><\/div>/,`<div id="buttons" className="mt-4 flex flex-col gap-4 sm:flex-row sm:items-center">
|
|
94
94
|
<Button asChild>
|
|
95
95
|
<Link to="/todos" className="flex items-center">
|
|
96
96
|
View Todo Demo
|
|
97
97
|
<ArrowRight className="ml-1 h-4 w-4" />
|
|
98
98
|
</Link>
|
|
99
99
|
</Button>
|
|
100
|
-
</div>`),await
|
|
101
|
-
|
|
102
|
-
${
|
|
103
|
-
${
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
${
|
|
108
|
-
${
|
|
109
|
-
${
|
|
110
|
-
${
|
|
111
|
-
${
|
|
112
|
-
${
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
`}function Ft(e,a,t,o){let r=[];return a==="prisma"?(e==="sqlite"&&r.push(`${l.yellow("NOTE:")} Turso support with Prisma is in Early Access and requires additional setup.`,`${l.dim("Learn more at: https://www.prisma.io/docs/orm/overview/databases/turso")}`),o==="bun"&&r.push(`${l.yellow("NOTE:")} Prisma with Bun may require additional configuration. If you encounter errors, follow the guidance provided in the error messages`),r.push(`${l.cyan("\u2022")} Apply schema: ${l.dim(`${t} db:push`)}`),r.push(`${l.cyan("\u2022")} Database UI: ${l.dim(`${t} db:studio`)}`)):a==="drizzle"&&(e==="sqlite"&&r.push(`${l.cyan("\u2022")} Start local DB: ${l.dim(`cd apps/server && ${t} db:local`)}`),r.push(`${l.cyan("\u2022")} Apply schema: ${l.dim(`${t} db:push`)}`),r.push(`${l.cyan("\u2022")} Database UI: ${l.dim(`${t} db:studio`)}`)),r.length?`${l.bold("Database commands:")}
|
|
117
|
-
${r.join(`
|
|
100
|
+
</div>`),await w.writeFile(a,t)}}import{log as zt}from"@clack/prompts";import d from"picocolors";function ye(e,a,t,r,o,i,s){let n=t==="npm"?"npm run":t,u=`cd ${a}`,f=i?.includes("husky")||i?.includes("biome"),b=e!=="none"?Bt(e,o,n,s):"",P=i?.includes("tauri")?_t(n):"",C=f?Ut(n):"";zt.info(`${d.bold("Next steps:")}
|
|
101
|
+
${d.cyan("1.")} ${u}
|
|
102
|
+
${r?"":`${d.cyan("2.")} ${t} install
|
|
103
|
+
`}${d.cyan(r?"2.":"3.")} ${n} dev
|
|
104
|
+
|
|
105
|
+
${d.bold("Your project will be available at:")}
|
|
106
|
+
${d.cyan("\u2022")} Frontend: http://localhost:3001
|
|
107
|
+
${d.cyan("\u2022")} API: http://localhost:3000
|
|
108
|
+
${b?`
|
|
109
|
+
${b.trim()}`:""}${P?`
|
|
110
|
+
${P.trim()}`:""}${C?`
|
|
111
|
+
${C.trim()}`:""}`)}function Ut(e){return`${d.bold("Linting and formatting:")}
|
|
112
|
+
${d.cyan("\u2022")} Format and lint fix: ${d.dim(`${e} check`)}
|
|
113
|
+
|
|
114
|
+
`}function Bt(e,a,t,r){let o=[];return a==="prisma"?(e==="sqlite"&&o.push(`${d.yellow("NOTE:")} Turso support with Prisma is in Early Access and requires additional setup.`,`${d.dim("Learn more at: https://www.prisma.io/docs/orm/overview/databases/turso")}`),r==="bun"&&o.push(`${d.yellow("NOTE:")} Prisma with Bun may require additional configuration. If you encounter errors, follow the guidance provided in the error messages`),o.push(`${d.cyan("\u2022")} Apply schema: ${d.dim(`${t} db:push`)}`),o.push(`${d.cyan("\u2022")} Database UI: ${d.dim(`${t} db:studio`)}`)):a==="drizzle"&&(e==="sqlite"&&o.push(`${d.cyan("\u2022")} Start local DB: ${d.dim(`cd apps/server && ${t} db:local`)}`),o.push(`${d.cyan("\u2022")} Apply schema: ${d.dim(`${t} db:push`)}`),o.push(`${d.cyan("\u2022")} Database UI: ${d.dim(`${t} db:studio`)}`)),o.length?`${d.bold("Database commands:")}
|
|
115
|
+
${o.join(`
|
|
118
116
|
`)}
|
|
119
117
|
|
|
120
|
-
`:""}function
|
|
121
|
-
${
|
|
122
|
-
${
|
|
123
|
-
${
|
|
118
|
+
`:""}function _t(e){return`${d.bold("Desktop app with Tauri:")}
|
|
119
|
+
${d.cyan("\u2022")} Start desktop app: ${d.dim(`cd apps/client && ${e} desktop:dev`)}
|
|
120
|
+
${d.cyan("\u2022")} Build desktop app: ${d.dim(`cd apps/client && ${e} desktop:build`)}
|
|
121
|
+
${d.yellow("NOTE:")} Tauri requires Rust and platform-specific dependencies. See: ${d.dim("https://v2.tauri.app/start/prerequisites/")}
|
|
124
122
|
|
|
125
|
-
`}import M from"node:path";import{$ as
|
|
123
|
+
`}import M from"node:path";import{$ as Mt,execa as Gt}from"execa";import O from"fs-extra";async function ke(e,a){await Jt(e,a),await qt(e,a)}async function Jt(e,a){let t=M.join(e,"package.json");if(await O.pathExists(t)){let r=await O.readJson(t);r.name=a.projectName;let{stdout:o}=await Gt(a.packageManager,["-v"],{cwd:e});if(r.packageManager=`${a.packageManager}@${o.trim()}`,await O.writeJson(t,r,{spaces:2}),a.packageManager==="pnpm"){let i=M.join(y,"template/with-pnpm/pnpm-workspace.yaml"),s=M.join(e,"pnpm-workspace.yaml");await O.pathExists(i)&&await O.copy(i,s)}}}async function qt(e,a){let t=M.join(e,"apps/server/package.json");if(await O.pathExists(t)){let r=await O.readJson(t);a.database!=="none"&&(a.database==="sqlite"&&(r.scripts["db:local"]="turso dev --db-file local.db"),a.orm==="prisma"?(r.scripts["db:push"]="prisma db push --schema ./prisma/schema",r.scripts["db:studio"]="prisma studio"):a.orm==="drizzle"&&(r.scripts["db:push"]="drizzle-kit push",r.scripts["db:studio"]="drizzle-kit studio")),await O.writeJson(t,r,{spaces:2})}}async function Pe(e,a){a&&await Mt({cwd:e})`git init`}import G from"node:path";import F from"fs-extra";async function je(e,a,t){let r=G.join(e,"apps/server"),o=G.join(r,"src/index.ts"),i=await F.readFile(o,"utf-8");a==="bun"?await Vt(r,o,i,t):a==="node"&&await Ht(r,o,i,t)}async function Vt(e,a,t,r){let o=G.join(e,"package.json"),i=await F.readJson(o);if(i.scripts={...i.scripts,dev:"bun run --hot src/index.ts",start:"bun run dist/src/index.js"},await F.writeJson(o,i,{spaces:2}),h({devDependencies:["@types/bun"],projectDir:e}),r==="hono"){let s=`${t}
|
|
126
124
|
|
|
127
125
|
export default app;
|
|
128
|
-
`;await
|
|
129
|
-
`,
|
|
126
|
+
`;await F.writeFile(a,s)}}async function Ht(e,a,t,r){let o=G.join(e,"package.json"),i=await F.readJson(o);if(i.scripts={...i.scripts,dev:"tsx watch src/index.ts",start:"node dist/src/index.js"},await F.writeJson(o,i,{spaces:2}),h({devDependencies:["tsx","@types/node"],projectDir:e}),r==="hono"){h({dependencies:["@hono/node-server"],projectDir:e});let s=`import { serve } from "@hono/node-server";
|
|
127
|
+
`,n=`
|
|
130
128
|
serve(
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
129
|
+
{
|
|
130
|
+
fetch: app.fetch,
|
|
131
|
+
port: 3000,
|
|
132
|
+
},
|
|
133
|
+
(info) => {
|
|
134
|
+
console.log(\`Server is running on http://localhost:\${info.port}\`);
|
|
135
|
+
},
|
|
138
136
|
);
|
|
139
|
-
`;if(t.includes("@hono/node-server")){if(!t.includes("serve(")){let n=t+i;await S.writeFile(a,n)}}else{let n=t.lastIndexOf("import"),d=t.substring(0,n),P=t.substring(n),w=d+s+P+i;await S.writeFile(a,w)}}import v from"node:path";import y from"fs-extra";async function Pe(e){let a=v.join(g,"template/base");if(!await y.pathExists(a))throw new Error(`Template directory not found: ${a}`);await y.copy(a,e)}async function ke(e,a){if(!a)return;let t=v.join(g,"template/with-auth");await y.pathExists(t)&&await y.copy(t,e,{overwrite:!0})}async function je(e,a,t,o){if(a==="none"||t==="none")return;let r=v.join(g,Jt(a,t));if(await y.pathExists(r)){await y.copy(r,e,{overwrite:!0});let s=v.join(e,"apps/server/src"),i=v.join(s,"lib"),n=v.join(s,"with-auth-lib");o?await y.pathExists(n)&&(await y.remove(i),await y.move(n,i)):await y.remove(n)}}async function ve(e){let a=[v.join(e,"_gitignore"),v.join(e,"apps/client/_gitignore"),v.join(e,"apps/server/_gitignore")];for(let t of a)if(await y.pathExists(t)){let o=v.join(v.dirname(t),".gitignore");await y.move(t,o)}}function Jt(e,a){return e==="drizzle"?a==="sqlite"?"template/with-drizzle-sqlite":"template/with-drizzle-postgres":e==="prisma"?a==="sqlite"?"template/with-prisma-sqlite":"template/with-prisma-postgres":"template/base"}async function Te(e){let a=Vt(),t=Gt.resolve(process.cwd(),e.projectName);try{return await Ht.ensureDir(t),await Pe(t),await ve(t),await ke(t,e.auth),await je(t,e.orm,e.database,e.auth),await ye(t,e.runtime),await he(t,e.examples,e.orm,e.auth),await me(t,e.database,e.orm,e.turso??e.database==="sqlite"),await ne(t,e.auth),await fe(t,e),await be(t,e.git),e.addons.length>0&&await ae(t,e.addons,e.packageManager),await we(t,e),await ce(t,e),ge(e.database,e.projectName,e.packageManager,!e.noInstall,e.orm,e.addons,e.runtime),t}catch(o){throw a.message(xe.red("Failed")),o instanceof Error&&(qt(xe.red(`Error during project creation: ${o.message}`)),process.exit(1)),o}}import{log as $e,spinner as Ee}from"@clack/prompts";import{$ as Q}from"execa";import J from"picocolors";async function Ce({projectDir:e,packageManager:a,addons:t=[]}){let o=Ee();try{switch(o.start(`Running ${a} install...`),a){case"npm":await Q({cwd:e,stderr:"inherit"})`${a} install`;break;case"pnpm":case"bun":await Q({cwd:e})`${a} install`;break}o.stop("Dependencies installed successfully"),(t.includes("biome")||t.includes("husky"))&&await Wt(e,a)}catch(r){throw o.stop(J.red("Failed to install dependencies")),r instanceof Error&&$e.error(J.red(`Installation error: ${r.message}`)),r}}async function Wt(e,a){let t=Ee();try{t.start("Running Biome format check..."),await Q({cwd:e})`${a} biome check --write .`,t.stop("Biome check completed successfully")}catch{t.stop(J.yellow("Biome check encountered issues")),$e.warn(J.yellow("Some files may need manual formatting"))}}import{cancel as _a,group as Ma}from"@clack/prompts";import Ba from"picocolors";import{cancel as Qt,isCancel as Kt,multiselect as Xt}from"@clack/prompts";import Yt from"picocolors";async function Se(e){if(e!==void 0)return e;let a=await Xt({message:"Which Addons would you like to add?",options:[{value:"pwa",label:"PWA (Progressive Web App)",hint:"Make your app installable and work offline"},{value:"tauri",label:"Tauri Desktop App",hint:"Build native desktop apps from your web frontend"},{value:"biome",label:"Biome",hint:"Add Biome for linting and formatting"},{value:"husky",label:"Husky",hint:"Add Git hooks with Husky, lint-staged (requires Biome)"}],required:!1});return Kt(a)&&(Qt(Yt.red("Operation cancelled")),process.exit(0)),a.includes("husky")&&!a.includes("biome")&&a.push("biome"),a}import{cancel as Zt,confirm as ea,isCancel as ta}from"@clack/prompts";import aa from"picocolors";async function Oe(e,a){if(!a)return!1;if(e!==void 0)return e;let t=await ea({message:"Would you like to add authentication with Better-Auth?",initialValue:u.auth});return ta(t)&&(Zt(aa.red("Operation cancelled")),process.exit(0)),t}async function Ae(e){return e!==void 0?e:"hono"}import{cancel as oa,isCancel as ra,select as sa}from"@clack/prompts";import ia from"picocolors";async function Re(e){if(e!==void 0)return e;let a=await sa({message:"Which database would you like to use?",options:[{value:"none",label:"None",hint:"No database setup"},{value:"sqlite",label:"SQLite",hint:"by Turso"},{value:"postgres",label:"PostgreSQL",hint:"Traditional relational database"}],initialValue:"sqlite"});return ra(a)&&(oa(ia.red("Operation cancelled")),process.exit(0)),a}import{cancel as na,isCancel as ca,multiselect as pa}from"@clack/prompts";import la from"picocolors";async function Ie(e,a){if(e!==void 0)return e;if(a==="none")return[];let t=await pa({message:"Which examples would you like to include?",options:[{value:"todo",label:"Todo App",hint:"A simple CRUD example app"}],required:!1,initialValues:u.examples});return ca(t)&&(na(la.red("Operation cancelled")),process.exit(0)),t}import{cancel as ua,confirm as da,isCancel as ma}from"@clack/prompts";import fa from"picocolors";async function De(e){if(e!==void 0)return e;let a=await da({message:"Initialize a new git repository?",initialValue:u.git});return ma(a)&&(ua(fa.red("Operation cancelled")),process.exit(0)),a}import{cancel as ha,confirm as ga,isCancel as wa}from"@clack/prompts";import ba from"picocolors";async function Fe(e){if(e!==void 0)return e;let a=await ga({message:"Do you want to install project dependencies?",initialValue:!u.noInstall});return wa(a)&&(ha(ba.red("Operation cancelled")),process.exit(0)),!a}import{cancel as ya,isCancel as Pa,select as ka}from"@clack/prompts";import ja from"picocolors";async function ze(e,a){if(!a)return"none";if(e!==void 0)return e;let t=await ka({message:"Which ORM would you like to use?",options:[{value:"drizzle",label:"Drizzle",hint:"Type-safe, lightweight ORM"},{value:"prisma",label:"Prisma",hint:"Powerful, feature-rich ORM with schema migrations"}],initialValue:"drizzle"});return Pa(t)&&(ya(ja.red("Operation cancelled")),process.exit(0)),t}import{cancel as va,isCancel as xa,select as Ta}from"@clack/prompts";import $a from"picocolors";var Le=()=>{let e=process.env.npm_config_user_agent;return e?.startsWith("pnpm")?"pnpm":e?.startsWith("bun")?"bun":"npm"};async function Ne(e){if(e!==void 0)return e;let a=Le(),t=await Ta({message:"Which package manager do you want to use?",options:[{value:"npm",label:"npm",hint:"Node Package Manager"},{value:"bun",label:"bun",hint:"All-in-one JavaScript runtime & toolkit"},{value:"pnpm",label:"pnpm",hint:"Fast, disk space efficient package manager"}],initialValue:a});return xa(t)&&(va($a.red("Operation cancelled")),process.exit(0)),t}import L from"node:path";import{cancel as Ea,isCancel as Ca,text as Sa}from"@clack/prompts";import R from"fs-extra";import Oa from"picocolors";var Aa=["<",">",":",'"',"|","?","*"],Ue=255;function _e(e){if(e!=="."){if(!e)return"Project name cannot be empty";if(e.length>Ue)return`Project name must be less than ${Ue} characters`;if(Aa.some(a=>e.includes(a)))return"Project name contains invalid characters";if(e.startsWith(".")||e.startsWith("-"))return"Project name cannot start with a dot or dash";if(e.toLowerCase()==="node_modules"||e.toLowerCase()==="favicon.ico")return"Project name is reserved"}}async function Me(e){if(e)if(e==="."){let s=process.cwd();if(R.readdirSync(s).length===0)return e}else{let s=L.basename(e);if(!_e(s)){let n=L.resolve(process.cwd(),e);if(!R.pathExistsSync(n)||R.readdirSync(n).length===0)return e}}let a=!1,t="",o=u.projectName,r=1;for(;R.pathExistsSync(L.resolve(process.cwd(),o));)o=`${u.projectName}-${r}`,r++;for(;!a;){let s=await Sa({message:"Enter your project name or path (relative to current directory)",placeholder:o,initialValue:e,defaultValue:o,validate:i=>{let n=i.trim()||o;if(n==="."){if(R.readdirSync(process.cwd()).length>0)return"Current directory is not empty. Please choose a different directory.";a=!0;return}let d=L.resolve(process.cwd(),n),P=L.basename(d),w=_e(P);if(w)return w;if(!d.startsWith(process.cwd()))return"Project path must be within current directory";if(R.pathExistsSync(d)&&R.readdirSync(d).length>0)return`Directory "${n}" already exists and is not empty. Please choose a different name or path.`;a=!0}});Ca(s)&&(Ea(Oa.red("Operation cancelled.")),process.exit(0)),t=s||o}return t}import{cancel as Ra,isCancel as Ia,select as Da}from"@clack/prompts";import Fa from"picocolors";async function Be(e){if(e!==void 0)return e;let a=await Da({message:"Which runtime would you like to use?",options:[{value:"bun",label:"Bun",hint:"Fast all-in-one JavaScript runtime"},{value:"node",label:"Node.js",hint:"Traditional Node.js runtime"}],initialValue:"bun"});return Ia(a)&&(Ra(Fa.red("Operation cancelled")),process.exit(0)),a}import{cancel as za,confirm as La,isCancel as Na}from"@clack/prompts";import Ua from"picocolors";async function Je(e){if(e!==void 0)return e;let a=await La({message:"Set up a Turso database for this project?",initialValue:!0});return Na(a)&&(za(Ua.red("Operation cancelled")),process.exit(0)),a}async function Ge(e){let a=await Ma({projectName:async()=>Me(e.projectName),runtime:()=>Be(e.runtime),backendFramework:()=>Ae(e.backendFramework),database:()=>Re(e.database),orm:({results:t})=>ze(e.orm,t.database!=="none"),auth:({results:t})=>Oe(e.auth,t.database!=="none"),turso:({results:t})=>t.database==="sqlite"&&t.orm!=="prisma"?Je(e.turso):Promise.resolve(!1),addons:()=>Se(e.addons),examples:({results:t})=>Ie(e.examples,t.database),git:()=>De(e.git),packageManager:()=>Ne(e.packageManager),noInstall:()=>Fe(e.noInstall)},{onCancel:()=>{_a(Ba.red("Operation cancelled")),process.exit(0)}});return{projectName:a.projectName,database:a.database,orm:a.orm,auth:a.auth,addons:a.addons,examples:a.examples,git:a.git,packageManager:a.packageManager,noInstall:a.noInstall,turso:a.turso,backendFramework:a.backendFramework,runtime:a.runtime}}import $ from"picocolors";function K(e){let a=[];return e.projectName&&a.push(`${$.blue("Project Name:")} ${e.projectName}`),e.database&&a.push(`${$.blue("Database:")} ${e.database}`),e.orm&&a.push(`${$.blue("ORM:")} ${e.orm}`),e.auth!==void 0&&a.push(`${$.blue("Authentication:")} ${e.auth}`),e.runtime&&a.push(`${$.blue("Runtime:")} ${e.runtime}`),e.addons?.length&&a.push(`${$.blue("Addons:")} ${e.addons.join(", ")}`),e.git!==void 0&&a.push(`${$.blue("Git Init:")} ${e.git}`),e.packageManager&&a.push(`${$.blue("Package Manager:")} ${e.packageManager}`),e.noInstall!==void 0&&a.push(`${$.blue("Skip Install:")} ${e.noInstall}`),e.turso!==void 0&&a.push(`${$.blue("Turso Setup:")} ${e.turso}`),a.join(`
|
|
140
|
-
|
|
137
|
+
`;if(!t.includes("@hono/node-server")){let u=t.lastIndexOf("import"),f=t.substring(0,u),b=t.substring(u),P=f+s+b+n;await F.writeFile(a,P)}}else if(r==="elysia"&&(h({dependencies:["@elysiajs/node"],projectDir:e}),!t.includes("@elysiajs/node"))){let s=`import { node } from "@elysiajs/node";
|
|
138
|
+
`,n=t.indexOf(`
|
|
139
|
+
`,t.indexOf("import")),u=t.substring(0,n+1),f=t.substring(n+1),b=u+s+f;b=b.replace(/const app = new Elysia\([^)]*\)/,"const app = new Elysia({ adapter: node() })"),await F.writeFile(a,b)}}import m from"node:path";import g from"fs-extra";async function ve(e){let a=m.join(y,"template/base");if(!await g.pathExists(a))throw new Error(`Template directory not found: ${a}`);await g.copy(a,e)}async function xe(e,a){let t=m.join(y,`template/with-${a}`);await g.pathExists(t)&&await g.copy(t,e,{overwrite:!0})}async function Te(e,a,t,r){if(a==="none"||t==="none")return;let o=m.join(y,Wt(a,t));if(await g.pathExists(o)&&(await g.copy(o,e,{overwrite:!0}),!r)){if(a==="prisma"){let i=m.join(e,"apps/server/prisma/schema/auth.prisma");await g.pathExists(i)&&await g.remove(i)}else if(a==="drizzle"){let i=m.join(e,"apps/server/src/db/schema/auth.ts");await g.pathExists(i)&&await g.remove(i)}}}async function $e(e,a,t,r,o){if(!a)return;let i=m.join(y,"template/with-auth");if(await g.pathExists(i)){let s=m.join(i,"apps/client"),n=m.join(e,"apps/client");await g.copy(s,n,{overwrite:!0});let u=m.join(i,"apps/server/src"),f=m.join(e,"apps/server/src");await g.copy(m.join(u,"lib/trpc.ts"),m.join(f,"lib/trpc.ts"),{overwrite:!0}),await g.copy(m.join(u,"routers/index.ts"),m.join(f,"routers/index.ts"),{overwrite:!0});let b=`with-${t}-context.ts`;await g.copy(m.join(u,"lib",b),m.join(f,"lib/context.ts"),{overwrite:!0});let P=`with-${t}-index.ts`;await g.copy(m.join(u,P),m.join(f,"index.ts"),{overwrite:!0});let C=Qt(r,o),D=m.join(u,C);if(await g.pathExists(D)){let et=await g.readdir(D);for(let Z of et)await g.copy(m.join(D,Z),m.join(f,"lib",Z),{overwrite:!0})}}}async function Ee(e){let a=[m.join(e,"_gitignore"),m.join(e,"apps/client/_gitignore"),m.join(e,"apps/server/_gitignore")];for(let t of a)if(await g.pathExists(t)){let r=m.join(m.dirname(t),".gitignore");await g.move(t,r)}}function Wt(e,a){return e==="drizzle"?a==="sqlite"?"template/with-drizzle-sqlite":"template/with-drizzle-postgres":e==="prisma"?a==="sqlite"?"template/with-prisma-sqlite":"template/with-prisma-postgres":"template/base"}function Qt(e,a){if(e==="drizzle")return a==="sqlite"?"with-drizzle-sqlite-lib":"with-drizzle-postgres-lib";if(e==="prisma")return a==="sqlite"?"with-prisma-sqlite-lib":"with-prisma-postgres-lib";throw new Error("Invalid ORM or database configuration for auth setup")}async function De(e){let a=Yt(),t=Kt.resolve(process.cwd(),e.projectName);try{return await Zt.ensureDir(t),await ve(t),await Ee(t),await xe(t,e.backendFramework),await le(t,e.backendFramework,e.runtime),await Te(t,e.orm,e.database,e.auth),await ge(t,e.database,e.orm,e.turso??e.database==="sqlite"),await $e(t,e.auth,e.backendFramework,e.orm,e.database),await pe(t,e.auth),await je(t,e.runtime,e.backendFramework),await be(t,e.examples,e.orm,e.auth),await we(t,e),await Pe(t,e.git),e.addons.length>0&&await oe(t,e.addons,e.packageManager),await ke(t,e),await de(t,e),ye(e.database,e.projectName,e.packageManager,!e.noInstall,e.orm,e.addons,e.runtime),t}catch(r){throw a.message(Ce.red("Failed")),r instanceof Error&&(Xt(Ce.red(`Error during project creation: ${r.message}`)),process.exit(1)),r}}import{log as Oe,spinner as Fe}from"@clack/prompts";import{$ as K}from"execa";import J from"picocolors";async function Se({projectDir:e,packageManager:a,addons:t=[]}){let r=Fe();try{switch(r.start(`Running ${a} install...`),a){case"npm":await K({cwd:e,stderr:"inherit"})`${a} install`;break;case"pnpm":case"bun":await K({cwd:e})`${a} install`;break}r.stop("Dependencies installed successfully"),(t.includes("biome")||t.includes("husky"))&&await ea(e,a)}catch(o){throw r.stop(J.red("Failed to install dependencies")),o instanceof Error&&Oe.error(J.red(`Installation error: ${o.message}`)),o}}async function ea(e,a){let t=Fe();try{t.start("Running Biome format check..."),await K({cwd:e})`${a} biome check --write .`,t.stop("Biome check completed successfully")}catch{t.stop(J.yellow("Biome check encountered issues")),Oe.warn(J.yellow("Some files may need manual formatting"))}}import{cancel as Ka,group as Xa}from"@clack/prompts";import Ya from"picocolors";import{cancel as ta,isCancel as aa,multiselect as ra}from"@clack/prompts";import oa from"picocolors";async function Ae(e){if(e!==void 0)return e;let a=await ra({message:"Which Addons would you like to add?",options:[{value:"pwa",label:"PWA (Progressive Web App)",hint:"Make your app installable and work offline"},{value:"tauri",label:"Tauri Desktop App",hint:"Build native desktop apps from your web frontend"},{value:"biome",label:"Biome",hint:"Add Biome for linting and formatting"},{value:"husky",label:"Husky",hint:"Add Git hooks with Husky, lint-staged (requires Biome)"}],initialValues:c.addons,required:!1});return aa(a)&&(ta(oa.red("Operation cancelled")),process.exit(0)),a.includes("husky")&&!a.includes("biome")&&a.push("biome"),a}import{cancel as ia,confirm as sa,isCancel as na}from"@clack/prompts";import ca from"picocolors";async function Ie(e,a){if(!a)return!1;if(e!==void 0)return e;let t=await sa({message:"Would you like to add authentication with Better-Auth?",initialValue:c.auth});return na(t)&&(ia(ca.red("Operation cancelled")),process.exit(0)),t}import{cancel as pa,isCancel as la,select as da}from"@clack/prompts";import ua from"picocolors";async function Re(e){if(e!==void 0)return e;let a=await da({message:"Which backend framework would you like to use?",options:[{value:"hono",label:"Hono",hint:"Lightweight, ultrafast web framework"},{value:"elysia",label:"Elysia",hint:"TypeScript framework with end-to-end type safety)"}],initialValue:c.backendFramework});return la(a)&&(pa(ua.red("Operation cancelled")),process.exit(0)),a}import{cancel as ma,isCancel as fa,select as ha}from"@clack/prompts";import ga from"picocolors";async function Le(e){if(e!==void 0)return e;let a=await ha({message:"Which database would you like to use?",options:[{value:"none",label:"None",hint:"No database setup"},{value:"sqlite",label:"SQLite",hint:"by Turso"},{value:"postgres",label:"PostgreSQL",hint:"Traditional relational database"}],initialValue:c.database});return fa(a)&&(ma(ga.red("Operation cancelled")),process.exit(0)),a}import{cancel as wa,isCancel as ba,multiselect as ya}from"@clack/prompts";import ka from"picocolors";async function Ne(e,a){if(e!==void 0)return e;if(a==="none")return[];let t=await ya({message:"Which examples would you like to include?",options:[{value:"todo",label:"Todo App",hint:"A simple CRUD example app"}],required:!1,initialValues:c.examples});return ba(t)&&(wa(ka.red("Operation cancelled")),process.exit(0)),t}import{cancel as Pa,confirm as ja,isCancel as va}from"@clack/prompts";import xa from"picocolors";async function ze(e){if(e!==void 0)return e;let a=await ja({message:"Initialize a new git repository?",initialValue:c.git});return va(a)&&(Pa(xa.red("Operation cancelled")),process.exit(0)),a}import{cancel as Ta,confirm as $a,isCancel as Ea}from"@clack/prompts";import Ca from"picocolors";async function Ue(e){if(e!==void 0)return e;let a=await $a({message:"Do you want to install project dependencies?",initialValue:!c.noInstall});return Ea(a)&&(Ta(Ca.red("Operation cancelled")),process.exit(0)),!a}import{cancel as Da,isCancel as Oa,select as Fa}from"@clack/prompts";import Sa from"picocolors";async function Be(e,a){if(!a)return"none";if(e!==void 0)return e;let t=await Fa({message:"Which ORM would you like to use?",options:[{value:"drizzle",label:"Drizzle",hint:"Type-safe, lightweight ORM"},{value:"prisma",label:"Prisma",hint:"Powerful, feature-rich ORM with schema migrations"}],initialValue:c.orm});return Oa(t)&&(Da(Sa.red("Operation cancelled")),process.exit(0)),t}import{cancel as Aa,isCancel as Ia,select as Ra}from"@clack/prompts";import La from"picocolors";async function _e(e){if(e!==void 0)return e;let a=z(),t=await Ra({message:"Which package manager do you want to use?",options:[{value:"npm",label:"npm",hint:"Node Package Manager"},{value:"bun",label:"bun",hint:"All-in-one JavaScript runtime & toolkit"},{value:"pnpm",label:"pnpm",hint:"Fast, disk space efficient package manager"}],initialValue:a});return Ia(t)&&(Aa(La.red("Operation cancelled")),process.exit(0)),t}import N from"node:path";import{cancel as Na,isCancel as za,text as Ua}from"@clack/prompts";import A from"fs-extra";import Ba from"picocolors";var _a=["<",">",":",'"',"|","?","*"],Me=255;function Ge(e){if(e!=="."){if(!e)return"Project name cannot be empty";if(e.length>Me)return`Project name must be less than ${Me} characters`;if(_a.some(a=>e.includes(a)))return"Project name contains invalid characters";if(e.startsWith(".")||e.startsWith("-"))return"Project name cannot start with a dot or dash";if(e.toLowerCase()==="node_modules"||e.toLowerCase()==="favicon.ico")return"Project name is reserved"}}async function Je(e){if(e)if(e==="."){let i=process.cwd();if(A.readdirSync(i).length===0)return e}else{let i=N.basename(e);if(!Ge(i)){let n=N.resolve(process.cwd(),e);if(!A.pathExistsSync(n)||A.readdirSync(n).length===0)return e}}let a=!1,t="",r=c.projectName,o=1;for(;A.pathExistsSync(N.resolve(process.cwd(),r));)r=`${c.projectName}-${o}`,o++;for(;!a;){let i=await Ua({message:"Enter your project name or path (relative to current directory)",placeholder:r,initialValue:e,defaultValue:r,validate:s=>{let n=s.trim()||r;if(n==="."){if(A.readdirSync(process.cwd()).length>0)return"Current directory is not empty. Please choose a different directory.";a=!0;return}let u=N.resolve(process.cwd(),n),f=N.basename(u),b=Ge(f);if(b)return b;if(!u.startsWith(process.cwd()))return"Project path must be within current directory";if(A.pathExistsSync(u)&&A.readdirSync(u).length>0)return`Directory "${n}" already exists and is not empty. Please choose a different name or path.`;a=!0}});za(i)&&(Na(Ba.red("Operation cancelled.")),process.exit(0)),t=i||r}return t}import{cancel as Ma,isCancel as Ga,select as Ja}from"@clack/prompts";import qa from"picocolors";async function qe(e){if(e!==void 0)return e;let a=await Ja({message:"Which runtime would you like to use?",options:[{value:"bun",label:"Bun",hint:"Fast all-in-one JavaScript runtime"},{value:"node",label:"Node.js",hint:"Traditional Node.js runtime"}],initialValue:c.runtime});return Ga(a)&&(Ma(qa.red("Operation cancelled")),process.exit(0)),a}import{cancel as Va,confirm as Ha,isCancel as Wa}from"@clack/prompts";import Qa from"picocolors";async function Ve(e){if(e!==void 0)return e;let a=await Ha({message:"Set up a Turso database for this project?",initialValue:c.turso});return Wa(a)&&(Va(Qa.red("Operation cancelled")),process.exit(0)),a}async function He(e){let a=await Xa({projectName:async()=>Je(e.projectName),backendFramework:()=>Re(e.backendFramework),runtime:()=>qe(e.runtime),database:()=>Le(e.database),orm:({results:t})=>Be(e.orm,t.database!=="none"),auth:({results:t})=>Ie(e.auth,t.database!=="none"),turso:({results:t})=>t.database==="sqlite"&&t.orm!=="prisma"?Ve(e.turso):Promise.resolve(!1),addons:()=>Ae(e.addons),examples:({results:t})=>Ne(e.examples,t.database),git:()=>ze(e.git),packageManager:()=>_e(e.packageManager),noInstall:()=>Ue(e.noInstall)},{onCancel:()=>{Ka(Ya.red("Operation cancelled")),process.exit(0)}});return{projectName:a.projectName,database:a.database,orm:a.orm,auth:a.auth,addons:a.addons,examples:a.examples,git:a.git,packageManager:a.packageManager,noInstall:a.noInstall,turso:a.turso,backendFramework:a.backendFramework,runtime:a.runtime}}import v from"picocolors";function X(e){let a=[];if(e.projectName&&a.push(`${v.blue("Project Name:")} ${e.projectName}`),e.backendFramework!==void 0&&a.push(`${v.blue("Backend Framework:")} ${e.backendFramework}`),e.runtime!==void 0&&a.push(`${v.blue("Runtime:")} ${e.runtime}`),e.database!==void 0&&a.push(`${v.blue("Database:")} ${e.database}`),e.orm!==void 0&&a.push(`${v.blue("ORM:")} ${e.orm}`),e.auth!==void 0&&a.push(`${v.blue("Authentication:")} ${e.auth}`),e.addons!==void 0){let t=e.addons.length>0?e.addons.join(", "):"none";a.push(`${v.blue("Addons:")} ${t}`)}if(e.examples!==void 0){let t=e.examples.length>0?e.examples.join(", "):"none";a.push(`${v.blue("Examples:")} ${t}`)}return e.git!==void 0&&a.push(`${v.blue("Git Init:")} ${e.git}`),e.packageManager!==void 0&&a.push(`${v.blue("Package Manager:")} ${e.packageManager}`),e.noInstall!==void 0&&a.push(`${v.blue("Skip Install:")} ${e.noInstall}`),e.turso!==void 0&&a.push(`${v.blue("Turso Setup:")} ${e.turso}`),a.join(`
|
|
140
|
+
`)}function We(e){let a=[];if(e.database==="none"?a.push("--no-database"):(a.push(`--${e.database}`),e.orm&&a.push(`--${e.orm}`),e.database==="sqlite"&&a.push(e.turso?"--turso":"--no-turso")),a.push(e.auth?"--auth":"--no-auth"),a.push(e.git?"--git":"--no-git"),a.push(e.noInstall?"--no-install":"--install"),e.packageManager&&a.push(`--${e.packageManager}`),e.backendFramework&&a.push(`--${e.backendFramework}`),e.runtime&&a.push(`--runtime ${e.runtime}`),e.addons.length>0)for(let o of e.addons)a.push(`--${o}`);else a.push("--no-addons");e.examples&&e.examples.length>0?a.push(`--examples ${e.examples.join(",")}`):a.push("--no-examples");let t="npx create-better-t-stack",r=e.projectName?` ${e.projectName}`:"";return`${t}${r} ${a.join(" ")}`}import Za from"node:path";import er from"fs-extra";var Qe=()=>{let e=Za.join(y,"package.json");return er.readJSONSync(e).version??"1.0.0"};import Ke from"gradient-string";var Xe=`
|
|
141
141
|
\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557
|
|
142
142
|
\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557
|
|
143
143
|
\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D
|
|
@@ -151,10 +151,10 @@ serve(
|
|
|
151
151
|
\u2588\u2588\u2551 \u255A\u2550\u2550\u2550\u2550\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2588\u2588\u2557
|
|
152
152
|
\u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2557
|
|
153
153
|
\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D
|
|
154
|
-
`,
|
|
155
|
-
`),t=Math.max(...a.map(
|
|
154
|
+
`,Ye={pink:"#F5C2E7",mauve:"#CBA6F7",red:"#F38BA8",maroon:"#E78284",peach:"#FAB387",yellow:"#F9E2AF",green:"#A6E3A1",teal:"#94E2D5",sky:"#89DCEB",sapphire:"#74C7EC",lavender:"#B4BEFE"},Ze=()=>{let e=process.stdout.columns||80,a=Xe.split(`
|
|
155
|
+
`),t=Math.max(...a.map(r=>r.length));e<t?console.log(Ke(Object.values(Ye)).multiline(`
|
|
156
156
|
\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
|
|
157
157
|
\u2551 Better T-Stack \u2551
|
|
158
158
|
\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D
|
|
159
|
-
`)):console.log(
|
|
160
|
-
${E.white(
|
|
159
|
+
`)):console.log(Ke(Object.values(Ye)).multiline(Xe))};process.on("SIGINT",()=>{$.error(E.red("Operation cancelled")),process.exit(0)});var Y=new ir;async function sr(){let e=Date.now();Y.name("create-better-t-stack").description("Create a new Better-T Stack project").version(Qe()).argument("[project-directory]","Project name/directory").option("-y, --yes","Use default configuration").option("--no-database","Skip database setup").option("--sqlite","Use SQLite database").option("--postgres","Use PostgreSQL database").option("--auth","Include authentication").option("--no-auth","Exclude authentication").option("--pwa","Include Progressive Web App support").option("--tauri","Include Tauri desktop app support").option("--biome","Include Biome for linting and formatting").option("--husky","Include Husky, lint-staged for Git hooks").option("--no-addons","Skip all additional addons").option("--examples <examples>","Include specified examples").option("--no-examples","Skip all examples").option("--git","Include git setup").option("--no-git","Skip git initialization").option("--npm","Use npm package manager").option("--pnpm","Use pnpm package manager").option("--bun","Use bun package manager").option("--drizzle","Use Drizzle ORM").option("--prisma","Use Prisma ORM (coming soon)").option("--install","Install dependencies").option("--no-install","Skip installing dependencies").option("--turso","Set up Turso for SQLite database").option("--no-turso","Skip Turso setup for SQLite database").option("--hono","Use Hono backend framework").option("--elysia","Use Elysia backend framework").option("--runtime <runtime>","Specify runtime (bun or node)").parse();let a=or();try{Ze(),ar(E.magenta("Creating a new Better-T-Stack project"));let t=Y.opts(),r=Y.args[0],o;t.hono&&(o="hono"),t.elysia&&(o="elysia");let i={...r&&{projectName:r},...t.database===!1&&{database:"none"},...t.sqlite&&{database:"sqlite"},...t.postgres&&{database:"postgres"},...t.drizzle&&{orm:"drizzle"},...t.prisma&&{orm:"prisma"},..."auth"in t&&{auth:t.auth},...t.npm&&{packageManager:"npm"},...t.pnpm&&{packageManager:"pnpm"},...t.bun&&{packageManager:"bun"},..."git"in t&&{git:t.git},..."install"in t&&{noInstall:!t.install},..."turso"in t&&{turso:t.turso},...o&&{backendFramework:o},...t.runtime&&{runtime:t.runtime},...(t.pwa||t.tauri||t.biome||t.husky||t.addons===!1)&&{addons:t.addons===!1?[]:[...t.pwa?["pwa"]:[],...t.tauri?["tauri"]:[],...t.biome?["biome"]:[],...t.husky?["husky"]:[]]},...(t.examples||t.examples===!1)&&{examples:t.examples===!1?[]:typeof t.examples=="string"?t.examples.split(",").filter(f=>f==="todo"):[]}};!t.yes&&Object.keys(i).length>0&&($.info(E.yellow("Using these pre-selected options:")),$.message(X(i)),$.message(""));let s=t.yes?{...c,projectName:r??c.projectName,database:t.database===!1?"none":t.sqlite?"sqlite":t.postgres?"postgres":c.database,orm:t.database===!1?"none":t.drizzle?"drizzle":t.prisma?"prisma":c.orm,auth:"auth"in t?t.auth:c.auth,git:"git"in t?t.git:c.git,noInstall:"install"in t?!t.install:c.noInstall,packageManager:i.packageManager??c.packageManager,addons:i.addons?.length?i.addons:c.addons,examples:i.examples?.length?i.examples:c.examples,turso:"turso"in t?t.turso:i.database==="sqlite"?c.turso:!1,backendFramework:o??c.backendFramework,runtime:t.runtime?t.runtime:c.runtime}:await He(i);t.yes&&($.info(E.yellow("Using these default options:")),$.message(X(s)),$.message(""));let n=await De(s);s.noInstall||await Se({projectDir:n,packageManager:s.packageManager,addons:s.addons}),$.success(E.blue(`You can reproduce this setup with the following command:
|
|
160
|
+
${E.white(We(s))}`));let u=((Date.now()-e)/1e3).toFixed(2);rr(E.magenta(`Project created successfully in ${E.bold(u)} seconds!`))}catch(t){a.stop(E.red("Failed")),t instanceof Error&&(tr(E.red(`An unexpected error occurred: ${t.message}`)),process.exit(1))}}sr().catch(e=>{$.error("Aborting installation..."),e instanceof Error?$.error(e.message):($.error("An unknown error has occurred. Please open an issue on GitHub with the below:"),console.log(e)),process.exit(1)});
|
package/package.json
CHANGED
|
@@ -8,10 +8,8 @@
|
|
|
8
8
|
"compile": "bun build --compile --minify --sourcemap --bytecode ./src/index.ts --outfile server"
|
|
9
9
|
},
|
|
10
10
|
"dependencies": {
|
|
11
|
-
"@hono/trpc-server": "^0.3.4",
|
|
12
11
|
"@trpc/server": "^11.0.0",
|
|
13
12
|
"dotenv": "^16.4.7",
|
|
14
|
-
"hono": "^4.7.5",
|
|
15
13
|
"zod": "^3.24.2"
|
|
16
14
|
},
|
|
17
15
|
"devDependencies": {
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import type { Context as
|
|
1
|
+
import type { Context as ElysiaContext } from "elysia";
|
|
2
2
|
import { auth } from "./auth";
|
|
3
3
|
|
|
4
4
|
export type CreateContextOptions = {
|
|
5
|
-
|
|
5
|
+
context: ElysiaContext;
|
|
6
6
|
};
|
|
7
7
|
|
|
8
|
-
export async function createContext({
|
|
8
|
+
export async function createContext({ context }: CreateContextOptions) {
|
|
9
9
|
const session = await auth.api.getSession({
|
|
10
|
-
headers:
|
|
10
|
+
headers: context.request.headers,
|
|
11
11
|
});
|
|
12
12
|
|
|
13
13
|
return {
|
|
@@ -2,12 +2,12 @@ import type { Context as HonoContext } from "hono";
|
|
|
2
2
|
import { auth } from "./auth";
|
|
3
3
|
|
|
4
4
|
export type CreateContextOptions = {
|
|
5
|
-
|
|
5
|
+
context: HonoContext;
|
|
6
6
|
};
|
|
7
7
|
|
|
8
|
-
export async function createContext({
|
|
8
|
+
export async function createContext({ context }: CreateContextOptions) {
|
|
9
9
|
const session = await auth.api.getSession({
|
|
10
|
-
headers:
|
|
10
|
+
headers: context.req.raw.headers,
|
|
11
11
|
});
|
|
12
12
|
|
|
13
13
|
return {
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import "dotenv/config";
|
|
2
|
+
import { Elysia } from "elysia";
|
|
3
|
+
import { cors } from "@elysiajs/cors";
|
|
4
|
+
import { auth } from "./lib/auth";
|
|
5
|
+
import { createContext } from "./lib/context";
|
|
6
|
+
import { appRouter } from "./routers/index";
|
|
7
|
+
import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
|
|
8
|
+
|
|
9
|
+
const app = new Elysia()
|
|
10
|
+
.use(
|
|
11
|
+
cors({
|
|
12
|
+
origin: process.env.CORS_ORIGIN || "",
|
|
13
|
+
methods: ["GET", "POST", "OPTIONS"],
|
|
14
|
+
allowedHeaders: ["Content-Type", "Authorization"],
|
|
15
|
+
credentials: true,
|
|
16
|
+
}),
|
|
17
|
+
)
|
|
18
|
+
.all("/api/auth/*", async (context) => {
|
|
19
|
+
const { request } = context;
|
|
20
|
+
if (["POST", "GET"].includes(request.method)) {
|
|
21
|
+
return auth.handler(request);
|
|
22
|
+
} else {
|
|
23
|
+
context.error(405);
|
|
24
|
+
}
|
|
25
|
+
})
|
|
26
|
+
.all("/trpc/*", async (context) => {
|
|
27
|
+
const res = await fetchRequestHandler({
|
|
28
|
+
endpoint: "/trpc",
|
|
29
|
+
router: appRouter,
|
|
30
|
+
req: context.request,
|
|
31
|
+
createContext: () => createContext({ context }),
|
|
32
|
+
});
|
|
33
|
+
return res;
|
|
34
|
+
})
|
|
35
|
+
.get("/", () => "OK")
|
|
36
|
+
.listen(3000, () => {
|
|
37
|
+
console.log(`Server is running on http://localhost:3000`);
|
|
38
|
+
});
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
|
|
1
2
|
import { trpcServer } from "@hono/trpc-server";
|
|
2
3
|
import "dotenv/config";
|
|
3
4
|
import { Hono } from "hono";
|
|
@@ -27,8 +28,8 @@ app.use(
|
|
|
27
28
|
"/trpc/*",
|
|
28
29
|
trpcServer({
|
|
29
30
|
router: appRouter,
|
|
30
|
-
createContext: (_opts,
|
|
31
|
-
return createContext({
|
|
31
|
+
createContext: (_opts, context) => {
|
|
32
|
+
return createContext({ context });
|
|
32
33
|
},
|
|
33
34
|
}),
|
|
34
35
|
);
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import "dotenv/config";
|
|
2
|
+
import { Elysia } from "elysia";
|
|
3
|
+
import { cors } from "@elysiajs/cors";
|
|
4
|
+
import { createContext } from "./lib/context";
|
|
5
|
+
import { appRouter } from "./routers/index";
|
|
6
|
+
import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
|
|
7
|
+
|
|
8
|
+
const app = new Elysia()
|
|
9
|
+
.use(
|
|
10
|
+
cors({
|
|
11
|
+
origin: process.env.CORS_ORIGIN || "",
|
|
12
|
+
methods: ["GET", "POST", "OPTIONS"],
|
|
13
|
+
}),
|
|
14
|
+
)
|
|
15
|
+
.all("/trpc/*", async (context) => {
|
|
16
|
+
const res = await fetchRequestHandler({
|
|
17
|
+
endpoint: "/trpc",
|
|
18
|
+
router: appRouter,
|
|
19
|
+
req: context.request,
|
|
20
|
+
createContext: () => createContext({ context }),
|
|
21
|
+
});
|
|
22
|
+
return res;
|
|
23
|
+
})
|
|
24
|
+
.get("/", () => "OK")
|
|
25
|
+
.listen(3000, () => {
|
|
26
|
+
console.log(`Server is running on http://localhost:3000`);
|
|
27
|
+
});
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Context as ElysiaContext } from "elysia";
|
|
2
|
+
|
|
3
|
+
export type CreateContextOptions = {
|
|
4
|
+
context: ElysiaContext;
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
export async function createContext({ context }: CreateContextOptions) {
|
|
8
|
+
return {
|
|
9
|
+
session: null,
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export type Context = Awaited<ReturnType<typeof createContext>>;
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import type { Context as HonoContext } from "hono";
|
|
2
2
|
|
|
3
3
|
export type CreateContextOptions = {
|
|
4
|
-
|
|
4
|
+
context: HonoContext;
|
|
5
5
|
};
|
|
6
6
|
|
|
7
|
-
export async function createContext({
|
|
7
|
+
export async function createContext({ context }: CreateContextOptions) {
|
|
8
8
|
return {
|
|
9
9
|
session: null,
|
|
10
10
|
};
|
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
import { z } from "zod";
|
|
2
|
-
import { router, publicProcedure } from "../lib/trpc";
|
|
3
|
-
import { todo } from "../db/schema";
|
|
4
|
-
import { eq } from "drizzle-orm";
|
|
5
|
-
import { db } from "../db";
|
|
6
|
-
|
|
7
|
-
export const todoRouter = router({
|
|
8
|
-
getAll: publicProcedure.query(async () => {
|
|
9
|
-
return await db.select().from(todo).all();
|
|
10
|
-
}),
|
|
11
|
-
|
|
12
|
-
create: publicProcedure
|
|
13
|
-
.input(z.object({ text: z.string().min(1) }))
|
|
14
|
-
.mutation(async ({ input }) => {
|
|
15
|
-
return await db
|
|
16
|
-
.insert(todo)
|
|
17
|
-
.values({
|
|
18
|
-
text: input.text,
|
|
19
|
-
})
|
|
20
|
-
.returning()
|
|
21
|
-
.get();
|
|
22
|
-
}),
|
|
23
|
-
|
|
24
|
-
toggle: publicProcedure
|
|
25
|
-
.input(z.object({ id: z.number(), completed: z.boolean() }))
|
|
26
|
-
.mutation(async ({ input }) => {
|
|
27
|
-
return await db
|
|
28
|
-
.update(todo)
|
|
29
|
-
.set({ completed: input.completed })
|
|
30
|
-
.where(eq(todo.id, input.id))
|
|
31
|
-
.returning()
|
|
32
|
-
.get();
|
|
33
|
-
}),
|
|
34
|
-
|
|
35
|
-
delete: publicProcedure
|
|
36
|
-
.input(z.object({ id: z.number() }))
|
|
37
|
-
.mutation(async ({ input }) => {
|
|
38
|
-
return await db
|
|
39
|
-
.delete(todo)
|
|
40
|
-
.where(eq(todo.id, input.id))
|
|
41
|
-
.returning()
|
|
42
|
-
.get();
|
|
43
|
-
}),
|
|
44
|
-
});
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import type { Context as HonoContext } from "hono";
|
|
2
|
-
import { auth } from "./auth";
|
|
3
|
-
|
|
4
|
-
export type CreateContextOptions = {
|
|
5
|
-
hono: HonoContext;
|
|
6
|
-
};
|
|
7
|
-
|
|
8
|
-
export async function createContext({ hono }: CreateContextOptions) {
|
|
9
|
-
const session = await auth.api.getSession({
|
|
10
|
-
headers: hono.req.raw.headers,
|
|
11
|
-
});
|
|
12
|
-
|
|
13
|
-
return {
|
|
14
|
-
session,
|
|
15
|
-
};
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export type Context = Awaited<ReturnType<typeof createContext>>;
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import { initTRPC, TRPCError } from "@trpc/server";
|
|
2
|
-
import type { Context } from "./context";
|
|
3
|
-
|
|
4
|
-
export const t = initTRPC.context<Context>().create();
|
|
5
|
-
|
|
6
|
-
export const router = t.router;
|
|
7
|
-
|
|
8
|
-
export const publicProcedure = t.procedure;
|
|
9
|
-
|
|
10
|
-
export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
|
|
11
|
-
if (!ctx.session) {
|
|
12
|
-
throw new TRPCError({
|
|
13
|
-
code: "UNAUTHORIZED",
|
|
14
|
-
message: "Authentication required",
|
|
15
|
-
cause: "No session",
|
|
16
|
-
});
|
|
17
|
-
}
|
|
18
|
-
return next({
|
|
19
|
-
ctx: {
|
|
20
|
-
...ctx,
|
|
21
|
-
session: ctx.session,
|
|
22
|
-
},
|
|
23
|
-
});
|
|
24
|
-
});
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import { initTRPC, TRPCError } from "@trpc/server";
|
|
2
|
-
import type { Context } from "./context";
|
|
3
|
-
|
|
4
|
-
export const t = initTRPC.context<Context>().create();
|
|
5
|
-
|
|
6
|
-
export const router = t.router;
|
|
7
|
-
|
|
8
|
-
export const publicProcedure = t.procedure;
|
|
9
|
-
|
|
10
|
-
export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
|
|
11
|
-
if (!ctx.session) {
|
|
12
|
-
throw new TRPCError({
|
|
13
|
-
code: "UNAUTHORIZED",
|
|
14
|
-
message: "Authentication required",
|
|
15
|
-
cause: "No session",
|
|
16
|
-
});
|
|
17
|
-
}
|
|
18
|
-
return next({
|
|
19
|
-
ctx: {
|
|
20
|
-
...ctx,
|
|
21
|
-
session: ctx.session,
|
|
22
|
-
},
|
|
23
|
-
});
|
|
24
|
-
});
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import type { Context as HonoContext } from "hono";
|
|
2
|
-
import { auth } from "./auth";
|
|
3
|
-
|
|
4
|
-
export type CreateContextOptions = {
|
|
5
|
-
hono: HonoContext;
|
|
6
|
-
};
|
|
7
|
-
|
|
8
|
-
export async function createContext({ hono }: CreateContextOptions) {
|
|
9
|
-
const session = await auth.api.getSession({
|
|
10
|
-
headers: hono.req.raw.headers,
|
|
11
|
-
});
|
|
12
|
-
|
|
13
|
-
return {
|
|
14
|
-
session,
|
|
15
|
-
};
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export type Context = Awaited<ReturnType<typeof createContext>>;
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import { initTRPC, TRPCError } from "@trpc/server";
|
|
2
|
-
import type { Context } from "./context";
|
|
3
|
-
|
|
4
|
-
export const t = initTRPC.context<Context>().create();
|
|
5
|
-
|
|
6
|
-
export const router = t.router;
|
|
7
|
-
|
|
8
|
-
export const publicProcedure = t.procedure;
|
|
9
|
-
|
|
10
|
-
export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
|
|
11
|
-
if (!ctx.session) {
|
|
12
|
-
throw new TRPCError({
|
|
13
|
-
code: "UNAUTHORIZED",
|
|
14
|
-
message: "Authentication required",
|
|
15
|
-
cause: "No session",
|
|
16
|
-
});
|
|
17
|
-
}
|
|
18
|
-
return next({
|
|
19
|
-
ctx: {
|
|
20
|
-
...ctx,
|
|
21
|
-
session: ctx.session,
|
|
22
|
-
},
|
|
23
|
-
});
|
|
24
|
-
});
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import { initTRPC, TRPCError } from "@trpc/server";
|
|
2
|
-
import type { Context } from "./context";
|
|
3
|
-
|
|
4
|
-
export const t = initTRPC.context<Context>().create();
|
|
5
|
-
|
|
6
|
-
export const router = t.router;
|
|
7
|
-
|
|
8
|
-
export const publicProcedure = t.procedure;
|
|
9
|
-
|
|
10
|
-
export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
|
|
11
|
-
if (!ctx.session) {
|
|
12
|
-
throw new TRPCError({
|
|
13
|
-
code: "UNAUTHORIZED",
|
|
14
|
-
message: "Authentication required",
|
|
15
|
-
cause: "No session",
|
|
16
|
-
});
|
|
17
|
-
}
|
|
18
|
-
return next({
|
|
19
|
-
ctx: {
|
|
20
|
-
...ctx,
|
|
21
|
-
session: ctx.session,
|
|
22
|
-
},
|
|
23
|
-
});
|
|
24
|
-
});
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { betterAuth } from "better-auth";
|
|
2
2
|
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
|
3
|
-
import * as schema from "../db/schema/auth";
|
|
4
3
|
import { db } from "../db";
|
|
4
|
+
import * as schema from "../db/schema/auth";
|
|
5
5
|
|
|
6
6
|
export const auth = betterAuth({
|
|
7
7
|
database: drizzleAdapter(db, {
|
|
File without changes
|
|
File without changes
|