create-lx2-app 0.11.0 → 0.11.1-beta.718fd8b
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 +27 -25
- package/package.json +99 -91
- package/template/packages/src/app/api/trpc/[trpc]/route.ts +34 -0
- package/template/packages/src/app/layout/with-trpc.tsx +37 -0
- package/template/packages/src/app/page/with-trpc.tsx +113 -0
- package/template/packages/src/components/greeting.tsx +21 -0
- package/template/packages/src/env/with-trpc.js +44 -0
- package/template/packages/src/lib/api/client.tsx +85 -0
- package/template/packages/src/lib/api/query-client.ts +22 -0
- package/template/packages/src/lib/api/server.ts +31 -0
- package/template/packages/src/lib/utils.ts +7 -0
- package/template/packages/src/server/api/init/base.ts +103 -0
- package/template/packages/src/server/api/root.ts +23 -0
- package/template/packages/src/server/api/routers/hello-world/base.ts +15 -0
- package/LICENSE.md +0 -20
package/dist/index.js
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
2
|
+
import ut from"path";import{execa as Vt}from"execa";import ft from"fs-extra";import ke from"path";import{fileURLToPath as gt}from"url";var ht=gt(import.meta.url),yt=ke.dirname(ht),m=ke.join(yt,"../"),xe=` ___ ___ ___ _ _____ ___ _ ___ _ ___ ___
|
|
3
3
|
/ __| _ \\ __| /_\\_ _| __| | | __ __|_ ) /_\\ | _ \\ _ \\
|
|
4
4
|
| (__| / _| / _ \\| | | _| | |__\\ \\ / / / / _ \\| _/ _/
|
|
5
5
|
\\___|_|_\\___/_/ \\_\\_| |___| |____/_\\_\\/___| /_/ \\_\\_| |_|
|
|
6
|
-
`,
|
|
6
|
+
`,M="my-lx2-app",ne="create-lx2-app",N=[{packages:["payload"],message:"Our Payload CMS integration does not yet support other packages."},{packages:["trpc","payload","authjs","betterAuth","prisma","drizzle"]}];import{confirm as K,input as Ne,select as R}from"@inquirer/prompts";import{Command as Ct}from"commander";var v=()=>{let e=process.env.npm_config_user_agent;return e?e.startsWith("yarn")?"yarn":e.startsWith("pnpm")?"pnpm":e.startsWith("bun")?"bun":"npm":"npm"};import j from"path";import re from"fs-extra";var Pe={"next-auth":"^5.0.0-beta.25","@auth/prisma-adapter":"^2.11.1","@auth/drizzle-adapter":"^1.11.1","better-auth":"^1.4.1","better-sqlite3":"^12.4.6","@types/better-sqlite3":"^7.6.13",prisma:"^7.0.0","@prisma/client":"^7.0.0","drizzle-orm":"^0.44.7","drizzle-kit":"^0.31.7","@libsql/client":"^0.15.15",mysql2:"^3.15.3",postgres:"^3.4.7","@trpc/server":"^11.7.2","@trpc/client":"^11.7.2","@trpc/react-query":"^11.7.2","@tanstack/react-query":"^5.90.10","server-only":"^0.0.1",superjson:"^2.2.5","@t3-oss/env-nextjs":"^0.13.8",zod:"^4.1.13",prettier:"^3.6.2","prettier-plugin-tailwindcss":"^0.7.1","@ianvs/prettier-plugin-sort-imports":"^4.7.0",eslint:"^9.39.1","eslint-config-next":"^16.0.4","@eslint/eslintrc":"^3.3.1","@biomejs/biome":"^2.3.7",typescript:"^5.9.3","@types/node":"^24.9.2","@types/react":"^19.2.2","@types/react-dom":"^19.2.2",payload:"^3.64.0","@payloadcms/next":"^3.64.0","@payloadcms/payload-cloud":"^3.64.0","@payloadcms/richtext-lexical":"^3.64.0","@payloadcms/db-vercel-postgres":"^3.64.0","@payloadcms/db-sqlite":"^3.64.0",graphql:"^16.12.0",sharp:"^0.34.5"};import Se from"path";import _e from"fs-extra";import bt from"sort-package-json";var f=e=>{let{dependencies:t,devMode:a,projectDir:i}=e,s=_e.readJsonSync(Se.join(i,"package.json"));t.forEach(r=>{let o=Pe[r];a&&s.devDependencies?s.devDependencies[r]=o:s.dependencies&&(s.dependencies[r]=o)});let n=bt(s);_e.writeJsonSync(Se.join(i,"package.json"),n,{spaces:2})};var je=({projectDir:e,packages:t})=>{let a=t?.prisma.inUse,i=t?.drizzle.inUse,s=["next-auth"];a&&s.push("@auth/prisma-adapter"),i&&s.push("@auth/drizzle-adapter"),f({projectDir:e,dependencies:s,devMode:!1});let n=j.join(m,"template/packages"),r="src/app/api/auth/[...nextauth]/route.ts",o=j.join(n,r),c=j.join(e,r),p=j.join(n,"src/server/auth/config",a?"authjs-with-prisma.ts":i?"authjs-with-drizzle.ts":"authjs.ts"),d=j.join(e,"src/server/auth/config.ts"),u=j.join(n,"src/server/auth/authjs.ts"),y=j.join(e,"src/server/auth/index.ts");re.copySync(o,c),re.copySync(p,d),re.copySync(u,y)};import S from"path";import q from"fs-extra";import vt from"path";import Ae from"fs-extra";import{sortPackageJson as wt}from"sort-package-json";function w(e){let{scripts:t,projectDir:a}=e,i=vt.join(a,"package.json"),s=Ae.readJSONSync(i);s.scripts={...s.scripts,...t};let n=wt(s);Ae.writeJSONSync(i,n,{spaces:2})}var Ie=({projectDir:e,packages:t,databaseProvider:a})=>{let i=t?.prisma.inUse,s=t?.drizzle.inUse,n=["better-auth"],r=[];(!i||!s)&&n.push("better-sqlite3"),(!i||!s)&&r.push("@types/better-sqlite3"),f({projectDir:e,dependencies:n,devMode:!1}),f({projectDir:e,dependencies:r,devMode:!0});let o=S.join(m,"template/packages"),c=S.join(o,"src/app/api/auth/[...betterauth]/route.ts"),p=S.join(e,"src/app/api/auth/[...all]/route.ts"),d=S.join(o,"src/server/auth",i?"better-auth-with-prisma.ts":s?"better-auth-with-drizzle.ts":"better-auth.ts"),u=q.readFileSync(d,"utf-8");(i||s)&&a!=="sqlite"&&(u=u.replace('provider: "sqlite",',`provider: "${{mysql:"mysql",postgresql:s?"pg":"postgresql"}[a]}",`));let y=S.join(e,"src/server/auth/index.ts");q.mkdirSync(S.dirname(y),{recursive:!0}),q.writeFileSync(y,u);let x=S.join(o,"src/lib/auth/better-auth-client.ts"),b=S.join(e,"src/lib/auth/client.ts");w({projectDir:e,scripts:{"auth:generate":"npx @better-auth/cli@latest generate --config ./src/server/auth/index.ts --yes",...!i&&!s&&{"auth:migrate":"npx @better-auth/cli@latest migrate --config ./src/server/auth/index.ts --yes"}}}),q.copySync(c,p),q.copySync(x,b)};import oe from"path";import kt from"fs-extra";var Ce=({projectDir:e})=>{f({projectDir:e,dependencies:["@biomejs/biome"],devMode:!0});let t=oe.join(m,"template/packages"),a=oe.join(t,"config/biome.jsonc"),i=oe.join(e,"biome.jsonc");kt.copyFileSync(a,i),w({projectDir:e,scripts:{"lint:unsafe":"biome check --write --unsafe .","lint:write":"biome check --write .",lint:"biome check .",format:"biome format --write ."}})};import _ from"path";import A from"fs-extra";var ze=({projectDir:e,packages:t,scopedAppName:a,databaseProvider:i})=>{let s=t?.authjs.inUse,n=t?.betterAuth.inUse;f({projectDir:e,dependencies:["drizzle-kit"],devMode:!0}),f({projectDir:e,dependencies:["drizzle-orm",{sqlite:"@libsql/client",mysql:"mysql2",postgresql:"postgres"}[i]],devMode:!1});let r=_.join(m,"template/packages"),o=_.join(r,"config/drizzle",{sqlite:"with-sqlite",mysql:"with-mysql",postgresql:"with-postgresql"}[i]+".ts"),c=_.join(e,"drizzle.config.ts"),p=_.join(r,"src/server/db/schema-drizzle",s?`with-authjs-${i}.ts`:n?`with-better-auth-${i}.ts`:`base-${i}.ts`),d=_.join(e,"src/server/db/schema.ts"),u=A.readFileSync(p,"utf-8");u=u.replace("project1_${name}",`${a}_\${name}`);let y=A.readFileSync(o,"utf-8");y=y.replace("project1_*",`${a}_*`);let x=_.join(r,`src/server/db/index-drizzle/with-${i}.ts`),b=_.join(e,"src/server/db/index.ts");w({projectDir:e,scripts:{"db:generate":"drizzle-kit generate","db:migrate":"drizzle-kit migrate","db:push":"drizzle-kit push","db:studio":"drizzle-kit studio"}}),A.copySync(o,c),A.mkdirSync(_.dirname(d),{recursive:!0}),A.writeFileSync(d,u),A.writeFileSync(c,y),A.copySync(x,b)};import G from"path";import le from"fs-extra";var Te=({projectDir:e,scopedAppName:t,packages:a,databaseProvider:i})=>{let s=a?.envVariables.inUse,n=a?.authjs.inUse,r=a?.betterAuth.inUse,o=a?.trpc.inUse,c=a?.prisma.inUse,p=a?.drizzle.inUse,d=a?.payload.inUse,u=[];s&&(u.push("@t3-oss/env-nextjs"),u.push("zod")),f({projectDir:e,dependencies:u,devMode:!1});let y=c||p||d,x=xt(!!n,!!r,!!o,!!c,!!p,!!d,t,i),b="";if(y?n?b="with-authjs-db.js":r?b="with-better-auth-db.js":d?b="with-payload.js":b="with-db.js":o?b="with-trpc.js":n?b="with-authjs.js":r&&(b="with-better-auth.js"),b!==""){let te=G.join(m,"template/packages/src/env",b),se=G.join(e,"src/env.ts");le.copyFileSync(te,se)}let X=G.join(e,".env"),Q=G.join(e,".env.example"),Z=Pt+x,O=Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64"),ee=x.replace('AUTH_SECRET=""',`AUTH_SECRET="${O}" # Generated by create-lx2-app`).replace('BETTER_AUTH_SECRET=""',`BETTER_AUTH_SECRET="${O}" # Generated by create-lx2-app`).replace('PAYLOAD_SECRET=""',`PAYLOAD_SECRET="${O}" # Generated by create-lx2-app`);le.writeFileSync(X,ee,"utf-8"),le.writeFileSync(Q,Z,"utf-8")};function xt(e,t,a,i,s,n,r,o){let c=`
|
|
7
7
|
# When adding additional environment variables, the schema in "/src/env.ts"
|
|
8
8
|
# should be updated accordingly.
|
|
9
9
|
`.trim().concat(`
|
|
10
|
-
`);return
|
|
10
|
+
`);return i&&(c+=`
|
|
11
11
|
# Prisma
|
|
12
12
|
# https://www.prisma.io/docs/reference/database-reference/connection-urls#env
|
|
13
|
-
`),
|
|
13
|
+
`),s&&(c+=`
|
|
14
14
|
# Drizzle ORM
|
|
15
15
|
# https://orm.drizzle.team/docs/connect-overview
|
|
16
|
-
`),(
|
|
17
|
-
`),
|
|
16
|
+
`),(i||s)&&(o==="mysql"?c+=`DATABASE_URL="mysql://root:password@localhost:3306/${r}"`:o==="postgresql"?c+=`DATABASE_URL="postgresql://postgres:password@localhost:5432/${r}"`:o==="sqlite"&&(c+='DATABASE_URL="file:./db.sqlite"'),c+=`
|
|
17
|
+
`),n&&(c+=`
|
|
18
18
|
# Payload CMS
|
|
19
19
|
# https://payloadcms.com/docs/database/overview
|
|
20
|
-
`,
|
|
21
|
-
`,o==="postgresql"?
|
|
22
|
-
`),e&&(
|
|
20
|
+
`,c+=`PAYLOAD_SECRET=""
|
|
21
|
+
`,o==="postgresql"?c+=`DATABASE_URL="postgresql://postgres:password@localhost:5432/${r}"`:o==="sqlite"&&(c+='DATABASE_URL="file:./db.sqlite"'),c+=`
|
|
22
|
+
`),e&&(c+=`
|
|
23
23
|
# Next Auth
|
|
24
24
|
# You can generate a new secret on the command line with:
|
|
25
25
|
# npx auth secret
|
|
@@ -29,7 +29,7 @@ AUTH_SECRET=""
|
|
|
29
29
|
# Next Auth Discord Provider
|
|
30
30
|
DISCORD_CLIENT_ID=""
|
|
31
31
|
DISCORD_CLIENT_SECRET=""
|
|
32
|
-
`),
|
|
32
|
+
`),t&&(c+=`
|
|
33
33
|
# Better Auth
|
|
34
34
|
# You can generate a new secret by going to the Better Auth docs:
|
|
35
35
|
# https://www.better-auth.com/docs/installation#set-environment-variables
|
|
@@ -39,11 +39,13 @@ NEXT_PUBLIC_BETTER_AUTH_URL="http://localhost:3000" # Base URL of your app
|
|
|
39
39
|
# Better Auth Discord Provider
|
|
40
40
|
DISCORD_CLIENT_ID=""
|
|
41
41
|
DISCORD_CLIENT_SECRET=""
|
|
42
|
-
`),!e&&!
|
|
42
|
+
`),!e&&!i&&!n&&(c+=`
|
|
43
43
|
# Example:
|
|
44
44
|
# SERVERVAR="foo"
|
|
45
45
|
# NEXT_PUBLIC_CLIENTVAR="bar"
|
|
46
|
-
`),
|
|
46
|
+
`),a&&(c+=`
|
|
47
|
+
NEXT_PUBLIC_URL="http://localhost:3000"
|
|
48
|
+
`),c}var Pt=`
|
|
47
49
|
# Since the ".env" file is gitignored, you can use the ".env.example" file to
|
|
48
50
|
# build a new ".env" file when you clone the repo. Keep this file up-to-date
|
|
49
51
|
# when you add new variables to \`.env\`.
|
|
@@ -53,19 +55,19 @@ DISCORD_CLIENT_SECRET=""
|
|
|
53
55
|
# ".env" and populate it with your secrets.
|
|
54
56
|
`.trim().concat(`
|
|
55
57
|
|
|
56
|
-
`);import
|
|
58
|
+
`);import W from"path";import De from"fs-extra";var Re=({projectDir:e,packages:t})=>{let a=t?.["eslint/prettier"].inUse,i=[];a&&(i.push("eslint"),i.push("eslint-config-next"),i.push("@eslint/eslintrc"),i.push("prettier"),i.push("prettier-plugin-tailwindcss"),i.push("@ianvs/prettier-plugin-sort-imports")),f({projectDir:e,dependencies:i,devMode:!0});let s=W.join(m,"template/packages/config","eslint.config.mjs"),n=W.join(m,"template/packages/config","prettier.config.mjs"),r=W.join(e,"eslint.config.mjs"),o=W.join(e,"prettier.config.mjs");w({projectDir:e,scripts:{"lint:write":"eslint --fix",lint:"eslint",format:"prettier --write ."}}),De.copyFileSync(s,r),De.copyFileSync(n,o)};import k from"path";import z from"fs-extra";var Oe=({projectDir:e,packages:t,databaseProvider:a})=>{let i=[],s=[];if(t?.payload.inUse)switch(i.push("payload"),i.push("@payloadcms/next"),i.push("@payloadcms/payload-cloud"),i.push("@payloadcms/richtext-lexical"),i.push("graphql"),a){case"sqlite":s.push("@payloadcms/db-sqlite");break;case"postgresql":s.push("@payloadcms/db-vercel-postgres");break}f({projectDir:e,dependencies:i,devMode:!1}),f({projectDir:e,dependencies:s,devMode:!1});let n=k.join(m,"template/packages"),r=k.join(n,"config/payload",`${a==="postgresql"?"with-postgres":"with-sqlite"}.ts`),o=k.join(e,"payload.config.ts");z.copyFileSync(r,o);let c=k.join(n,"src/payload/collections"),p=k.join(e,"src/collections");z.mkdirSync(p,{recursive:!0}),z.copyFileSync(k.join(c,"Media.ts"),k.join(p,"Media.ts")),z.copyFileSync(k.join(c,"Users.ts"),k.join(p,"Users.ts"));let d=k.join(n,"src/app/(payload)"),u=k.join(e,"src/app/(payload)");z.mkdirSync(u,{recursive:!0}),z.copySync(d,u),w({projectDir:e,scripts:{payload:"payload","generate:importmap":"payload generate:importmap","generate:types":"payload generate:types"}})};import I from"path";import T from"fs-extra";var Ue=({projectDir:e,packages:t,databaseProvider:a})=>{let i=t?.authjs.inUse,s=t?.betterAuth.inUse;f({projectDir:e,dependencies:["prisma"],devMode:!0}),f({projectDir:e,dependencies:["@prisma/client"],devMode:!1});let n=I.join(m,"template/packages"),r=I.join(n,"prisma/schema",`${i?"with-authjs":s?"with-better-auth":"base"}.prisma`),o=T.readFileSync(r,"utf-8");a!=="sqlite"&&(o=o.replace('provider = "sqlite"',`provider = "${{mysql:"mysql",postgresql:"postgresql"}[a]}"`),["mysql"].includes(a)&&(o=o.replace("// @db.Text","@db.Text")));let c=I.join(e,"prisma/schema.prisma");T.mkdirSync(I.dirname(c),{recursive:!0}),T.writeFileSync(c,o);let p=I.join(n,"src/server/db/db-prisma.ts"),d=I.join(e,"src/server/db/index.ts");T.mkdirSync(I.dirname(d),{recursive:!0}),T.writeFileSync(d,T.readFileSync(p,"utf-8")),w({projectDir:e,scripts:{postinstall:"prisma generate","db:push":"prisma db push","db:studio":"prisma studio","db:generate":"prisma migrate dev","db:migrate":"prisma migrate deploy"}})};import g from"path";import St from"fs-extra";var Ee=({projectDir:e,packages:t})=>{let a=t?.authjs.inUse,i=t?.betterAuth.inUse,s=t?.prisma.inUse,n=t?.drizzle.inUse,r=s||n;f({projectDir:e,dependencies:["@trpc/server","@trpc/client","@trpc/react-query","@tanstack/react-query","server-only","superjson"],devMode:!1});let o=g.join(m,"template/packages"),c="src/app/api/trpc/[trpc]/route.ts",p=g.join(o,c),d=g.join(e,c),u=a&&r?"with-authjs-db.ts":a?"with-authjs.ts":i&&r?"with-betterauth-db.ts":i?"with-betterauth.ts":r?"with-db.ts":"base.ts",y=g.join(o,"src/server/api/init",u),x=g.join(e,"src/server/api/init.ts"),b=g.join(o,"src/server/api/root.ts"),X=g.join(e,"src/server/api/root.ts");function Q({usingAuthjs:U,usingBetterAuth:E,usingPrisma:ve,usingDrizzle:we}){return(U||E)&&ve?"with-auth-prisma.ts":(U||E)&&we?"with-auth-drizzle.ts":U||E?"with-auth.ts":ve?"with-prisma.ts":we?"with-drizzle.ts":"base.ts"}let Z=Q({usingAuthjs:a,usingBetterAuth:i,usingPrisma:s,usingDrizzle:n}),O=g.join(o,"src/server/api/routers/hello-world",Z),ee=g.join(e,"src/server/api/routers/hello-world.ts"),te=g.join(o,"src/lib/utils.ts"),se=g.join(e,"src/lib/utils.ts"),be=[[p,d],[y,x],[b,X],[O,ee],[te,se]],ie=g.join(o,"src/lib/api"),ae=g.join(e,"src/lib/api");be.push([g.join(ie,"client.tsx"),g.join(ae,"client.tsx")],[g.join(ie,"query-client.ts"),g.join(ae,"query-client.ts")],[g.join(ie,"server.ts"),g.join(ae,"server.ts")],[g.join(o,"src/components/greeting.tsx"),g.join(e,"src/components/greeting.tsx")]),be.forEach(([U,E])=>{St.copySync(U,E)})};import Me from"path";import _t from"fs-extra";var qe=({projectDir:e,packages:t})=>{let a=t?.typescript.inUse,i=t?.payload.inUse,s=[];a&&(s.push("typescript"),s.push("@types/node"),s.push("@types/react"),s.push("@types/react-dom")),f({projectDir:e,dependencies:s,devMode:!0});let n=Me.join(m,"template/packages/config/tsconfig",`${i?"with-payload":"base"}.json`),r=Me.join(e,"tsconfig.json");_t.copyFileSync(n,r)};var $e=["nextjs","payload"],ce=["none","authjs","betterAuth"],pe=["none","prisma","drizzle"],J=["sqlite","mysql","postgresql"];var Le=e=>({authjs:{inUse:e.includes("authjs"),installer:je},betterAuth:{inUse:e.includes("betterAuth"),installer:Ie},trpc:{inUse:e.includes("trpc"),installer:Ee},prisma:{inUse:e.includes("prisma"),installer:Ue},drizzle:{inUse:e.includes("drizzle"),installer:ze},envVariables:{inUse:!0,installer:Te},"eslint/prettier":{inUse:e.includes("eslint/prettier"),installer:Re},biome:{inUse:e.includes("biome"),installer:Ce},typescript:{inUse:!0,installer:qe},payload:{inUse:e.includes("payload"),installer:Oe}});import jt from"path";import At from"fs-extra";function D(){let e=jt.join(m,"package.json");return At.readJSONSync(e).version??"1.0.0"}var $=class extends Error{constructor(t){super(t)}};import V from"chalk";var l={error(...e){console.log(V.red(...e))},warn(...e){console.log(V.yellow(...e))},info(...e){console.log(V.cyan(...e))},success(...e){console.log(V.green(...e))}};var H=e=>(e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e);var It=/^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/;function Fe(e){let t=H(e),a=t.split("/"),i=a.findIndex(n=>n.startsWith("@")),s=a[a.length-1];return a.findIndex(n=>n.startsWith("@"))!==-1&&(s=a.slice(i).join("/")),t=="."||It.test(s??"")?!0:"App name must consist of only lowercase alphanumeric characters, '-', and '_'"}var Be=e=>e.startsWith(".")||e.startsWith("/")?"Import alias can't start with '.' or '/'":!0;var h={appName:M,packages:[],flags:{git:!1,install:!1,default:!1,CI:!1,trpc:!1,authentication:"none",orm:"none",linter:"eslint/prettier",importAlias:"@/",dbProvider:"sqlite",backend:"nextjs"},databaseProvider:"sqlite"};async function Ge(){let e=h,t=new Ct().name(ne).description("CLI for scaffolding new web apps with the Lx2 stack").version(D(),"-v, --version","Output the current version of Create Lx2 App").argument("[dir]","The name of the application, as well as the name of the directory to create").option("--git","Boolean flag to explicitly tell the CLI to initialize a new git repo in the project",!1).option("--install","Boolean flag to explicitly tell the CLI to run the package manager's install command",!1).option("-y, --default","Bypass the CLI and use all default options to bootstrap a new lx2-app",!1).option("--CI","Boolean value if we're running in CI",!1).option("--backend [framework]",`Choose a backend framework to use. Possible values: ${$e.join(", ")}`,h.flags.backend).option("--trpc [boolean]","Boolean flag to explicitly tell the CLI to set up tRPC in the project",i=>!!i&&i!=="false").option("--authProvider [provider]",`Choose an authentication provider to use. Possible values: ${ce.join(", ")}`,h.flags.authentication).option("--databaseORM [orm]",`Choose a database ORM to use. Possible values: ${pe.join(", ")}`,h.flags.orm).option("--linter [linter]",`Choose what linter and formatter to use. Possible values: ${h.flags.linter}`,h.flags.linter).option("-i, --import-alias [alias]","Explicitly tell the CLI to use a custom import alias",h.flags.importAlias).option("--dbProvider [provider]",`Choose a database provider to use. Possible values: ${J.join(", ")}`,h.flags.dbProvider).parse(process.argv);process.env.npm_config_user_agent?.startsWith("yarn/3")&&l.warn(` WARNING: It looks like you are using Yarn 3. This is currently not supported,
|
|
57
59
|
and likely to result in a crash. Please run create-lx2-app with another
|
|
58
60
|
package manager such as pnpm, npm, or Yarn Classic.
|
|
59
|
-
See: https://github.com/t3-oss/create-t3-app/issues/57`);let a=
|
|
61
|
+
See: https://github.com/t3-oss/create-t3-app/issues/57`);let a=t.args[0];if(a&&(e.appName=a),e.flags=t.opts(),e.flags.CI){switch(e.packages=[],e.flags.backend){case"payload":e.packages.push("payload");break;default:break}switch(e.flags.trpc&&e.packages.push("trpc"),e.flags.authentication){case"authjs":e.packages.push("authjs");break;case"betterAuth":e.packages.push("betterAuth");break;default:break}switch(e.flags.orm){case"prisma":e.packages.push("prisma");break;case"drizzle":e.packages.push("drizzle");break;default:break}switch(e.flags.linter){case"eslint/prettier":e.packages.push("eslint/prettier");break;case"biome":e.packages.push("biome");break;default:break}return e.packages.includes("authjs")&&e.packages.includes("betterAuth")&&(l.warn(`Incompatible authentication providers provided. Use either ${ce.join(", or ")}. Exiting.`),process.exit(0)),e.packages.includes("prisma")&&e.packages.includes("drizzle")&&(l.warn(`Incompatible database ORMs provided. Use either ${pe.join(", or ")}. Exiting.`),process.exit(0)),J.includes(e.flags.dbProvider)===!1&&(l.warn(`Incompatible database provided. Use either ${J.join(", or ")}. Exiting.`),process.exit(0)),e.flags.backend==="payload"&&e.flags.dbProvider==="mysql"&&(l.warn("Payload CMS does not support MySQL. Exiting."),process.exit(0)),e.packages.includes("eslint/prettier")&&e.packages.includes("biome")&&(l.warn(`Incompatible linters provided. Use either ${h.flags.linter}. Exiting.`),process.exit(0)),e.databaseProvider=e.packages.includes("prisma")||e.packages.includes("drizzle")?e.flags.dbProvider:"sqlite",e}if(e.flags.default)return e;try{if(process.env.TERM_PROGRAM?.toLowerCase().includes("mintty"))throw l.warn(` WARNING: It looks like you are using MinTTY, which is non-interactive. This is most likely because you are
|
|
60
62
|
using Git Bash. If that's that case, please use Git Bash from another terminal, such as Windows Terminal. Alternatively, you
|
|
61
|
-
can provide the arguments from the CLI directly: https://create.lx2.dev/docs/getting-started#experimental-ci-flags to skip the prompts.`),new
|
|
62
|
-
Using: ${
|
|
63
|
-
`);let n=
|
|
64
|
-
`).start();if(
|
|
65
|
-
`);else{n.stopAndPersist();let
|
|
66
|
-
`),
|
|
67
|
-
`)}import
|
|
68
|
-
`).start(),a=
|
|
69
|
-
`)}catch{
|
|
70
|
-
`)}}import
|
|
71
|
-
`))};var
|
|
63
|
+
can provide the arguments from the CLI directly: https://create.lx2.dev/docs/getting-started#experimental-ci-flags to skip the prompts.`),new $("Non-interactive environment");let i=v(),s={};a||(s.name=await Ne({message:"What will your project be called?",default:M,validate:d=>Fe(d)})),s.backend=await R({message:"What backend framework would you like to use?",choices:[{value:"nextjs",name:"Next.js"},{value:"payload",name:"Payload CMS"}],default:!h.flags.backend}),s.backend==="payload"&&(s.databaseProvider=await R({message:"What database provider would you like to use?",choices:[{value:"sqlite",name:"SQLite"},{value:"postgresql",name:"PostgreSQL"}],default:!h.flags.dbProvider})),s.backend==="nextjs"&&(s.trpc=await K({message:"Would you like to use tRPC?",default:!h.flags.trpc}),s.authentication=await R({message:"What authentication provider would you like to use?",choices:[{value:"none",name:"None"},{value:"authjs",name:"Auth.js"},{value:"betterAuth",name:"Better Auth"}],default:!h.flags.authentication}),s.orm=await R({message:"What database ORM would you like to use?",choices:[{value:"none",name:"None"},{value:"prisma",name:"Prisma"},{value:"drizzle",name:"Drizzle"}],default:!h.flags.orm}),s.orm!=="none"&&(s.databaseProvider=await R({message:"What database provider would you like to use?",choices:[{value:"sqlite",name:"SQLite"},{value:"mysql",name:"MySQL"},{value:"postgresql",name:"PostgreSQL"}],default:!h.flags.dbProvider}))),s.linter=await R({message:"What linter and formatter would you like to use?",choices:[{value:"eslint/prettier",name:"ESLint/Prettier"},{value:"biome",name:"Biome"}],default:!h.flags.linter}),e.flags.git||(s.git=await K({message:"Should we initialize a Git repository and stage the changes?",default:!h.flags.git})),e.flags.install||(s.install=await K({message:`Should we run '${i}`+(i==="yarn"?"'?":" install' for you?"),default:!h.flags.install})),s.importAlias=await Ne({message:"What import alias would you like to use?",default:h.flags.importAlias,validate:Be});let n=[];switch(s.backend){case"payload":n.push("payload");break;default:break}switch(s.trpc&&n.push("trpc"),s.authentication){case"authjs":n.push("authjs");break;case"betterAuth":n.push("betterAuth");break;default:break}switch(s.orm){case"prisma":n.push("prisma");break;case"drizzle":n.push("drizzle");break;default:break}switch(s.linter){case"eslint/prettier":n.push("eslint/prettier");break;case"biome":n.push("biome");break;default:break}let r=[...e.packages||[],...n||[]],o=Array.from(new Set(r)),c=o.includes("trpc"),p=o.filter(d=>d!=="trpc"&&d!=="eslint/prettier"&&d!=="biome");return c&&p.length>0&&(l.warn("As of right now, Create Lx2 App only supports base tRPC without any additional packages or frameworks. Exiting."),process.exit(0)),{appName:s.name??e.appName,packages:n,flags:{...e.flags,git:s.git??e.flags.git,install:s.install??e.flags.install,importAlias:s.importAlias??e.flags.importAlias},databaseProvider:s.databaseProvider??"sqlite"}}catch(i){if(i instanceof $)l.warn(`${ne} needs an interactive terminal to run.`),await K({message:"Continue scaffolding with default options?",default:!0})||(l.info("Exiting..."),process.exit(0)),l.info(`Scaffolding default lx2 app in ./${e.appName}`);else throw i}return e}import Ot from"path";import We from"chalk";import zt from"ora";function Je(e){let{packages:t}=e;l.info("Adding boilerplate...");for(let[a,i]of Object.entries(t))if(i.inUse){let s=zt(`Boilerplating ${a}...`).start();i.installer(e),s.succeed(We.green(`${We.green.bold(a)}`))}l.info("")}import de from"path";import{confirm as Tt,select as Dt}from"@inquirer/prompts";import C from"chalk";import L from"fs-extra";import Rt from"ora";async function Ve({projectName:e,projectDir:t,pkgManager:a,install:i}){let s=de.join(m,"template/base");i?l.info(""):l.info(`
|
|
64
|
+
Using: ${C.cyan.bold(a)}
|
|
65
|
+
`);let n=Rt(`Scaffolding in: ${t}...
|
|
66
|
+
`).start();if(L.existsSync(t))if(L.readdirSync(t).length===0)e!=="."&&n.info(`${C.cyan.bold(e)} exists but is empty, continuing...
|
|
67
|
+
`);else{n.stopAndPersist();let o=await Dt({message:`${C.redBright.bold("Warning:")} ${C.cyan.bold(e)} already exists and isn't empty. How would you like to proceed?`,choices:[{value:"abort",name:"Abort installation (recommended)"},{value:"clear",name:"Clear the directory and continue installation"},{value:"overwrite",name:"Continue installation and overwrite conflicting files"}],default:"abort"});o==="abort"&&(n.fail("Aborting installation..."),process.exit(1)),await Tt({message:`Are you sure you want to ${o==="clear"?"clear the directory":"overwrite conflicting files"}`,default:!1})||(n.fail("Aborting installation..."),process.exit(1)),o==="clear"&&(n.info(`Emptying ${C.cyan.bold(e)} and creating lx2 app...
|
|
68
|
+
`),L.emptyDirSync(t))}n.start(),L.copySync(s,t),L.renameSync(de.join(t,"_gitignore"),de.join(t,".gitignore"));let r=e==="."?"App":C.cyan.bold(e);n.succeed(`${r} ${C.green.bold("scaffolded successfully!")}
|
|
69
|
+
`)}import P from"path";import me from"fs-extra";function He({packages:e,projectDir:t}){let a=P.join(m,"template/packages/src/app/layout"),i=e.payload.inUse,s=e.trpc.inUse,n="base.tsx";s&&(n="with-trpc.tsx");let r=P.join(a,n),o=P.join(t,`src/app/${i?"(frontend)":""}/layout.tsx`);me.copySync(r,o)}function Ke({packages:e,projectDir:t}){let a=P.join(m,"template/packages/src/app/page"),i=e.payload.inUse,s=e.authjs.inUse,n=e.betterAuth.inUse,r=e.trpc.inUse,o=e.prisma.inUse,c=e.drizzle.inUse,p="base.tsx";i&&(p="with-payload.tsx"),s&&(p="with-authjs.tsx"),n&&(p="with-better-auth.tsx"),r&&s&&(p="with-trpc-authjs.tsx"),r&&n&&(p="with-trpc-betterauth.tsx"),r&&(p="with-trpc.tsx"),o&&(p="with-prisma.tsx"),s&&o&&(p="with-authjs-prisma.tsx"),n&&o&&(p="with-better-auth-prisma.tsx"),c&&(p="with-drizzle.tsx"),s&&c&&(p="with-authjs-drizzle.tsx"),n&&c&&(p="with-better-auth-drizzle.tsx");let d=P.join(a,p),u=P.join(t,`src/app/${i?"(frontend)":""}/page.tsx`);me.copySync(d,u)}function Ye({projectDir:e}){let t=P.join(m,"template/packages/src/styles"),i=P.join(t,"base.css"),s=P.join(e,"src/styles/globals.css");me.copySync(i,s)}async function Xe({projectName:e,scopedAppName:t,packages:a,install:i,databaseProvider:s}){let n=v(),r=Ot.resolve(process.cwd(),e);return await Ve({projectName:e,projectDir:r,pkgManager:n,scopedAppName:t,install:i,databaseProvider:s}),Je({projectName:e,scopedAppName:t,projectDir:r,pkgManager:n,packages:a,install:i,databaseProvider:s}),He({packages:a,projectDir:r}),Ke({packages:a,projectDir:r}),Ye({packages:a,projectDir:r}),r}import{execSync as fe}from"child_process";import ue from"path";import{confirm as Qe}from"@inquirer/prompts";import F from"chalk";import{execa as B}from"execa";import Ze from"fs-extra";import Ut from"ora";function Et(e){try{return fe("git --version",{cwd:e}),!0}catch{return!1}}function ge(e){return Ze.existsSync(ue.join(e,".git"))}async function he(e){try{return await B("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdout:"ignore"}),!0}catch{return!1}}function Mt(){let t=fe("git --version").toString().trim().split(" ")[2],a=t?.split(".")[0],i=t?.split(".")[1];return{major:Number(a),minor:Number(i)}}function qt(){return fe("git config --global init.defaultBranch || echo main").toString().trim()}async function et(e){if(l.info("Initializing Git..."),!Et(e)){l.warn("Git is not installed. Skipping Git initialization.");return}let t=Ut(`Creating a new git repo...
|
|
70
|
+
`).start(),a=ge(e),i=await he(e),s=ue.parse(e).name;if(i&&a){if(t.stop(),!await Qe({message:`${F.redBright.bold("Warning:")} Git is already initialized in "${s}". Initializing a new git repository would delete the previous history. Would you like to continue anyways?`,default:!1})){t.info("Skipping Git initialization.");return}Ze.removeSync(ue.join(e,".git"))}else if(i&&!a&&(t.stop(),!await Qe({message:`${F.redBright.bold("Warning:")} "${s}" is already in a git worktree. Would you still like to initialize a new git repository in this directory?`,default:!1}))){t.info("Skipping Git initialization.");return}try{let n=qt(),{major:r,minor:o}=Mt();r<2||r==2&&o<28?(await B("git",["init"],{cwd:e}),await B("git",["symbolic-ref","HEAD",`refs/heads/${n}`],{cwd:e})):await B("git",["init",`--initial-branch=${n}`],{cwd:e}),await B("git",["add","."],{cwd:e}),t.succeed(`${F.green("Successfully initialized and staged")} ${F.green.bold("git")}
|
|
71
|
+
`)}catch{t.fail(`${F.bold.red("Failed:")} could not initialize git. Update git to the latest version!
|
|
72
|
+
`)}}import $t from"chalk";import{execa as tt}from"execa";import st from"ora";var ye=async(e,t,a)=>{let{onDataHandle:i,args:s=["install"],stdout:n="pipe"}=a,r=st(`Running ${t} install...`).start(),o=tt(t,s,{cwd:e,stdout:n});return await new Promise((c,p)=>{i&&o.stdout?.on("data",i(r)),o.on("error",d=>p(d)),o.on("close",()=>c())}),r},Lt=async(e,t)=>{switch(e){case"npm":return await tt(e,["install"],{cwd:t,stderr:"inherit"}),null;case"pnpm":return ye(t,e,{onDataHandle:a=>i=>{let s=i.toString();s.includes("Progress")&&(a.text=s.includes("|")?s.split(" | ")[1]??"":s)}});case"yarn":return ye(t,e,{onDataHandle:a=>i=>{a.text=i.toString()}});case"bun":return ye(t,e,{stdout:"ignore"})}},it=async({projectDir:e})=>{l.info("Installing dependencies...");let t=v();(await Lt(t,e)??st()).succeed($t.green(`Successfully installed dependencies!
|
|
73
|
+
`))};var at=async({projectName:e=M,packages:t,install:a,projectDir:i,databaseProvider:s})=>{let n=v();l.info("Next steps:"),e!=="."&&l.info(` cd ${e}`),a===!1&&(n==="yarn"?l.info(` ${n}`):l.info(` ${n} install`)),["postgresql","mysql"].includes(s)&&l.info(" Add your database connection string to .env"),t?.authjs.inUse&&l.info(" Fill in your .env with necessary values. See https://create.lx2.dev/docs/first-steps for more info."),t?.betterAuth.inUse&&l.info(" Fill in your .env with necessary values. See https://create.lx2.dev/docs/first-steps for more info."),t?.prisma.inUse&&l.info(` Run "${n} db:push" to create you database tables.`),["npm"].includes(n)?l.info(` ${n} run dev`):l.info(` ${n} dev`),!await he(i)&&!ge(i)&&l.info(" git init"),l.info(' git commit -m "initial commit"')};import Y from"fs";import Ft from"path";function nt(e,t,a){Y.readdirSync(e).forEach(s=>{let n=Ft.join(e,s);if(Y.statSync(n).isDirectory())nt(n,t,a);else{let o=Y.readFileSync(n,"utf8").replace(new RegExp(t,"g"),a);Y.writeFileSync(n,o,"utf8")}})}function rt(e,t){let a=t.replace(/\*/g,"").replace(/[^\/]$/,"$&/");nt(e,"@/",a)}import ot from"path";function lt(e){let a=H(e).split("/"),i=a[a.length-1];if(i==="."){let r=ot.resolve(process.cwd());i=ot.basename(r)}let s=a.findIndex(r=>r.startsWith("@"));a.findIndex(r=>r.startsWith("@"))!==-1&&(i=a.slice(s).join("/"));let n=a.filter(r=>!r.startsWith("@")).join("/");return[i,n]}function ct(){l.warn("Compatibility Warnings:");for(let e of N){let t=e.packages,a="";e.message?a=`- ${e.message}`:t.length===2?a=`- Using ${t[0]} with ${t[1]} is not supported yet.`:t.length>2&&(a=`- Using ${t[0]} with ${t.slice(1,-1).join(", ")}, or ${t.slice(-1)} is not supported yet.`),l.warn(a)}console.log("")}import Bt from"gradient-string";var Nt={primary:"#bf95f9",accent:"#6071a4",secondary:"#ff7ac5"};function pt(){let e=Bt(Object.values(Nt)),t=v();(t==="yarn"||t==="pnpm")&&console.log(""),console.log(e.multiline(xe))}import{execSync as Gt}from"child_process";import Wt from"https";function dt(e){let t=D();t.includes("beta")?(l.warn(" You are using a beta version of create-lx2-app."),l.warn(" Please report any bugs you encounter.")):t!==e&&(l.warn(" You are using an outdated version of create-lx2-app."),l.warn(" Your version:",t+".","Latest version in the npm registry:",e),l.warn(" Please run the CLI with @latest to get the latest updates.")),console.log("")}function Jt(){return new Promise((e,t)=>{Wt.get("https://registry.npmjs.org/-/package/create-lx2-app/dist-tags",a=>{if(a.statusCode===200){let i="";a.on("data",s=>i+=s),a.on("end",()=>{e(JSON.parse(i).latest)})}else t()}).on("error",()=>{t()})})}var mt=()=>Jt().catch(()=>{try{return Gt("npm view create-lx2-app version").toString().trim()}catch{return null}});async function Ht(){let e=await mt(),t=v();pt(),e&&dt(e),N.length>0&&ct();let{appName:a,packages:i,flags:{git:s,install:n,importAlias:r},databaseProvider:o}=await Ge(),c=Le(i),[p,d]=lt(a),u=await Xe({projectName:d,scopedAppName:p,packages:c,install:n,databaseProvider:o}),y=ft.readJsonSync(ut.join(u,"package.json"));if(y.name=p,y.clx2aMetadata={initVersion:D()},t!=="bun"){let{stdout:x}=await Vt(t,["-v"],{cwd:u});y.packageManager=`${t}@${x.trim()}`}ft.writeJSONSync(ut.join(u,"package.json"),y,{spaces:2}),r!=="@/"&&rt(u,r),n&&await it({projectDir:u}),s&&await et(u),await at({projectDir:u,projectName:d,packages:c,install:n,databaseProvider:o}),process.exit(0)}Ht().catch(e=>{l.error("Aborting installation..."),e instanceof Error?l.error(e.message):(l.error("An unknown error occurred. Please open an issue on GitHub with the below:"),console.error(e)),process.exit(1)});
|
package/package.json
CHANGED
|
@@ -1,92 +1,100 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
2
|
+
"name": "create-lx2-app",
|
|
3
|
+
"version": "0.11.1-beta.718fd8b",
|
|
4
|
+
"description": "The Most Opinionated Way to Build Next.js Apps",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/slickyeet/create-lx2-app",
|
|
9
|
+
"directory": "cli"
|
|
10
|
+
},
|
|
11
|
+
"keywords": [
|
|
12
|
+
"create-lx2-app",
|
|
13
|
+
"lx2-app",
|
|
14
|
+
"typescript",
|
|
15
|
+
"next.js",
|
|
16
|
+
"tailwind"
|
|
17
|
+
],
|
|
18
|
+
"type": "module",
|
|
19
|
+
"exports": "./dist/index.js",
|
|
20
|
+
"bin": {
|
|
21
|
+
"create-lx2-app": "./dist/index.js"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist",
|
|
25
|
+
"template",
|
|
26
|
+
"README.md",
|
|
27
|
+
"LICENSE",
|
|
28
|
+
"package.json"
|
|
29
|
+
],
|
|
30
|
+
"engines": {
|
|
31
|
+
"node": ">=18"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"dev": "tsup --watch",
|
|
35
|
+
"build": "tsup",
|
|
36
|
+
"start": "node dist/index.js",
|
|
37
|
+
"format": "prettier '**/*.{cjs,mjs,ts,tsx,md,json}' --ignore-path ../.gitignore --ignore-unknown --no-error-on-unmatched-pattern --write",
|
|
38
|
+
"format:check": "prettier '**/*.{cjs,mjs,ts,tsx,md,json}' --ignore-path ../.gitignore --ignore-unknown --no-error-on-unmatched-pattern --check",
|
|
39
|
+
"typecheck": "tsc",
|
|
40
|
+
"clean": "rm -rf dist .turbo node_modules",
|
|
41
|
+
"link": "pnpm run build && npm link",
|
|
42
|
+
"release": "changeset version",
|
|
43
|
+
"pub:beta": "pnpm run build && npm publish --tag beta",
|
|
44
|
+
"pub:release": "pnpm run build && npm publish"
|
|
45
|
+
},
|
|
46
|
+
"dependencies": {
|
|
47
|
+
"@inquirer/prompts": "^8.0.1",
|
|
48
|
+
"chalk": "^5.6.2",
|
|
49
|
+
"commander": "^14.0.2",
|
|
50
|
+
"execa": "^9.6.0",
|
|
51
|
+
"fs-extra": "^11.3.2",
|
|
52
|
+
"gradient-string": "^3.0.0",
|
|
53
|
+
"ora": "^9.0.0",
|
|
54
|
+
"sort-package-json": "^3.4.0"
|
|
55
|
+
},
|
|
56
|
+
"devDependencies": {
|
|
57
|
+
"@auth/drizzle-adapter": "^1.11.1",
|
|
58
|
+
"@auth/prisma-adapter": "^2.11.1",
|
|
59
|
+
"@biomejs/biome": "^2.3.7",
|
|
60
|
+
"@eslint/eslintrc": "^3.3.1",
|
|
61
|
+
"@ianvs/prettier-plugin-sort-imports": "^4.7.0",
|
|
62
|
+
"@libsql/client": "^0.15.15",
|
|
63
|
+
"@payloadcms/db-sqlite": "^3.64.0",
|
|
64
|
+
"@payloadcms/db-vercel-postgres": "^3.64.0",
|
|
65
|
+
"@payloadcms/next": "^3.64.0",
|
|
66
|
+
"@payloadcms/payload-cloud": "^3.64.0",
|
|
67
|
+
"@payloadcms/richtext-lexical": "^3.64.0",
|
|
68
|
+
"@prisma/client": "^7.0.0",
|
|
69
|
+
"@t3-oss/env-nextjs": "^0.13.8",
|
|
70
|
+
"@types/better-sqlite3": "^7.6.13",
|
|
71
|
+
"@types/fs-extra": "^11.0.4",
|
|
72
|
+
"@types/node": "^24.10.1",
|
|
73
|
+
"@types/react": "^19.2.7",
|
|
74
|
+
"@types/react-dom": "^19.2.3",
|
|
75
|
+
"better-auth": "^1.4.1",
|
|
76
|
+
"better-sqlite3": "^12.4.6",
|
|
77
|
+
"drizzle-kit": "^0.31.7",
|
|
78
|
+
"drizzle-orm": "^0.44.7",
|
|
79
|
+
"eslint": "^9.39.1",
|
|
80
|
+
"eslint-config-next": "^16.0.4",
|
|
81
|
+
"graphql": "^16.12.0",
|
|
82
|
+
"mysql2": "^3.15.3",
|
|
83
|
+
"next": "^16.0.4",
|
|
84
|
+
"next-auth": "^5.0.0-beta.25",
|
|
85
|
+
"payload": "^3.64.0",
|
|
86
|
+
"postgres": "^3.4.7",
|
|
87
|
+
"prettier": "^3.6.2",
|
|
88
|
+
"prettier-plugin-tailwindcss": "^0.7.1",
|
|
89
|
+
"prisma": "^7.0.0",
|
|
90
|
+
"react": "^19.2.0",
|
|
91
|
+
"react-dom": "^19.2.0",
|
|
92
|
+
"server-only": "^0.0.1",
|
|
93
|
+
"sharp": "^0.34.5",
|
|
94
|
+
"tailwindcss": "^4.1.17",
|
|
95
|
+
"tsup": "^8.5.1",
|
|
96
|
+
"type-fest": "^5.2.0",
|
|
97
|
+
"typescript": "^5.9.3",
|
|
98
|
+
"zod": "^4.1.13"
|
|
99
|
+
}
|
|
100
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { fetchRequestHandler } from "@trpc/server/adapters/fetch"
|
|
2
|
+
import { type NextRequest } from "next/server"
|
|
3
|
+
|
|
4
|
+
import { env } from "@/env"
|
|
5
|
+
import { createTRPCContext } from "@/server/api/init"
|
|
6
|
+
import { appRouter } from "@/server/api/root"
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when
|
|
10
|
+
* handling a HTTP request (e.g. when you make requests from Client Components).
|
|
11
|
+
*/
|
|
12
|
+
async function createContext(req: NextRequest) {
|
|
13
|
+
return createTRPCContext({
|
|
14
|
+
headers: req.headers,
|
|
15
|
+
})
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const handler = (req: NextRequest) =>
|
|
19
|
+
fetchRequestHandler({
|
|
20
|
+
endpoint: "/api/trpc",
|
|
21
|
+
req,
|
|
22
|
+
router: appRouter,
|
|
23
|
+
createContext: () => createContext(req),
|
|
24
|
+
onError:
|
|
25
|
+
env.NODE_ENV === "development"
|
|
26
|
+
? ({ path, error }) => {
|
|
27
|
+
console.error(
|
|
28
|
+
`[tRPC] Error on ${path ?? "<no-path>"}: ${error.message}`
|
|
29
|
+
)
|
|
30
|
+
}
|
|
31
|
+
: undefined,
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
export { handler as GET, handler as POST }
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { Metadata } from "next"
|
|
2
|
+
import { Geist, Geist_Mono } from "next/font/google"
|
|
3
|
+
|
|
4
|
+
import { TRPCReactProvider } from "@/lib/api/client"
|
|
5
|
+
|
|
6
|
+
import "@/styles/globals.css"
|
|
7
|
+
|
|
8
|
+
const geistSans = Geist({
|
|
9
|
+
variable: "--font-geist-sans",
|
|
10
|
+
subsets: ["latin"],
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
const geistMono = Geist_Mono({
|
|
14
|
+
variable: "--font-geist-mono",
|
|
15
|
+
subsets: ["latin"],
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
export const metadata: Metadata = {
|
|
19
|
+
title: "Create Lx2 App",
|
|
20
|
+
description: "Generated by create lx2 app",
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export default function RootLayout({
|
|
24
|
+
children,
|
|
25
|
+
}: Readonly<{
|
|
26
|
+
children: React.ReactNode
|
|
27
|
+
}>) {
|
|
28
|
+
return (
|
|
29
|
+
<html lang="en">
|
|
30
|
+
<body
|
|
31
|
+
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
|
|
32
|
+
>
|
|
33
|
+
<TRPCReactProvider>{children}</TRPCReactProvider>
|
|
34
|
+
</body>
|
|
35
|
+
</html>
|
|
36
|
+
)
|
|
37
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { fileURLToPath } from "url"
|
|
2
|
+
|
|
3
|
+
import { Greeting } from "@/components/greeting"
|
|
4
|
+
import { api, HydrateClient } from "@/lib/api/server"
|
|
5
|
+
|
|
6
|
+
export default async function HomePage() {
|
|
7
|
+
const fileURL = `vscode://file/${fileURLToPath(import.meta.url)}`
|
|
8
|
+
|
|
9
|
+
void api.helloWorld.greeting({ text: "from tRPC!" })
|
|
10
|
+
|
|
11
|
+
return (
|
|
12
|
+
<HydrateClient>
|
|
13
|
+
<main className="mx-auto flex h-screen max-w-5xl flex-col items-center justify-between overflow-hidden p-6 sm:p-[45px]">
|
|
14
|
+
<div className="flex grow flex-col items-center justify-center">
|
|
15
|
+
{/* Logo */}
|
|
16
|
+
<picture className="relative">
|
|
17
|
+
<div className="absolute inset-0 animate-pulse bg-linear-to-r from-[oklch(0.7468_0.1455_302.21)] via-[oklch(0.7345_0.0464_270.71)] to-[oklch(0.7563_0.1807_347.17)] opacity-20 blur-lg dark:via-[oklch(0.5567_0.0816_269.53)]" />
|
|
18
|
+
|
|
19
|
+
<source srcSet="https://github.com/SlickYeet/create-lx2-app/blob/f1209465d59e03e284702d9f492f1bc1cfa49c32/docs/v2/public/android-chrome-192x192.png?raw=true" />
|
|
20
|
+
<img
|
|
21
|
+
src="https://github.com/SlickYeet/create-lx2-app/blob/f1209465d59e03e284702d9f492f1bc1cfa49c32/docs/v2/public/android-chrome-192x192.png?raw=true"
|
|
22
|
+
alt="Logo"
|
|
23
|
+
width={65}
|
|
24
|
+
height={65}
|
|
25
|
+
className="block h-auto max-w-full"
|
|
26
|
+
/>
|
|
27
|
+
</picture>
|
|
28
|
+
|
|
29
|
+
{/* Title & Description */}
|
|
30
|
+
<h1 className="mt-6 text-5xl font-bold tracking-tight text-balance md:text-6xl lg:text-7xl">
|
|
31
|
+
Create{" "}
|
|
32
|
+
<span className="text-[oklch(0.7468_0.1455_302.21)]">Lx2</span> App
|
|
33
|
+
</h1>
|
|
34
|
+
<p className="text-center text-lg text-neutral-700 md:text-xl lg:mt-6 dark:text-neutral-300">
|
|
35
|
+
The Most Opinionated Way to Build Next.js Apps
|
|
36
|
+
</p>
|
|
37
|
+
|
|
38
|
+
{/* Links */}
|
|
39
|
+
<div className="mt-12 flex items-center gap-3">
|
|
40
|
+
<a
|
|
41
|
+
href="https://create.lx2.dev/docs"
|
|
42
|
+
target="_blank"
|
|
43
|
+
rel="noopener noreferrer"
|
|
44
|
+
className="flex items-center rounded-md border border-white/25 px-2 py-1 outline-none hover:opacity-80 focus:opacity-80 active:opacity-70"
|
|
45
|
+
>
|
|
46
|
+
Docs
|
|
47
|
+
<svg
|
|
48
|
+
xmlns="http://www.w3.org/2000/svg"
|
|
49
|
+
viewBox="0 0 24 24"
|
|
50
|
+
strokeLinecap="round"
|
|
51
|
+
strokeLinejoin="round"
|
|
52
|
+
className="mb-1.5 size-4 fill-none stroke-current stroke-2"
|
|
53
|
+
>
|
|
54
|
+
<path d="M7 7h10v10" />
|
|
55
|
+
<path d="M7 17 17 7" />
|
|
56
|
+
</svg>
|
|
57
|
+
</a>
|
|
58
|
+
<a
|
|
59
|
+
href="https://link.lx2.dev/discord"
|
|
60
|
+
target="_blank"
|
|
61
|
+
rel="noopener noreferrer"
|
|
62
|
+
className="flex items-center rounded-md border border-white/25 px-2 py-1 outline-none hover:opacity-80 focus:opacity-80 active:opacity-70"
|
|
63
|
+
>
|
|
64
|
+
Discord
|
|
65
|
+
<svg
|
|
66
|
+
xmlns="http://www.w3.org/2000/svg"
|
|
67
|
+
viewBox="0 0 24 24"
|
|
68
|
+
strokeLinecap="round"
|
|
69
|
+
strokeLinejoin="round"
|
|
70
|
+
className="mb-1.5 size-4 fill-none stroke-current stroke-2"
|
|
71
|
+
>
|
|
72
|
+
<path d="M7 7h10v10" />
|
|
73
|
+
<path d="M7 17 17 7" />
|
|
74
|
+
</svg>
|
|
75
|
+
</a>
|
|
76
|
+
<a
|
|
77
|
+
href="https://github.com/SlickYeet/create-lx2-app"
|
|
78
|
+
target="_blank"
|
|
79
|
+
rel="noopener noreferrer"
|
|
80
|
+
className="flex items-center rounded-md border border-white/25 px-2 py-1 outline-none hover:opacity-80 focus:opacity-80 active:opacity-70"
|
|
81
|
+
>
|
|
82
|
+
GitHub
|
|
83
|
+
<svg
|
|
84
|
+
xmlns="http://www.w3.org/2000/svg"
|
|
85
|
+
viewBox="0 0 24 24"
|
|
86
|
+
strokeLinecap="round"
|
|
87
|
+
strokeLinejoin="round"
|
|
88
|
+
className="mb-1.5 size-4 fill-none stroke-current stroke-2"
|
|
89
|
+
>
|
|
90
|
+
<path d="M7 7h10v10" />
|
|
91
|
+
<path d="M7 17 17 7" />
|
|
92
|
+
</svg>
|
|
93
|
+
</a>
|
|
94
|
+
</div>
|
|
95
|
+
|
|
96
|
+
{/* tRPC Greeting */}
|
|
97
|
+
<Greeting />
|
|
98
|
+
</div>
|
|
99
|
+
|
|
100
|
+
{/* Footer */}
|
|
101
|
+
<div className="flex flex-col items-center gap-1 text-sm text-neutral-600 lg:flex-row lg:gap-2 dark:text-neutral-400">
|
|
102
|
+
<p className="m-0">Get started by editing </p>
|
|
103
|
+
<a
|
|
104
|
+
href={fileURL}
|
|
105
|
+
className="rounded-md bg-neutral-200 px-2 py-1 dark:bg-neutral-800"
|
|
106
|
+
>
|
|
107
|
+
<code>src/app/page.tsx</code>
|
|
108
|
+
</a>
|
|
109
|
+
</div>
|
|
110
|
+
</main>
|
|
111
|
+
</HydrateClient>
|
|
112
|
+
)
|
|
113
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"use client"
|
|
2
|
+
|
|
3
|
+
import { api } from "@/lib/api/client"
|
|
4
|
+
|
|
5
|
+
export function Greeting() {
|
|
6
|
+
const [greeting] = api.helloWorld.greeting.useSuspenseQuery({
|
|
7
|
+
text: "from tRPC!",
|
|
8
|
+
})
|
|
9
|
+
|
|
10
|
+
return (
|
|
11
|
+
<div className="mt-12 flex flex-col items-center gap-3">
|
|
12
|
+
<div className="mb-4">
|
|
13
|
+
<h2 className="mb-4 text-center">
|
|
14
|
+
<span className="text-2xl text-neutral-700 dark:text-neutral-300">
|
|
15
|
+
{greeting}
|
|
16
|
+
</span>
|
|
17
|
+
</h2>
|
|
18
|
+
</div>
|
|
19
|
+
</div>
|
|
20
|
+
)
|
|
21
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { createEnv } from "@t3-oss/env-nextjs"
|
|
2
|
+
import { z } from "zod"
|
|
3
|
+
|
|
4
|
+
export const env = createEnv({
|
|
5
|
+
/**
|
|
6
|
+
* Specify your server-side environment variables schema here. This way you can ensure the app
|
|
7
|
+
* isn't built with invalid env vars.
|
|
8
|
+
*/
|
|
9
|
+
server: {
|
|
10
|
+
NODE_ENV: z
|
|
11
|
+
.enum(["development", "test", "production"])
|
|
12
|
+
.default("development"),
|
|
13
|
+
},
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Specify your client-side environment variables schema here. This way you can ensure the app
|
|
17
|
+
* isn't built with invalid env vars. To expose them to the client, prefix them with
|
|
18
|
+
* `NEXT_PUBLIC_`.
|
|
19
|
+
*/
|
|
20
|
+
client: {
|
|
21
|
+
// NEXT_PUBLIC_CLIENTVAR: z.string(),
|
|
22
|
+
NEXT_PUBLIC_URL: z.url(),
|
|
23
|
+
},
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* You can't destruct `process.env` as a regular object in the Next.js edge runtimes (e.g.
|
|
27
|
+
* middlewares) or client-side so we need to destruct manually.
|
|
28
|
+
*/
|
|
29
|
+
runtimeEnv: {
|
|
30
|
+
NODE_ENV: process.env.NODE_ENV,
|
|
31
|
+
// NEXT_PUBLIC_CLIENTVAR: process.env.NEXT_PUBLIC_CLIENTVAR,
|
|
32
|
+
NEXT_PUBLIC_URL: process.env.NEXT_PUBLIC_URL,
|
|
33
|
+
},
|
|
34
|
+
/**
|
|
35
|
+
* Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially
|
|
36
|
+
* useful for Docker builds.
|
|
37
|
+
*/
|
|
38
|
+
skipValidation: !!process.env.SKIP_ENV_VALIDATION,
|
|
39
|
+
/**
|
|
40
|
+
* Makes it so that empty strings are treated as undefined. `SOME_VAR: z.string()` and
|
|
41
|
+
* `SOME_VAR=''` will throw an error.
|
|
42
|
+
*/
|
|
43
|
+
emptyStringAsUndefined: true,
|
|
44
|
+
})
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"use client"
|
|
2
|
+
|
|
3
|
+
import { QueryClientProvider, type QueryClient } from "@tanstack/react-query"
|
|
4
|
+
import { httpBatchStreamLink, loggerLink } from "@trpc/client"
|
|
5
|
+
import { createTRPCReact } from "@trpc/react-query"
|
|
6
|
+
import { type inferRouterInputs, type inferRouterOutputs } from "@trpc/server"
|
|
7
|
+
import React from "react"
|
|
8
|
+
import superjson from "superjson"
|
|
9
|
+
|
|
10
|
+
import { getBaseUrl } from "@/lib/utils"
|
|
11
|
+
import { type AppRouter } from "@/server/api/root"
|
|
12
|
+
|
|
13
|
+
import { createQueryClient } from "./query-client"
|
|
14
|
+
|
|
15
|
+
let clientQueryClientSingleton: QueryClient | undefined = undefined
|
|
16
|
+
function getQueryClient() {
|
|
17
|
+
if (typeof window === "undefined") {
|
|
18
|
+
// Server: always make a new query client
|
|
19
|
+
return createQueryClient()
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Browser: use singleton pattern to keep the same query client
|
|
23
|
+
clientQueryClientSingleton ??= createQueryClient()
|
|
24
|
+
return clientQueryClientSingleton
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export const api = createTRPCReact<AppRouter>()
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Inference helper for inputs.
|
|
31
|
+
*
|
|
32
|
+
* @example type HelloInput = RouterInputs["helloWorld"]["hello"]
|
|
33
|
+
*/
|
|
34
|
+
export type RouterInputs = inferRouterInputs<AppRouter>
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Inference helper for outputs.
|
|
38
|
+
*
|
|
39
|
+
* @example type HelloOutput = RouterOutputs["helloWorld"]["hello"]
|
|
40
|
+
*/
|
|
41
|
+
export type RouterOutputs = inferRouterOutputs<AppRouter>
|
|
42
|
+
|
|
43
|
+
export function TRPCReactProvider({ children }: React.PropsWithChildren) {
|
|
44
|
+
const queryClient = getQueryClient()
|
|
45
|
+
|
|
46
|
+
const [trpcClient] = React.useState(() =>
|
|
47
|
+
api.createClient({
|
|
48
|
+
links: [
|
|
49
|
+
/**
|
|
50
|
+
* The loggerLink is useful for debugging, but can be very noisy.
|
|
51
|
+
* You can disable Query logging by commenting out the process.env.NODE_ENV check.
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* loggerLink({
|
|
55
|
+
* enabled: (opts) =>
|
|
56
|
+
* // process.env.NODE_ENV === "development" ||
|
|
57
|
+
* opts.direction === "down" && opts.result instanceof Error,
|
|
58
|
+
* }),
|
|
59
|
+
*/
|
|
60
|
+
loggerLink({
|
|
61
|
+
enabled: (opts) =>
|
|
62
|
+
process.env.NODE_ENV === "development" ||
|
|
63
|
+
(opts.direction === "down" && opts.result instanceof Error),
|
|
64
|
+
}),
|
|
65
|
+
httpBatchStreamLink({
|
|
66
|
+
transformer: superjson,
|
|
67
|
+
url: `${getBaseUrl()}/api/trpc`,
|
|
68
|
+
headers() {
|
|
69
|
+
const headers = new Headers()
|
|
70
|
+
headers.set("x-trpc-source", "nextjs-react")
|
|
71
|
+
return headers
|
|
72
|
+
},
|
|
73
|
+
}),
|
|
74
|
+
],
|
|
75
|
+
})
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
return (
|
|
79
|
+
<QueryClientProvider client={queryClient}>
|
|
80
|
+
<api.Provider client={trpcClient} queryClient={queryClient}>
|
|
81
|
+
{children}
|
|
82
|
+
</api.Provider>
|
|
83
|
+
</QueryClientProvider>
|
|
84
|
+
)
|
|
85
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { defaultShouldDehydrateQuery, QueryClient } from "@tanstack/react-query"
|
|
2
|
+
import superjson from "superjson"
|
|
3
|
+
|
|
4
|
+
export const createQueryClient = () =>
|
|
5
|
+
new QueryClient({
|
|
6
|
+
defaultOptions: {
|
|
7
|
+
queries: {
|
|
8
|
+
// With SSR, we usually want to set some default staleTime
|
|
9
|
+
// above 0 to avoid refetching immediately on the client
|
|
10
|
+
staleTime: 1000 * 30,
|
|
11
|
+
},
|
|
12
|
+
dehydrate: {
|
|
13
|
+
serializeData: superjson.serialize,
|
|
14
|
+
shouldDehydrateQuery: (query) =>
|
|
15
|
+
defaultShouldDehydrateQuery(query) ||
|
|
16
|
+
query.state.status === "pending",
|
|
17
|
+
},
|
|
18
|
+
hydrate: {
|
|
19
|
+
deserializeData: superjson.deserialize,
|
|
20
|
+
},
|
|
21
|
+
},
|
|
22
|
+
})
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import "server-only"
|
|
2
|
+
|
|
3
|
+
import { createHydrationHelpers } from "@trpc/react-query/rsc"
|
|
4
|
+
import { headers } from "next/headers"
|
|
5
|
+
import React from "react"
|
|
6
|
+
|
|
7
|
+
import { createTRPCContext } from "@/server/api/init"
|
|
8
|
+
import { createCaller, type AppRouter } from "@/server/api/root"
|
|
9
|
+
|
|
10
|
+
import { createQueryClient } from "./query-client"
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when
|
|
14
|
+
* handling a tRPC call from a React Server Component.
|
|
15
|
+
*/
|
|
16
|
+
const createContext = React.cache(async () => {
|
|
17
|
+
const heads = new Headers(await headers())
|
|
18
|
+
heads.set("x-trpc-source", "rsc")
|
|
19
|
+
|
|
20
|
+
return createTRPCContext({
|
|
21
|
+
headers: heads,
|
|
22
|
+
})
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
const caller = createCaller(createContext)
|
|
26
|
+
const getQueryClient = React.cache(createQueryClient)
|
|
27
|
+
|
|
28
|
+
export const { trpc: api, HydrateClient } = createHydrationHelpers<AppRouter>(
|
|
29
|
+
caller,
|
|
30
|
+
getQueryClient
|
|
31
|
+
)
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* YOU PROBABLY DON'T NEED TO EDIT THIS FILE, UNLESS:
|
|
3
|
+
* 1. You want to modify request context (see Part 1).
|
|
4
|
+
* 2. You want to create a new middleware or type of procedure (see Part 3).
|
|
5
|
+
*
|
|
6
|
+
* TL;DR - This is where all the tRPC server stuff is created and plugged in.
|
|
7
|
+
* The pieces you will need to use are documented accordingly near the end.
|
|
8
|
+
*/
|
|
9
|
+
import { initTRPC } from "@trpc/server"
|
|
10
|
+
import superjson from "superjson"
|
|
11
|
+
import { z, ZodError } from "zod"
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* 1. CONTEXT
|
|
15
|
+
*
|
|
16
|
+
* This section defines the "contexts" that are available in the backend API.
|
|
17
|
+
*
|
|
18
|
+
* These allow you to access things when processing a request, like the database, the session, etc.
|
|
19
|
+
*
|
|
20
|
+
* This helper generates the "internals" for a tRPC context. The API handler and RSC clients each
|
|
21
|
+
* wrap this and provides the required context.
|
|
22
|
+
*
|
|
23
|
+
* @see https://trpc.io/docs/server/context
|
|
24
|
+
*/
|
|
25
|
+
export async function createTRPCContext(opts: { headers: Headers }) {
|
|
26
|
+
return {
|
|
27
|
+
...opts,
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 2. INITIALIZATION
|
|
33
|
+
*
|
|
34
|
+
* This is where the tRPC API is initialized, connecting the context and transformer. We also parse
|
|
35
|
+
* ZodErrors so that you get typesafety on the frontend if your procedure fails due to validation
|
|
36
|
+
* errors on the backend.
|
|
37
|
+
*/
|
|
38
|
+
const t = initTRPC.context<typeof createTRPCContext>().create({
|
|
39
|
+
transformer: superjson,
|
|
40
|
+
errorFormatter({ shape, error }) {
|
|
41
|
+
return {
|
|
42
|
+
...shape,
|
|
43
|
+
data: {
|
|
44
|
+
...shape.data,
|
|
45
|
+
zodError:
|
|
46
|
+
error.cause instanceof ZodError ? z.treeifyError(error.cause) : null,
|
|
47
|
+
},
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Create a server-side caller.
|
|
54
|
+
*
|
|
55
|
+
* @see https://trpc.io/docs/server/server-side-calls
|
|
56
|
+
*/
|
|
57
|
+
export const createCallerFactory = t.createCallerFactory
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 3. ROUTER & PROCEDURE (THE IMPORTANT BIT)
|
|
61
|
+
*
|
|
62
|
+
* These are the pieces you use to build your tRPC API. You should import these a lot in the
|
|
63
|
+
* "/src/server/api/routers" directory.
|
|
64
|
+
*/
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* This is how you create new routers and sub-routers in your tRPC API.
|
|
68
|
+
*
|
|
69
|
+
* @see https://trpc.io/docs/router
|
|
70
|
+
*/
|
|
71
|
+
export const createTRPCRouter = t.router
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Middleware for timing procedure execution and adding an artificial delay in development.
|
|
75
|
+
*
|
|
76
|
+
* You can remove this if you don't like it, but it can help catch unwanted waterfalls by simulating
|
|
77
|
+
* network latency that would occur in production but not in local development.
|
|
78
|
+
*/
|
|
79
|
+
const timingMiddleware = t.middleware(async ({ next, path }) => {
|
|
80
|
+
const start = Date.now()
|
|
81
|
+
|
|
82
|
+
if (t._config.isDev) {
|
|
83
|
+
// artificial delay in dev
|
|
84
|
+
const waitMs = Math.floor(Math.random() * 400) + 100
|
|
85
|
+
await new Promise((resolve) => setTimeout(resolve, waitMs))
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const result = await next()
|
|
89
|
+
|
|
90
|
+
const end = Date.now()
|
|
91
|
+
console.log(`[tRPC] ${path} took ${end - start}ms to execute`)
|
|
92
|
+
|
|
93
|
+
return result
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Public (unauthenticated) procedure
|
|
98
|
+
*
|
|
99
|
+
* This is the base piece you use to build new queries and mutations on your tRPC API. It does not
|
|
100
|
+
* guarantee that a user querying is authorized, but you can still access user session data if they
|
|
101
|
+
* are logged in.
|
|
102
|
+
*/
|
|
103
|
+
export const publicProcedure = t.procedure.use(timingMiddleware)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { createCallerFactory, createTRPCRouter } from "@/server/api/init"
|
|
2
|
+
import { helloWorldRouter } from "@/server/api/routers/hello-world"
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* This is the primary router for your server.
|
|
6
|
+
*
|
|
7
|
+
* All routers added in /api/routers should be manually added here.
|
|
8
|
+
*/
|
|
9
|
+
export const appRouter = createTRPCRouter({
|
|
10
|
+
helloWorld: helloWorldRouter,
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
// Export type definition of API
|
|
14
|
+
export type AppRouter = typeof appRouter
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Create a server-side caller for the tRPC API.
|
|
18
|
+
* @example
|
|
19
|
+
* const trpc = createCaller(createContext);
|
|
20
|
+
* const res = await trpc.post.all();
|
|
21
|
+
* ^? Post[]
|
|
22
|
+
*/
|
|
23
|
+
export const createCaller = createCallerFactory(appRouter)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import z from "zod"
|
|
2
|
+
|
|
3
|
+
import { createTRPCRouter, publicProcedure } from "@/server/api/init"
|
|
4
|
+
|
|
5
|
+
export const helloWorldRouter = createTRPCRouter({
|
|
6
|
+
greeting: publicProcedure
|
|
7
|
+
.input(
|
|
8
|
+
z.object({
|
|
9
|
+
text: z.string(),
|
|
10
|
+
})
|
|
11
|
+
)
|
|
12
|
+
.query(({ input }) => {
|
|
13
|
+
return `Hello ${input.text}`
|
|
14
|
+
}),
|
|
15
|
+
})
|
package/LICENSE.md
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2025 Lasse Lammers
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
6
|
-
this software and associated documentation files (the "Software"), to deal in
|
|
7
|
-
the Software without restriction, including without limitation the rights to
|
|
8
|
-
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
|
9
|
-
the Software, and to permit persons to whom the Software is furnished to do so,
|
|
10
|
-
subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
17
|
-
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
18
|
-
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
19
|
-
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
20
|
-
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|