create-lacspace-app 2.3.0 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -0
- package/dist/index.js +962 -6
- package/dist/lib.cjs +962 -6
- package/dist/lib.d.cts +16 -0
- package/dist/lib.d.ts +16 -0
- package/dist/lib.js +962 -6
- package/package.json +1 -1
package/dist/lib.cjs
CHANGED
|
@@ -40,7 +40,8 @@ function resolveContext(options = {}) {
|
|
|
40
40
|
const seg = raw.split(/[\\/]/).filter(Boolean).pop() ?? "my-app";
|
|
41
41
|
const name = seg.toLowerCase().replace(/[^a-z0-9-_]/g, "-").replace(/^-+|-+$/g, "") || "my-app";
|
|
42
42
|
const features = normalizeFeatures(options.features);
|
|
43
|
-
|
|
43
|
+
const mode = options.mode === "dynamic" ? "dynamic" : "static";
|
|
44
|
+
return { name, template, features, mode };
|
|
44
45
|
}
|
|
45
46
|
function normalizeFeatures(requested) {
|
|
46
47
|
if (!requested || requested.length === 0) return [];
|
|
@@ -1913,6 +1914,10 @@ Because posts are just Markdown files, you can:
|
|
|
1913
1914
|
Check the [first post](/blog/welcome) for the full Markdown reference.
|
|
1914
1915
|
`;
|
|
1915
1916
|
function buildFiles(ctx) {
|
|
1917
|
+
if (ctx.mode === "dynamic") return buildFullStack(ctx);
|
|
1918
|
+
return buildApp(ctx);
|
|
1919
|
+
}
|
|
1920
|
+
function buildApp(ctx) {
|
|
1916
1921
|
const isBlog = ctx.template.key === "blog";
|
|
1917
1922
|
const isDocs = ctx.template.key === "docs";
|
|
1918
1923
|
const files = {
|
|
@@ -5094,6 +5099,918 @@ var faqSection = (ctx) => {
|
|
|
5094
5099
|
</div>
|
|
5095
5100
|
</section>`;
|
|
5096
5101
|
};
|
|
5102
|
+
var scope = (ctx) => `@${ctx.name}`;
|
|
5103
|
+
var typesPkgJson = (ctx) => JSON.stringify({
|
|
5104
|
+
name: `${scope(ctx)}/types`,
|
|
5105
|
+
version: "0.1.0",
|
|
5106
|
+
private: true,
|
|
5107
|
+
// Type-only package: it ships a single .d.ts (no runtime code, nothing to build).
|
|
5108
|
+
types: "./index.d.ts",
|
|
5109
|
+
exports: { ".": { types: "./index.d.ts" } }
|
|
5110
|
+
}, null, 2) + "\n";
|
|
5111
|
+
var sharedTypes = () => `// Shared API contract \u2014 imported by BOTH the frontend and the backend, so the two
|
|
5112
|
+
// can never drift. These are TYPE-ONLY (no runtime code), so importing them adds
|
|
5113
|
+
// nothing to either bundle. Edit here once; both sides update. Use \`import type\`.
|
|
5114
|
+
|
|
5115
|
+
/** A user, as returned by the API (no password; dates are ISO strings). */
|
|
5116
|
+
export interface User {
|
|
5117
|
+
id: string;
|
|
5118
|
+
email: string;
|
|
5119
|
+
name: string;
|
|
5120
|
+
createdAt: string;
|
|
5121
|
+
}
|
|
5122
|
+
|
|
5123
|
+
/** The response from POST /auth/register and POST /auth/login. */
|
|
5124
|
+
export interface AuthResponse {
|
|
5125
|
+
token: string;
|
|
5126
|
+
user: User;
|
|
5127
|
+
}
|
|
5128
|
+
|
|
5129
|
+
/** The shape of an error response from the API. */
|
|
5130
|
+
export interface ApiError {
|
|
5131
|
+
error: string;
|
|
5132
|
+
fields?: Record<string, string>;
|
|
5133
|
+
}
|
|
5134
|
+
|
|
5135
|
+
/** The example CRUD resource. Rename "Note" to your real domain object. */
|
|
5136
|
+
export interface Note {
|
|
5137
|
+
id: string;
|
|
5138
|
+
title: string;
|
|
5139
|
+
body: string;
|
|
5140
|
+
userId: string;
|
|
5141
|
+
createdAt: string;
|
|
5142
|
+
updatedAt: string;
|
|
5143
|
+
}
|
|
5144
|
+
|
|
5145
|
+
export interface CreateNoteInput {
|
|
5146
|
+
title: string;
|
|
5147
|
+
body?: string;
|
|
5148
|
+
}
|
|
5149
|
+
|
|
5150
|
+
export interface UpdateNoteInput {
|
|
5151
|
+
title?: string;
|
|
5152
|
+
body?: string;
|
|
5153
|
+
}
|
|
5154
|
+
`;
|
|
5155
|
+
var rootPkgJson = (ctx) => JSON.stringify({
|
|
5156
|
+
name: ctx.name,
|
|
5157
|
+
version: "0.1.0",
|
|
5158
|
+
private: true,
|
|
5159
|
+
workspaces: ["types", "backend", "frontend"],
|
|
5160
|
+
scripts: {
|
|
5161
|
+
// Run the API and the frontend together (concurrently), colourised + kill-all.
|
|
5162
|
+
dev: 'concurrently -k -n api,web -c blue,magenta "npm:dev:api" "npm:dev:web"',
|
|
5163
|
+
"dev:api": `npm run dev --workspace ${scope(ctx)}/backend`,
|
|
5164
|
+
"dev:web": `npm run dev --workspace ${scope(ctx)}/frontend`,
|
|
5165
|
+
build: `npm run build --workspace ${scope(ctx)}/backend && npm run build --workspace ${scope(ctx)}/frontend`,
|
|
5166
|
+
start: 'concurrently -k -n api,web -c blue,magenta "npm:start:api" "npm:start:web"',
|
|
5167
|
+
"start:api": `npm run start --workspace ${scope(ctx)}/backend`,
|
|
5168
|
+
"start:web": `npm run start --workspace ${scope(ctx)}/frontend`,
|
|
5169
|
+
typecheck: `npm run typecheck --workspace ${scope(ctx)}/backend`
|
|
5170
|
+
},
|
|
5171
|
+
devDependencies: { concurrently: "^9.1.0" },
|
|
5172
|
+
engines: { node: ">=18" }
|
|
5173
|
+
}, null, 2) + "\n";
|
|
5174
|
+
var dockerCompose = (ctx) => `# Local infrastructure for ${ctx.name}. Start it with: docker compose up -d
|
|
5175
|
+
# Optional \u2014 the API also runs with NO Redis, and against any MongoDB (e.g. Atlas).
|
|
5176
|
+
services:
|
|
5177
|
+
mongo:
|
|
5178
|
+
image: mongo:7
|
|
5179
|
+
restart: unless-stopped
|
|
5180
|
+
ports:
|
|
5181
|
+
- "27017:27017"
|
|
5182
|
+
volumes:
|
|
5183
|
+
- mongo-data:/data/db
|
|
5184
|
+
redis:
|
|
5185
|
+
image: redis:7-alpine
|
|
5186
|
+
restart: unless-stopped
|
|
5187
|
+
ports:
|
|
5188
|
+
- "6379:6379"
|
|
5189
|
+
|
|
5190
|
+
volumes:
|
|
5191
|
+
mongo-data:
|
|
5192
|
+
`;
|
|
5193
|
+
var rootGitignore = () => `node_modules
|
|
5194
|
+
.env
|
|
5195
|
+
.env.local
|
|
5196
|
+
*.log
|
|
5197
|
+
.DS_Store
|
|
5198
|
+
dist
|
|
5199
|
+
.next
|
|
5200
|
+
`;
|
|
5201
|
+
var rootEnvExample = (ctx) => `# ${ctx.name} \u2014 ONE .env for the whole monorepo. Copy it: cp .env.example .env
|
|
5202
|
+
# The defaults below let the app run locally with zero changes.
|
|
5203
|
+
|
|
5204
|
+
# --- Backend ---
|
|
5205
|
+
NODE_ENV=development
|
|
5206
|
+
PORT=4000
|
|
5207
|
+
|
|
5208
|
+
# MongoDB. With Docker (docker compose up -d) the default just works. Or paste a
|
|
5209
|
+
# free MongoDB Atlas connection string here.
|
|
5210
|
+
MONGODB_URI=mongodb://localhost:27017/${ctx.name}
|
|
5211
|
+
|
|
5212
|
+
# Signs JWTs. In production generate a strong value: openssl rand -hex 32
|
|
5213
|
+
JWT_SECRET=dev-secret-change-me
|
|
5214
|
+
|
|
5215
|
+
# Redis is OPTIONAL \u2014 leave empty to use the in-memory cache fallback.
|
|
5216
|
+
# With Docker, set it to: redis://localhost:6379
|
|
5217
|
+
REDIS_URL=
|
|
5218
|
+
|
|
5219
|
+
# Who may call the API (the frontend origin). Comma-separate for multiple.
|
|
5220
|
+
CORS_ORIGIN=http://localhost:3000
|
|
5221
|
+
|
|
5222
|
+
# --- Frontend ---
|
|
5223
|
+
# Where the browser calls the API. Unset = http://localhost:4000 (local default).
|
|
5224
|
+
# NEXT_PUBLIC_API_URL=http://localhost:4000
|
|
5225
|
+
`;
|
|
5226
|
+
var rootReadme = (ctx) => `# ${ctx.name}
|
|
5227
|
+
|
|
5228
|
+
A full-stack app scaffolded with [create-lacspace-app](https://www.npmjs.com/package/create-lacspace-app) \u2014 a **${ctx.template.label}** frontend + a real backend, wired together.
|
|
5229
|
+
|
|
5230
|
+
\`\`\`
|
|
5231
|
+
${ctx.name}/
|
|
5232
|
+
\u251C\u2500 frontend/ Next.js 15 app (your UI) \u2014 talks to the API
|
|
5233
|
+
\u251C\u2500 backend/ Node \xB7 Express \xB7 MongoDB \xB7 Redis \xB7 TypeScript API
|
|
5234
|
+
\u251C\u2500 types/ Shared API types \u2014 imported by BOTH sides, so they can't drift
|
|
5235
|
+
\u2514\u2500 docker-compose.yml Mongo + Redis for local dev (optional)
|
|
5236
|
+
\`\`\`
|
|
5237
|
+
|
|
5238
|
+
## Quick start
|
|
5239
|
+
|
|
5240
|
+
\`\`\`bash
|
|
5241
|
+
cp .env.example .env # one env file for everything (sensible defaults)
|
|
5242
|
+
docker compose up -d # optional: starts MongoDB + Redis locally
|
|
5243
|
+
npm install # installs all three workspaces at once
|
|
5244
|
+
npm run dev # runs the API (:4000) and the frontend (:3000) together
|
|
5245
|
+
\`\`\`
|
|
5246
|
+
|
|
5247
|
+
Then open **http://localhost:3000** \u2192 visit **/register**, create an account, and you'll land on **/account** \u2014 a protected page that reads/writes the example "notes" resource through the API.
|
|
5248
|
+
|
|
5249
|
+
**No Docker?** Point \`MONGODB_URI\` at any MongoDB (a free [Atlas](https://www.mongodb.com/atlas) cluster works). Redis is optional \u2014 leave \`REDIS_URL\` empty and the API uses an in-memory cache instead.
|
|
5250
|
+
|
|
5251
|
+
## What's already built
|
|
5252
|
+
|
|
5253
|
+
- **Auth** \u2014 \`POST /auth/register\`, \`POST /auth/login\` (JWT), \`GET /auth/me\`. Passwords hashed with \`@lacspace/password\`, tokens signed/verified with \`@lacspace/jwt\`.
|
|
5254
|
+
- **Example CRUD** \u2014 \`/notes\` (list \xB7 create \xB7 read \xB7 update \xB7 delete), protected, per-user, with a per-user cache (Redis or in-memory) that busts on writes.
|
|
5255
|
+
- **Validation** \u2014 request bodies validated with \`@lacspace/validate\`; failures return a clean 400.
|
|
5256
|
+
- **Rate limiting** \u2014 auth endpoints throttled with \`@lacspace/rate-limit\`.
|
|
5257
|
+
- **Typed env** \u2014 \`@lacspace/env\` fails fast at boot if config is wrong.
|
|
5258
|
+
|
|
5259
|
+
Everything on the backend is built from zero-dependency \`@lacspace/*\` packages \u2192 https://lacspace.com/packages
|
|
5260
|
+
|
|
5261
|
+
## Make it yours
|
|
5262
|
+
|
|
5263
|
+
Rename the \`Note\` resource (in \`types/index.d.ts\`, \`backend/src/models/note.ts\`, \`backend/src/routes/notes.ts\`) to your real domain object, then follow the same pattern for more resources. The shared \`types/\` package keeps the frontend and backend in lock-step.
|
|
5264
|
+
`;
|
|
5265
|
+
var frontendApiClient = (ctx) => `import type { AuthResponse, User, Note, CreateNoteInput, ApiError } from "${scope(ctx)}/types";
|
|
5266
|
+
|
|
5267
|
+
// how this works: a tiny typed fetch wrapper around the backend API. The response
|
|
5268
|
+
// shapes come from the shared "${scope(ctx)}/types" package \u2014 the SAME types the
|
|
5269
|
+
// backend uses \u2014 so the client and server can never disagree about the contract.
|
|
5270
|
+
const BASE = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:4000";
|
|
5271
|
+
const TOKEN_KEY = "${ctx.name}_token";
|
|
5272
|
+
|
|
5273
|
+
export function getToken(): string | null {
|
|
5274
|
+
if (typeof window === "undefined") return null;
|
|
5275
|
+
try { return localStorage.getItem(TOKEN_KEY); } catch { return null; }
|
|
5276
|
+
}
|
|
5277
|
+
export function setToken(token: string | null): void {
|
|
5278
|
+
if (typeof window === "undefined") return;
|
|
5279
|
+
try { token ? localStorage.setItem(TOKEN_KEY, token) : localStorage.removeItem(TOKEN_KEY); } catch {}
|
|
5280
|
+
}
|
|
5281
|
+
|
|
5282
|
+
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
|
5283
|
+
const token = getToken();
|
|
5284
|
+
const res = await fetch(\`\${BASE}\${path}\`, {
|
|
5285
|
+
...init,
|
|
5286
|
+
headers: {
|
|
5287
|
+
"Content-Type": "application/json",
|
|
5288
|
+
...(token ? { Authorization: \`Bearer \${token}\` } : {}),
|
|
5289
|
+
...(init?.headers ?? {}),
|
|
5290
|
+
},
|
|
5291
|
+
});
|
|
5292
|
+
if (!res.ok) {
|
|
5293
|
+
let message = "Request failed";
|
|
5294
|
+
try { message = ((await res.json()) as ApiError).error ?? message; } catch {}
|
|
5295
|
+
throw new Error(message);
|
|
5296
|
+
}
|
|
5297
|
+
if (res.status === 204) return undefined as T;
|
|
5298
|
+
return (await res.json()) as T;
|
|
5299
|
+
}
|
|
5300
|
+
|
|
5301
|
+
export const api = {
|
|
5302
|
+
register: (input: { name: string; email: string; password: string }) =>
|
|
5303
|
+
request<AuthResponse>("/auth/register", { method: "POST", body: JSON.stringify(input) }),
|
|
5304
|
+
login: (input: { email: string; password: string }) =>
|
|
5305
|
+
request<AuthResponse>("/auth/login", { method: "POST", body: JSON.stringify(input) }),
|
|
5306
|
+
me: () => request<User>("/auth/me"),
|
|
5307
|
+
listNotes: () => request<Note[]>("/notes"),
|
|
5308
|
+
createNote: (input: CreateNoteInput) =>
|
|
5309
|
+
request<Note>("/notes", { method: "POST", body: JSON.stringify(input) }),
|
|
5310
|
+
deleteNote: (id: string) => request<void>(\`/notes/\${id}\`, { method: "DELETE" }),
|
|
5311
|
+
};
|
|
5312
|
+
`;
|
|
5313
|
+
var frontendLoginPage = () => `"use client";
|
|
5314
|
+
import { useState } from "react";
|
|
5315
|
+
import { useRouter } from "next/navigation";
|
|
5316
|
+
import Link from "next/link";
|
|
5317
|
+
import { api, setToken } from "@/lib/api";
|
|
5318
|
+
|
|
5319
|
+
// how this works: posts to the backend /auth/login, stores the returned JWT, then
|
|
5320
|
+
// redirects to /account. Every request after this sends the token automatically.
|
|
5321
|
+
export default function LoginPage() {
|
|
5322
|
+
const router = useRouter();
|
|
5323
|
+
const [email, setEmail] = useState("");
|
|
5324
|
+
const [password, setPassword] = useState("");
|
|
5325
|
+
const [error, setError] = useState<string | null>(null);
|
|
5326
|
+
const [busy, setBusy] = useState(false);
|
|
5327
|
+
|
|
5328
|
+
async function onSubmit(e: React.FormEvent) {
|
|
5329
|
+
e.preventDefault();
|
|
5330
|
+
setBusy(true); setError(null);
|
|
5331
|
+
try {
|
|
5332
|
+
const { token } = await api.login({ email, password });
|
|
5333
|
+
setToken(token);
|
|
5334
|
+
router.push("/account");
|
|
5335
|
+
} catch (err) {
|
|
5336
|
+
setError(err instanceof Error ? err.message : "Something went wrong");
|
|
5337
|
+
} finally { setBusy(false); }
|
|
5338
|
+
}
|
|
5339
|
+
|
|
5340
|
+
return (
|
|
5341
|
+
<main className="mx-auto flex min-h-[70vh] max-w-sm flex-col justify-center px-6">
|
|
5342
|
+
<h1 className="text-2xl font-bold">Welcome back</h1>
|
|
5343
|
+
<p className="mt-1 text-muted">Sign in to your account.</p>
|
|
5344
|
+
<form onSubmit={onSubmit} className="mt-6 space-y-4">
|
|
5345
|
+
<input value={email} onChange={(e) => setEmail(e.target.value)} type="email" required placeholder="you@example.com" className="w-full rounded-xl border border-hairline bg-surface px-4 py-3 outline-none" />
|
|
5346
|
+
<input value={password} onChange={(e) => setPassword(e.target.value)} type="password" required placeholder="Password" className="w-full rounded-xl border border-hairline bg-surface px-4 py-3 outline-none" />
|
|
5347
|
+
{error && <p className="text-sm text-red-400">{error}</p>}
|
|
5348
|
+
<button disabled={busy} className="w-full rounded-full gradient-bg px-4 py-3 font-semibold on-accent transition hover:opacity-90 disabled:opacity-60">{busy ? "Signing in\u2026" : "Sign in"}</button>
|
|
5349
|
+
</form>
|
|
5350
|
+
<p className="mt-4 text-sm text-muted">No account? <Link href="/register" className="underline">Create one</Link></p>
|
|
5351
|
+
</main>
|
|
5352
|
+
);
|
|
5353
|
+
}
|
|
5354
|
+
`;
|
|
5355
|
+
var frontendRegisterPage = () => `"use client";
|
|
5356
|
+
import { useState } from "react";
|
|
5357
|
+
import { useRouter } from "next/navigation";
|
|
5358
|
+
import Link from "next/link";
|
|
5359
|
+
import { api, setToken } from "@/lib/api";
|
|
5360
|
+
|
|
5361
|
+
// how this works: posts to /auth/register, stores the JWT, redirects to /account.
|
|
5362
|
+
export default function RegisterPage() {
|
|
5363
|
+
const router = useRouter();
|
|
5364
|
+
const [name, setName] = useState("");
|
|
5365
|
+
const [email, setEmail] = useState("");
|
|
5366
|
+
const [password, setPassword] = useState("");
|
|
5367
|
+
const [error, setError] = useState<string | null>(null);
|
|
5368
|
+
const [busy, setBusy] = useState(false);
|
|
5369
|
+
|
|
5370
|
+
async function onSubmit(e: React.FormEvent) {
|
|
5371
|
+
e.preventDefault();
|
|
5372
|
+
setBusy(true); setError(null);
|
|
5373
|
+
try {
|
|
5374
|
+
const { token } = await api.register({ name, email, password });
|
|
5375
|
+
setToken(token);
|
|
5376
|
+
router.push("/account");
|
|
5377
|
+
} catch (err) {
|
|
5378
|
+
setError(err instanceof Error ? err.message : "Something went wrong");
|
|
5379
|
+
} finally { setBusy(false); }
|
|
5380
|
+
}
|
|
5381
|
+
|
|
5382
|
+
return (
|
|
5383
|
+
<main className="mx-auto flex min-h-[70vh] max-w-sm flex-col justify-center px-6">
|
|
5384
|
+
<h1 className="text-2xl font-bold">Create your account</h1>
|
|
5385
|
+
<p className="mt-1 text-muted">It takes a few seconds.</p>
|
|
5386
|
+
<form onSubmit={onSubmit} className="mt-6 space-y-4">
|
|
5387
|
+
<input value={name} onChange={(e) => setName(e.target.value)} required placeholder="Your name" className="w-full rounded-xl border border-hairline bg-surface px-4 py-3 outline-none" />
|
|
5388
|
+
<input value={email} onChange={(e) => setEmail(e.target.value)} type="email" required placeholder="you@example.com" className="w-full rounded-xl border border-hairline bg-surface px-4 py-3 outline-none" />
|
|
5389
|
+
<input value={password} onChange={(e) => setPassword(e.target.value)} type="password" required minLength={8} placeholder="Password (min 8 chars)" className="w-full rounded-xl border border-hairline bg-surface px-4 py-3 outline-none" />
|
|
5390
|
+
{error && <p className="text-sm text-red-400">{error}</p>}
|
|
5391
|
+
<button disabled={busy} className="w-full rounded-full gradient-bg px-4 py-3 font-semibold on-accent transition hover:opacity-90 disabled:opacity-60">{busy ? "Creating\u2026" : "Create account"}</button>
|
|
5392
|
+
</form>
|
|
5393
|
+
<p className="mt-4 text-sm text-muted">Already have one? <Link href="/login" className="underline">Sign in</Link></p>
|
|
5394
|
+
</main>
|
|
5395
|
+
);
|
|
5396
|
+
}
|
|
5397
|
+
`;
|
|
5398
|
+
var frontendAccountPage = (ctx) => `"use client";
|
|
5399
|
+
import { useEffect, useState } from "react";
|
|
5400
|
+
import { useRouter } from "next/navigation";
|
|
5401
|
+
import { api, getToken, setToken } from "@/lib/api";
|
|
5402
|
+
import type { User, Note } from "${scope(ctx)}/types";
|
|
5403
|
+
|
|
5404
|
+
// how this works: a PROTECTED page. On mount it calls /auth/me with the stored
|
|
5405
|
+
// token; if that fails it bounces to /login. Notes are the example CRUD resource.
|
|
5406
|
+
export default function AccountPage() {
|
|
5407
|
+
const router = useRouter();
|
|
5408
|
+
const [user, setUser] = useState<User | null>(null);
|
|
5409
|
+
const [notes, setNotes] = useState<Note[]>([]);
|
|
5410
|
+
const [title, setTitle] = useState("");
|
|
5411
|
+
const [body, setBody] = useState("");
|
|
5412
|
+
const [error, setError] = useState<string | null>(null);
|
|
5413
|
+
|
|
5414
|
+
useEffect(() => {
|
|
5415
|
+
if (!getToken()) { router.push("/login"); return; }
|
|
5416
|
+
(async () => {
|
|
5417
|
+
try {
|
|
5418
|
+
setUser(await api.me());
|
|
5419
|
+
setNotes(await api.listNotes());
|
|
5420
|
+
} catch { setToken(null); router.push("/login"); }
|
|
5421
|
+
})();
|
|
5422
|
+
}, [router]);
|
|
5423
|
+
|
|
5424
|
+
async function addNote(e: React.FormEvent) {
|
|
5425
|
+
e.preventDefault();
|
|
5426
|
+
setError(null);
|
|
5427
|
+
try {
|
|
5428
|
+
const note = await api.createNote({ title, body });
|
|
5429
|
+
setNotes((prev) => [note, ...prev]);
|
|
5430
|
+
setTitle(""); setBody("");
|
|
5431
|
+
} catch (err) { setError(err instanceof Error ? err.message : "Failed to save"); }
|
|
5432
|
+
}
|
|
5433
|
+
async function remove(id: string) {
|
|
5434
|
+
await api.deleteNote(id);
|
|
5435
|
+
setNotes((prev) => prev.filter((n) => n.id !== id));
|
|
5436
|
+
}
|
|
5437
|
+
function signOut() { setToken(null); router.push("/login"); }
|
|
5438
|
+
|
|
5439
|
+
if (!user) return <main className="mx-auto max-w-2xl px-6 py-16 text-muted">Loading\u2026</main>;
|
|
5440
|
+
|
|
5441
|
+
return (
|
|
5442
|
+
<main className="mx-auto max-w-2xl px-6 py-16">
|
|
5443
|
+
<div className="flex items-center justify-between">
|
|
5444
|
+
<div>
|
|
5445
|
+
<h1 className="text-2xl font-bold">Hi, {user.name}</h1>
|
|
5446
|
+
<p className="text-muted">{user.email}</p>
|
|
5447
|
+
</div>
|
|
5448
|
+
<button onClick={signOut} className="rounded-full border border-hairline px-4 py-2 text-sm transition hover:bg-surface">Sign out</button>
|
|
5449
|
+
</div>
|
|
5450
|
+
|
|
5451
|
+
<form onSubmit={addNote} className="mt-8 space-y-3 rounded-2xl border border-hairline bg-surface p-5">
|
|
5452
|
+
<h2 className="font-semibold">Add a note</h2>
|
|
5453
|
+
<input value={title} onChange={(e) => setTitle(e.target.value)} required placeholder="Title" className="w-full rounded-xl border border-hairline bg-app px-4 py-2 outline-none" />
|
|
5454
|
+
<textarea value={body} onChange={(e) => setBody(e.target.value)} placeholder="Write something\u2026" rows={3} className="w-full rounded-xl border border-hairline bg-app px-4 py-2 outline-none" />
|
|
5455
|
+
{error && <p className="text-sm text-red-400">{error}</p>}
|
|
5456
|
+
<button className="rounded-full gradient-bg px-4 py-2 text-sm font-semibold on-accent">Save note</button>
|
|
5457
|
+
</form>
|
|
5458
|
+
|
|
5459
|
+
<ul className="mt-6 space-y-3">
|
|
5460
|
+
{notes.length === 0 && <li className="text-muted">No notes yet \u2014 add your first above.</li>}
|
|
5461
|
+
{notes.map((n) => (
|
|
5462
|
+
<li key={n.id} className="flex items-start justify-between rounded-2xl border border-hairline p-4">
|
|
5463
|
+
<div>
|
|
5464
|
+
<p className="font-medium">{n.title}</p>
|
|
5465
|
+
{n.body && <p className="mt-1 text-sm text-muted">{n.body}</p>}
|
|
5466
|
+
</div>
|
|
5467
|
+
<button onClick={() => remove(n.id)} className="shrink-0 text-sm text-muted transition hover:text-red-400">Delete</button>
|
|
5468
|
+
</li>
|
|
5469
|
+
))}
|
|
5470
|
+
</ul>
|
|
5471
|
+
</main>
|
|
5472
|
+
);
|
|
5473
|
+
}
|
|
5474
|
+
`;
|
|
5475
|
+
function buildFullStack(ctx) {
|
|
5476
|
+
const out = {};
|
|
5477
|
+
const s = scope(ctx);
|
|
5478
|
+
const app = buildApp(ctx);
|
|
5479
|
+
for (const [rel, content] of Object.entries(app)) out[`frontend/${rel}`] = content;
|
|
5480
|
+
const fpkg = JSON.parse(out["frontend/package.json"]);
|
|
5481
|
+
fpkg.name = `${s}/frontend`;
|
|
5482
|
+
fpkg.dependencies[`${s}/types`] = "*";
|
|
5483
|
+
out["frontend/package.json"] = JSON.stringify(fpkg, null, 2) + "\n";
|
|
5484
|
+
const fts = JSON.parse(out["frontend/tsconfig.json"]);
|
|
5485
|
+
fts.compilerOptions.paths[`${s}/types`] = ["../types/index.d.ts"];
|
|
5486
|
+
out["frontend/tsconfig.json"] = JSON.stringify(fts, null, 2) + "\n";
|
|
5487
|
+
const fenv = out["frontend/.env.example"] ?? "";
|
|
5488
|
+
out["frontend/.env.example"] = (fenv.endsWith("\n") || fenv === "" ? fenv : fenv + "\n") + "\n# The backend API base URL. Unset = http://localhost:4000 (local default).\n# NEXT_PUBLIC_API_URL=http://localhost:4000\n";
|
|
5489
|
+
out["frontend/lib/api.ts"] = frontendApiClient(ctx);
|
|
5490
|
+
out["frontend/app/login/page.tsx"] = frontendLoginPage();
|
|
5491
|
+
out["frontend/app/register/page.tsx"] = frontendRegisterPage();
|
|
5492
|
+
out["frontend/app/account/page.tsx"] = frontendAccountPage(ctx);
|
|
5493
|
+
Object.assign(out, backendFiles(ctx));
|
|
5494
|
+
out["types/package.json"] = typesPkgJson(ctx);
|
|
5495
|
+
out["types/index.d.ts"] = sharedTypes();
|
|
5496
|
+
out["package.json"] = rootPkgJson(ctx);
|
|
5497
|
+
out["docker-compose.yml"] = dockerCompose(ctx);
|
|
5498
|
+
out[".gitignore"] = rootGitignore();
|
|
5499
|
+
out[".env.example"] = rootEnvExample(ctx);
|
|
5500
|
+
out["README.md"] = rootReadme(ctx);
|
|
5501
|
+
return out;
|
|
5502
|
+
}
|
|
5503
|
+
var backendPkgJson = (ctx) => JSON.stringify({
|
|
5504
|
+
name: `${scope(ctx)}/backend`,
|
|
5505
|
+
version: "0.1.0",
|
|
5506
|
+
private: true,
|
|
5507
|
+
type: "module",
|
|
5508
|
+
main: "dist/index.js",
|
|
5509
|
+
scripts: {
|
|
5510
|
+
dev: "tsx watch src/index.ts",
|
|
5511
|
+
build: "tsc -p tsconfig.json",
|
|
5512
|
+
start: "node dist/index.js",
|
|
5513
|
+
typecheck: "tsc -p tsconfig.json --noEmit"
|
|
5514
|
+
},
|
|
5515
|
+
dependencies: {
|
|
5516
|
+
express: "^4.21.2",
|
|
5517
|
+
cors: "^2.8.5",
|
|
5518
|
+
mongoose: "^8.9.0",
|
|
5519
|
+
ioredis: "^5.4.2",
|
|
5520
|
+
dotenv: "^16.4.7",
|
|
5521
|
+
// ✨ Backend built on zero-dep @lacspace/* packages instead of the usual grab-bag.
|
|
5522
|
+
"@lacspace/env": "^1.1.0",
|
|
5523
|
+
"@lacspace/jwt": "^1.4.0",
|
|
5524
|
+
"@lacspace/password": "^1.1.0",
|
|
5525
|
+
"@lacspace/validate": "^1.1.0",
|
|
5526
|
+
"@lacspace/id": "^1.1.0",
|
|
5527
|
+
"@lacspace/rate-limit": "^1.2.0",
|
|
5528
|
+
"@lacspace/cache": "^1.1.0",
|
|
5529
|
+
[`${scope(ctx)}/types`]: "*"
|
|
5530
|
+
},
|
|
5531
|
+
devDependencies: {
|
|
5532
|
+
typescript: "^5.7.0",
|
|
5533
|
+
tsx: "^4.19.2",
|
|
5534
|
+
"@types/node": "^22.10.0",
|
|
5535
|
+
"@types/express": "^4.17.21",
|
|
5536
|
+
"@types/cors": "^2.8.17"
|
|
5537
|
+
}
|
|
5538
|
+
}, null, 2) + "\n";
|
|
5539
|
+
var backendTsconfig = (ctx) => JSON.stringify({
|
|
5540
|
+
compilerOptions: {
|
|
5541
|
+
target: "ES2022",
|
|
5542
|
+
module: "NodeNext",
|
|
5543
|
+
moduleResolution: "NodeNext",
|
|
5544
|
+
lib: ["ES2022"],
|
|
5545
|
+
esModuleInterop: true,
|
|
5546
|
+
allowSyntheticDefaultImports: true,
|
|
5547
|
+
strict: true,
|
|
5548
|
+
skipLibCheck: true,
|
|
5549
|
+
resolveJsonModule: true,
|
|
5550
|
+
outDir: "dist",
|
|
5551
|
+
rootDir: "src",
|
|
5552
|
+
sourceMap: true,
|
|
5553
|
+
types: ["node"],
|
|
5554
|
+
baseUrl: ".",
|
|
5555
|
+
paths: { [`${scope(ctx)}/types`]: ["../types/index.d.ts"] }
|
|
5556
|
+
},
|
|
5557
|
+
include: ["src/**/*"],
|
|
5558
|
+
exclude: ["node_modules", "dist"]
|
|
5559
|
+
}, null, 2) + "\n";
|
|
5560
|
+
var backendGitignore = () => `node_modules
|
|
5561
|
+
dist
|
|
5562
|
+
.env
|
|
5563
|
+
*.log
|
|
5564
|
+
`;
|
|
5565
|
+
var backendReadme = (ctx) => `# ${ctx.name} \u2014 API
|
|
5566
|
+
|
|
5567
|
+
Node \xB7 Express \xB7 MongoDB \xB7 Redis (optional) \xB7 TypeScript. Built on zero-dependency \`@lacspace/*\` packages.
|
|
5568
|
+
|
|
5569
|
+
Run it from the repo root with \`npm run dev\` (starts this API + the frontend). Standalone: \`npm run dev\` inside this folder.
|
|
5570
|
+
|
|
5571
|
+
## Endpoints
|
|
5572
|
+
|
|
5573
|
+
| Method | Path | Auth | Description |
|
|
5574
|
+
|--------|------------------|------|--------------------------------|
|
|
5575
|
+
| GET | \`/health\` | \u2014 | Liveness check |
|
|
5576
|
+
| POST | \`/auth/register\` | \u2014 | Create an account \u2192 JWT + user |
|
|
5577
|
+
| POST | \`/auth/login\` | \u2014 | Log in \u2192 JWT + user |
|
|
5578
|
+
| GET | \`/auth/me\` | \u2713 | The current user |
|
|
5579
|
+
| GET | \`/notes\` | \u2713 | List your notes (cached) |
|
|
5580
|
+
| POST | \`/notes\` | \u2713 | Create a note |
|
|
5581
|
+
| GET | \`/notes/:id\` | \u2713 | Read one note |
|
|
5582
|
+
| PATCH | \`/notes/:id\` | \u2713 | Update a note |
|
|
5583
|
+
| DELETE | \`/notes/:id\` | \u2713 | Delete a note |
|
|
5584
|
+
|
|
5585
|
+
Send \`Authorization: Bearer <token>\` for the \u2713 routes (you get the token from register/login).
|
|
5586
|
+
|
|
5587
|
+
## Layout
|
|
5588
|
+
|
|
5589
|
+
\`\`\`
|
|
5590
|
+
src/
|
|
5591
|
+
\u251C\u2500 index.ts boot: load env \u2192 connect Mongo \u2192 listen
|
|
5592
|
+
\u251C\u2500 load-env.ts loads the root .env (imported first)
|
|
5593
|
+
\u251C\u2500 env.ts typed, validated env (@lacspace/env)
|
|
5594
|
+
\u251C\u2500 app.ts the Express app (CORS, routes, error handler)
|
|
5595
|
+
\u251C\u2500 db.ts Mongoose connection
|
|
5596
|
+
\u251C\u2500 cache.ts Redis, or an in-memory fallback (@lacspace/cache)
|
|
5597
|
+
\u251C\u2500 http.ts HttpError + asyncHandler
|
|
5598
|
+
\u251C\u2500 validation.ts request schemas (@lacspace/validate)
|
|
5599
|
+
\u251C\u2500 middleware/ auth (@lacspace/jwt) + error handling
|
|
5600
|
+
\u251C\u2500 models/ Mongoose models (User, Note)
|
|
5601
|
+
\u2514\u2500 routes/ auth + notes (the example CRUD resource)
|
|
5602
|
+
\`\`\`
|
|
5603
|
+
`;
|
|
5604
|
+
var backendLoadEnv = () => `import { config } from "dotenv";
|
|
5605
|
+
import { resolve } from "node:path";
|
|
5606
|
+
|
|
5607
|
+
// how this works: the whole monorepo shares ONE .env at the repo root. When this
|
|
5608
|
+
// API runs via \`npm run dev\` its working directory is backend/, so the root .env
|
|
5609
|
+
// is one level up. This module is imported FIRST (before env.ts) so the variables
|
|
5610
|
+
// exist by the time anything reads them.
|
|
5611
|
+
config({ path: resolve(process.cwd(), "../.env") });
|
|
5612
|
+
config(); // also load backend/.env if you keep one (root values already set win)
|
|
5613
|
+
`;
|
|
5614
|
+
var backendEnv = (ctx) => `import { createEnv, str, port, oneOf } from "@lacspace/env";
|
|
5615
|
+
|
|
5616
|
+
// how this works: fail-fast, TYPED environment variables (@lacspace/env). Bad or
|
|
5617
|
+
// missing values throw at boot with a clear message. Sensible dev defaults mean it
|
|
5618
|
+
// runs with zero config against a local MongoDB; set real values in the root .env.
|
|
5619
|
+
export const env = createEnv({
|
|
5620
|
+
NODE_ENV: oneOf(["development", "production", "test"], { default: "development" }),
|
|
5621
|
+
PORT: port({ default: 4000 }),
|
|
5622
|
+
MONGODB_URI: str({ default: "mongodb://localhost:27017/${ctx.name}" }),
|
|
5623
|
+
JWT_SECRET: str({ default: "dev-secret-change-me" }),
|
|
5624
|
+
REDIS_URL: str({ optional: true }),
|
|
5625
|
+
CORS_ORIGIN: str({ default: "http://localhost:3000" }),
|
|
5626
|
+
});
|
|
5627
|
+
|
|
5628
|
+
if (env.NODE_ENV === "production" && env.JWT_SECRET === "dev-secret-change-me") {
|
|
5629
|
+
throw new Error("Set a strong JWT_SECRET in production (see .env.example).");
|
|
5630
|
+
}
|
|
5631
|
+
`;
|
|
5632
|
+
var backendIndex = (ctx) => `import "./load-env.js"; // MUST be first: fills process.env before anything reads it
|
|
5633
|
+
import { env } from "./env.js";
|
|
5634
|
+
import { connectDb } from "./db.js";
|
|
5635
|
+
import { createApp } from "./app.js";
|
|
5636
|
+
|
|
5637
|
+
// how this works: connect to MongoDB, build the Express app, then listen.
|
|
5638
|
+
async function main(): Promise<void> {
|
|
5639
|
+
await connectDb(env.MONGODB_URI);
|
|
5640
|
+
const app = createApp();
|
|
5641
|
+
app.listen(env.PORT, () => {
|
|
5642
|
+
console.log(\`\u{1F680} ${ctx.name} API ready on http://localhost:\${env.PORT}\`);
|
|
5643
|
+
});
|
|
5644
|
+
}
|
|
5645
|
+
|
|
5646
|
+
main().catch((err) => {
|
|
5647
|
+
console.error("Failed to start the API:", err);
|
|
5648
|
+
process.exit(1);
|
|
5649
|
+
});
|
|
5650
|
+
`;
|
|
5651
|
+
var backendDb = () => `import mongoose from "mongoose";
|
|
5652
|
+
|
|
5653
|
+
// how this works: opens the Mongoose connection. Call once at boot.
|
|
5654
|
+
export async function connectDb(uri: string): Promise<void> {
|
|
5655
|
+
mongoose.set("strictQuery", true);
|
|
5656
|
+
await mongoose.connect(uri);
|
|
5657
|
+
console.log("\u2714 MongoDB connected");
|
|
5658
|
+
}
|
|
5659
|
+
`;
|
|
5660
|
+
var backendCache = () => `import { createCache } from "@lacspace/cache";
|
|
5661
|
+
import { Redis } from "ioredis";
|
|
5662
|
+
import { env } from "./env.js";
|
|
5663
|
+
|
|
5664
|
+
// how this works: one cache interface, TWO backends. If REDIS_URL is set we use
|
|
5665
|
+
// Redis; otherwise we fall back to @lacspace/cache (zero-dep, in-memory) so the app
|
|
5666
|
+
// runs with NO Redis at all. The rest of the code doesn't care which is active.
|
|
5667
|
+
export interface Cache {
|
|
5668
|
+
get(key: string): Promise<string | null>;
|
|
5669
|
+
set(key: string, value: string, ttlSeconds?: number): Promise<void>;
|
|
5670
|
+
del(key: string): Promise<void>;
|
|
5671
|
+
readonly kind: "redis" | "memory";
|
|
5672
|
+
}
|
|
5673
|
+
|
|
5674
|
+
function redisCache(url: string): Cache {
|
|
5675
|
+
const client = new Redis(url, { maxRetriesPerRequest: 2 });
|
|
5676
|
+
client.on("error", (e: Error) => console.warn("\u26A0 Redis error:", e.message));
|
|
5677
|
+
return {
|
|
5678
|
+
kind: "redis",
|
|
5679
|
+
async get(key) { return client.get(key); },
|
|
5680
|
+
async set(key, value, ttl) { if (ttl) await client.set(key, value, "EX", ttl); else await client.set(key, value); },
|
|
5681
|
+
async del(key) { await client.del(key); },
|
|
5682
|
+
};
|
|
5683
|
+
}
|
|
5684
|
+
|
|
5685
|
+
function memoryCache(): Cache {
|
|
5686
|
+
const mem = createCache<string>({ max: 5000 });
|
|
5687
|
+
return {
|
|
5688
|
+
kind: "memory",
|
|
5689
|
+
async get(key) { return mem.get(key) ?? null; },
|
|
5690
|
+
async set(key, value, ttl) { mem.set(key, value, ttl ? ttl * 1000 : undefined); },
|
|
5691
|
+
async del(key) { mem.delete(key); },
|
|
5692
|
+
};
|
|
5693
|
+
}
|
|
5694
|
+
|
|
5695
|
+
export const cache: Cache = env.REDIS_URL ? redisCache(env.REDIS_URL) : memoryCache();
|
|
5696
|
+
console.log(\`\u2714 Cache: \${cache.kind}\${cache.kind === "memory" ? " (no REDIS_URL \u2014 in-memory fallback)" : ""}\`);
|
|
5697
|
+
`;
|
|
5698
|
+
var backendHttp = () => `import type { Request, Response, NextFunction, RequestHandler } from "express";
|
|
5699
|
+
|
|
5700
|
+
/** A simple HTTP error with a status code \u2014 throw it from any handler. */
|
|
5701
|
+
export class HttpError extends Error {
|
|
5702
|
+
status: number;
|
|
5703
|
+
constructor(status: number, message: string) {
|
|
5704
|
+
super(message);
|
|
5705
|
+
this.status = status;
|
|
5706
|
+
this.name = "HttpError";
|
|
5707
|
+
}
|
|
5708
|
+
}
|
|
5709
|
+
|
|
5710
|
+
// how this works: Express v4 doesn't catch rejected Promises from async handlers,
|
|
5711
|
+
// so wrap them \u2014 any thrown error is forwarded to the error middleware.
|
|
5712
|
+
export const asyncHandler =
|
|
5713
|
+
(fn: (req: Request, res: Response, next: NextFunction) => Promise<unknown>): RequestHandler =>
|
|
5714
|
+
(req, res, next) => { fn(req, res, next).catch(next); };
|
|
5715
|
+
`;
|
|
5716
|
+
var backendExpressTypes = () => `// Adds req.user (populated by requireAuth) to Express's Request type.
|
|
5717
|
+
import "express";
|
|
5718
|
+
|
|
5719
|
+
declare global {
|
|
5720
|
+
namespace Express {
|
|
5721
|
+
interface Request {
|
|
5722
|
+
user?: { sub: string; email: string; iat?: number; exp?: number; iss?: string };
|
|
5723
|
+
}
|
|
5724
|
+
}
|
|
5725
|
+
}
|
|
5726
|
+
|
|
5727
|
+
export {};
|
|
5728
|
+
`;
|
|
5729
|
+
var backendErrorMw = () => `import type { Request, Response, NextFunction } from "express";
|
|
5730
|
+
import { ValidationError } from "@lacspace/validate";
|
|
5731
|
+
import { HttpError } from "../http.js";
|
|
5732
|
+
|
|
5733
|
+
// how this works: ONE place that turns thrown errors into clean JSON responses.
|
|
5734
|
+
// Register it LAST (after all routes). Express identifies it by its 4 arguments.
|
|
5735
|
+
export function errorHandler(err: unknown, _req: Request, res: Response, _next: NextFunction): void {
|
|
5736
|
+
if (err instanceof ValidationError) {
|
|
5737
|
+
res.status(400).json({ error: "Validation failed", fields: err.flatten() });
|
|
5738
|
+
return;
|
|
5739
|
+
}
|
|
5740
|
+
if (err instanceof HttpError) {
|
|
5741
|
+
res.status(err.status).json({ error: err.message });
|
|
5742
|
+
return;
|
|
5743
|
+
}
|
|
5744
|
+
console.error(err);
|
|
5745
|
+
res.status(500).json({ error: "Internal server error" });
|
|
5746
|
+
}
|
|
5747
|
+
`;
|
|
5748
|
+
var backendAuthMw = (ctx) => `import type { RequestHandler } from "express";
|
|
5749
|
+
import { expressJwt } from "@lacspace/jwt";
|
|
5750
|
+
import { env } from "../env.js";
|
|
5751
|
+
|
|
5752
|
+
// how this works: verifies the "Authorization: Bearer <token>" header with
|
|
5753
|
+
// @lacspace/jwt and attaches the decoded payload to req.user (see express.d.ts).
|
|
5754
|
+
// Missing/invalid token \u2192 it responds 401 automatically. Put it on any route you
|
|
5755
|
+
// want protected: router.get("/secret", requireAuth, handler)
|
|
5756
|
+
// (@lacspace/jwt's middleware is framework-agnostic, so we cast it to Express's
|
|
5757
|
+
// RequestHandler \u2014 it's a standard (req, res, next) function underneath.)
|
|
5758
|
+
export const requireAuth = expressJwt(env.JWT_SECRET, { issuer: "${ctx.name}-api" }) as unknown as RequestHandler;
|
|
5759
|
+
`;
|
|
5760
|
+
var backendUserModel = () => `import mongoose from "mongoose";
|
|
5761
|
+
import { uuidv7 } from "@lacspace/id";
|
|
5762
|
+
|
|
5763
|
+
// how this works: the User fields. _id is a time-sortable UUID (@lacspace/id)
|
|
5764
|
+
// instead of an ObjectId, so ids are readable and orderable. We store only a
|
|
5765
|
+
// password HASH, never the raw password. (We DON'T extend mongoose.Document \u2014 that
|
|
5766
|
+
// would force _id to be an ObjectId; a plain interface lets _id be our string.)
|
|
5767
|
+
export interface UserDoc {
|
|
5768
|
+
_id: string;
|
|
5769
|
+
email: string;
|
|
5770
|
+
name: string;
|
|
5771
|
+
passwordHash: string;
|
|
5772
|
+
createdAt: Date;
|
|
5773
|
+
updatedAt: Date;
|
|
5774
|
+
}
|
|
5775
|
+
|
|
5776
|
+
const userSchema = new mongoose.Schema<UserDoc>(
|
|
5777
|
+
{
|
|
5778
|
+
_id: { type: String, default: () => uuidv7() },
|
|
5779
|
+
email: { type: String, required: true, unique: true, lowercase: true, trim: true },
|
|
5780
|
+
name: { type: String, required: true, trim: true },
|
|
5781
|
+
passwordHash: { type: String, required: true },
|
|
5782
|
+
},
|
|
5783
|
+
{ timestamps: true },
|
|
5784
|
+
);
|
|
5785
|
+
|
|
5786
|
+
export const User =
|
|
5787
|
+
(mongoose.models.User as mongoose.Model<UserDoc>) ?? mongoose.model<UserDoc>("User", userSchema);
|
|
5788
|
+
`;
|
|
5789
|
+
var backendNoteModel = () => `import mongoose from "mongoose";
|
|
5790
|
+
import { uuidv7 } from "@lacspace/id";
|
|
5791
|
+
|
|
5792
|
+
// how this works: the example CRUD resource. Rename "Note" to your real domain
|
|
5793
|
+
// object (Task, Post, Product\u2026) and add fields \u2014 the routes follow the same shape.
|
|
5794
|
+
// (Plain interface, not mongoose.Document, so _id can be our string UUID.)
|
|
5795
|
+
export interface NoteDoc {
|
|
5796
|
+
_id: string;
|
|
5797
|
+
title: string;
|
|
5798
|
+
body: string;
|
|
5799
|
+
userId: string;
|
|
5800
|
+
createdAt: Date;
|
|
5801
|
+
updatedAt: Date;
|
|
5802
|
+
}
|
|
5803
|
+
|
|
5804
|
+
const noteSchema = new mongoose.Schema<NoteDoc>(
|
|
5805
|
+
{
|
|
5806
|
+
_id: { type: String, default: () => uuidv7() },
|
|
5807
|
+
title: { type: String, required: true, trim: true },
|
|
5808
|
+
body: { type: String, default: "" },
|
|
5809
|
+
userId: { type: String, required: true, index: true },
|
|
5810
|
+
},
|
|
5811
|
+
{ timestamps: true },
|
|
5812
|
+
);
|
|
5813
|
+
|
|
5814
|
+
export const Note =
|
|
5815
|
+
(mongoose.models.Note as mongoose.Model<NoteDoc>) ?? mongoose.model<NoteDoc>("Note", noteSchema);
|
|
5816
|
+
`;
|
|
5817
|
+
var backendValidation = () => `import { v, type Infer } from "@lacspace/validate";
|
|
5818
|
+
|
|
5819
|
+
// how this works: Zod-like schemas (@lacspace/validate). .parse(body) throws a
|
|
5820
|
+
// ValidationError on bad input, which the error middleware turns into a clean 400
|
|
5821
|
+
// with per-field messages.
|
|
5822
|
+
export const RegisterInput = v.object({
|
|
5823
|
+
name: v.string().min(2).max(80),
|
|
5824
|
+
email: v.string().email(),
|
|
5825
|
+
password: v.string().min(8).max(200),
|
|
5826
|
+
});
|
|
5827
|
+
|
|
5828
|
+
export const LoginInput = v.object({
|
|
5829
|
+
email: v.string().email(),
|
|
5830
|
+
password: v.string().min(1),
|
|
5831
|
+
});
|
|
5832
|
+
|
|
5833
|
+
export const NoteInput = v.object({
|
|
5834
|
+
title: v.string().min(1).max(200),
|
|
5835
|
+
body: v.string().max(10_000).default(""),
|
|
5836
|
+
});
|
|
5837
|
+
|
|
5838
|
+
export type RegisterBody = Infer<typeof RegisterInput>;
|
|
5839
|
+
export type LoginBody = Infer<typeof LoginInput>;
|
|
5840
|
+
export type NoteBody = Infer<typeof NoteInput>;
|
|
5841
|
+
`;
|
|
5842
|
+
var backendAuthRoutes = (ctx) => `import express from "express";
|
|
5843
|
+
import { hash, verify as verifyPassword } from "@lacspace/password";
|
|
5844
|
+
import { sign } from "@lacspace/jwt";
|
|
5845
|
+
import { asyncHandler, HttpError } from "../http.js";
|
|
5846
|
+
import { requireAuth } from "../middleware/auth.js";
|
|
5847
|
+
import { User, type UserDoc } from "../models/user.js";
|
|
5848
|
+
import { env } from "../env.js";
|
|
5849
|
+
import { RegisterInput, LoginInput } from "../validation.js";
|
|
5850
|
+
import type { AuthResponse, User as UserDTO } from "${scope(ctx)}/types";
|
|
5851
|
+
|
|
5852
|
+
const ISSUER = "${ctx.name}-api";
|
|
5853
|
+
const WEEK = 60 * 60 * 24 * 7; // token lifetime, in seconds
|
|
5854
|
+
const router = express.Router();
|
|
5855
|
+
|
|
5856
|
+
function toDTO(u: UserDoc): UserDTO {
|
|
5857
|
+
return { id: String(u._id), email: u.email, name: u.name, createdAt: u.createdAt.toISOString() };
|
|
5858
|
+
}
|
|
5859
|
+
function tokenFor(u: UserDoc): Promise<string> {
|
|
5860
|
+
return sign({ sub: String(u._id), email: u.email }, env.JWT_SECRET, { expiresIn: WEEK, issuer: ISSUER });
|
|
5861
|
+
}
|
|
5862
|
+
|
|
5863
|
+
// POST /auth/register \u2014 create an account, return a JWT + the user.
|
|
5864
|
+
router.post("/register", asyncHandler(async (req, res) => {
|
|
5865
|
+
const { name, email, password } = RegisterInput.parse(req.body);
|
|
5866
|
+
if (await User.findOne({ email })) throw new HttpError(409, "That email is already registered");
|
|
5867
|
+
const passwordHash = await hash(password); // PBKDF2 via @lacspace/password
|
|
5868
|
+
const user = await User.create({ name, email, passwordHash });
|
|
5869
|
+
const out: AuthResponse = { token: await tokenFor(user), user: toDTO(user) };
|
|
5870
|
+
res.status(201).json(out);
|
|
5871
|
+
}));
|
|
5872
|
+
|
|
5873
|
+
// POST /auth/login \u2014 verify credentials, return a JWT + the user.
|
|
5874
|
+
router.post("/login", asyncHandler(async (req, res) => {
|
|
5875
|
+
const { email, password } = LoginInput.parse(req.body);
|
|
5876
|
+
const user = await User.findOne({ email });
|
|
5877
|
+
if (!user || !(await verifyPassword(password, user.passwordHash))) {
|
|
5878
|
+
throw new HttpError(401, "Invalid email or password");
|
|
5879
|
+
}
|
|
5880
|
+
const out: AuthResponse = { token: await tokenFor(user), user: toDTO(user) };
|
|
5881
|
+
res.json(out);
|
|
5882
|
+
}));
|
|
5883
|
+
|
|
5884
|
+
// GET /auth/me \u2014 the current user (requires a valid token).
|
|
5885
|
+
router.get("/me", requireAuth, asyncHandler(async (req, res) => {
|
|
5886
|
+
const user = await User.findById(req.user!.sub);
|
|
5887
|
+
if (!user) throw new HttpError(404, "User not found");
|
|
5888
|
+
res.json(toDTO(user));
|
|
5889
|
+
}));
|
|
5890
|
+
|
|
5891
|
+
export default router;
|
|
5892
|
+
`;
|
|
5893
|
+
var backendNoteRoutes = (ctx) => `import express from "express";
|
|
5894
|
+
import { asyncHandler, HttpError } from "../http.js";
|
|
5895
|
+
import { requireAuth } from "../middleware/auth.js";
|
|
5896
|
+
import { Note, type NoteDoc } from "../models/note.js";
|
|
5897
|
+
import { cache } from "../cache.js";
|
|
5898
|
+
import { NoteInput } from "../validation.js";
|
|
5899
|
+
import type { Note as NoteDTO } from "${scope(ctx)}/types";
|
|
5900
|
+
|
|
5901
|
+
const router = express.Router();
|
|
5902
|
+
router.use(requireAuth); // every /notes route requires a valid token
|
|
5903
|
+
|
|
5904
|
+
function toDTO(n: NoteDoc): NoteDTO {
|
|
5905
|
+
return {
|
|
5906
|
+
id: String(n._id),
|
|
5907
|
+
title: n.title,
|
|
5908
|
+
body: n.body,
|
|
5909
|
+
userId: String(n.userId),
|
|
5910
|
+
createdAt: n.createdAt.toISOString(),
|
|
5911
|
+
updatedAt: n.updatedAt.toISOString(),
|
|
5912
|
+
};
|
|
5913
|
+
}
|
|
5914
|
+
const listKey = (userId: string): string => \`notes:\${userId}\`;
|
|
5915
|
+
|
|
5916
|
+
// GET /notes \u2014 this user's notes. Cached for 30s (Redis or in-memory); every write
|
|
5917
|
+
// below busts the cache, so reads are fast but never stale after a change.
|
|
5918
|
+
router.get("/", asyncHandler(async (req, res) => {
|
|
5919
|
+
const userId = req.user!.sub;
|
|
5920
|
+
const cached = await cache.get(listKey(userId));
|
|
5921
|
+
if (cached) { res.json(JSON.parse(cached) as NoteDTO[]); return; }
|
|
5922
|
+
const notes = await Note.find({ userId }).sort({ createdAt: -1 });
|
|
5923
|
+
const dto = notes.map(toDTO);
|
|
5924
|
+
await cache.set(listKey(userId), JSON.stringify(dto), 30);
|
|
5925
|
+
res.json(dto);
|
|
5926
|
+
}));
|
|
5927
|
+
|
|
5928
|
+
// POST /notes \u2014 create a note.
|
|
5929
|
+
router.post("/", asyncHandler(async (req, res) => {
|
|
5930
|
+
const userId = req.user!.sub;
|
|
5931
|
+
const { title, body } = NoteInput.parse(req.body);
|
|
5932
|
+
const note = await Note.create({ title, body, userId });
|
|
5933
|
+
await cache.del(listKey(userId));
|
|
5934
|
+
res.status(201).json(toDTO(note));
|
|
5935
|
+
}));
|
|
5936
|
+
|
|
5937
|
+
// GET /notes/:id \u2014 one note (only if it's yours).
|
|
5938
|
+
router.get("/:id", asyncHandler(async (req, res) => {
|
|
5939
|
+
const note = await Note.findOne({ _id: req.params.id, userId: req.user!.sub });
|
|
5940
|
+
if (!note) throw new HttpError(404, "Note not found");
|
|
5941
|
+
res.json(toDTO(note));
|
|
5942
|
+
}));
|
|
5943
|
+
|
|
5944
|
+
// PATCH /notes/:id \u2014 update a note.
|
|
5945
|
+
router.patch("/:id", asyncHandler(async (req, res) => {
|
|
5946
|
+
const patch = NoteInput.partial().parse(req.body);
|
|
5947
|
+
const note = await Note.findOneAndUpdate({ _id: req.params.id, userId: req.user!.sub }, { $set: patch }, { new: true });
|
|
5948
|
+
if (!note) throw new HttpError(404, "Note not found");
|
|
5949
|
+
await cache.del(listKey(req.user!.sub));
|
|
5950
|
+
res.json(toDTO(note));
|
|
5951
|
+
}));
|
|
5952
|
+
|
|
5953
|
+
// DELETE /notes/:id \u2014 delete a note.
|
|
5954
|
+
router.delete("/:id", asyncHandler(async (req, res) => {
|
|
5955
|
+
const note = await Note.findOneAndDelete({ _id: req.params.id, userId: req.user!.sub });
|
|
5956
|
+
if (!note) throw new HttpError(404, "Note not found");
|
|
5957
|
+
await cache.del(listKey(req.user!.sub));
|
|
5958
|
+
res.status(204).end();
|
|
5959
|
+
}));
|
|
5960
|
+
|
|
5961
|
+
export default router;
|
|
5962
|
+
`;
|
|
5963
|
+
var backendApp = (ctx) => `import express from "express";
|
|
5964
|
+
import type { RequestHandler } from "express";
|
|
5965
|
+
import cors from "cors";
|
|
5966
|
+
import { rateLimit, expressRateLimit } from "@lacspace/rate-limit";
|
|
5967
|
+
import { env } from "./env.js";
|
|
5968
|
+
import { errorHandler } from "./middleware/error.js";
|
|
5969
|
+
import authRoutes from "./routes/auth.js";
|
|
5970
|
+
import noteRoutes from "./routes/notes.js";
|
|
5971
|
+
|
|
5972
|
+
// how this works: assembles the Express app \u2014 CORS for the frontend, JSON parsing,
|
|
5973
|
+
// a health check, the auth + notes routers, then the error handler LAST.
|
|
5974
|
+
export function createApp(): express.Express {
|
|
5975
|
+
const app = express();
|
|
5976
|
+
|
|
5977
|
+
app.use(cors({ origin: env.CORS_ORIGIN.split(",").map((o) => o.trim()), credentials: true }));
|
|
5978
|
+
app.use(express.json());
|
|
5979
|
+
|
|
5980
|
+
// Brute-force protection on auth: 20 requests / minute / IP (@lacspace/rate-limit).
|
|
5981
|
+
const authLimiter = expressRateLimit(rateLimit({ limit: 20, windowMs: 60_000 })) as unknown as RequestHandler;
|
|
5982
|
+
|
|
5983
|
+
app.get("/health", (_req, res) => { res.json({ ok: true, service: "${ctx.name}-api" }); });
|
|
5984
|
+
app.use("/auth", authLimiter, authRoutes);
|
|
5985
|
+
app.use("/notes", noteRoutes);
|
|
5986
|
+
|
|
5987
|
+
app.use(errorHandler);
|
|
5988
|
+
return app;
|
|
5989
|
+
}
|
|
5990
|
+
`;
|
|
5991
|
+
function backendFiles(ctx) {
|
|
5992
|
+
return {
|
|
5993
|
+
"backend/package.json": backendPkgJson(ctx),
|
|
5994
|
+
"backend/tsconfig.json": backendTsconfig(ctx),
|
|
5995
|
+
"backend/.gitignore": backendGitignore(),
|
|
5996
|
+
"backend/README.md": backendReadme(ctx),
|
|
5997
|
+
"backend/src/index.ts": backendIndex(ctx),
|
|
5998
|
+
"backend/src/load-env.ts": backendLoadEnv(),
|
|
5999
|
+
"backend/src/env.ts": backendEnv(ctx),
|
|
6000
|
+
"backend/src/db.ts": backendDb(),
|
|
6001
|
+
"backend/src/cache.ts": backendCache(),
|
|
6002
|
+
"backend/src/app.ts": backendApp(ctx),
|
|
6003
|
+
"backend/src/http.ts": backendHttp(),
|
|
6004
|
+
"backend/src/express.d.ts": backendExpressTypes(),
|
|
6005
|
+
"backend/src/validation.ts": backendValidation(),
|
|
6006
|
+
"backend/src/middleware/auth.ts": backendAuthMw(ctx),
|
|
6007
|
+
"backend/src/middleware/error.ts": backendErrorMw(),
|
|
6008
|
+
"backend/src/models/user.ts": backendUserModel(),
|
|
6009
|
+
"backend/src/models/note.ts": backendNoteModel(),
|
|
6010
|
+
"backend/src/routes/auth.ts": backendAuthRoutes(ctx),
|
|
6011
|
+
"backend/src/routes/notes.ts": backendNoteRoutes(ctx)
|
|
6012
|
+
};
|
|
6013
|
+
}
|
|
5097
6014
|
var splitList = (s) => s.split(",").map((x) => x.trim()).filter(Boolean);
|
|
5098
6015
|
function parseArgs(list) {
|
|
5099
6016
|
const a = { features: [], yes: false, install: true, git: true, pm: "npm", help: false };
|
|
@@ -5107,7 +6024,15 @@ function parseArgs(list) {
|
|
|
5107
6024
|
else if (arg === "--pm") a.pm = next();
|
|
5108
6025
|
else if (arg === "--theme" || arg === "--accent") a.theme = next();
|
|
5109
6026
|
else if (arg === "--with" || arg === "--features") a.features.push(...splitList(next()));
|
|
5110
|
-
else if (arg === "-
|
|
6027
|
+
else if (arg === "--fullstack" || arg === "--full-stack" || arg === "--dynamic") a.mode = "dynamic";
|
|
6028
|
+
else if (arg === "--static") a.mode = "static";
|
|
6029
|
+
else if (arg === "--mode") {
|
|
6030
|
+
const m = next().toLowerCase();
|
|
6031
|
+
a.mode = m === "dynamic" ? "dynamic" : "static";
|
|
6032
|
+
} else if (arg.startsWith("--mode=")) {
|
|
6033
|
+
const m = arg.slice(7).toLowerCase();
|
|
6034
|
+
a.mode = m === "dynamic" ? "dynamic" : "static";
|
|
6035
|
+
} else if (arg === "-h" || arg === "--help") a.help = true;
|
|
5111
6036
|
else if (arg.startsWith("--template=")) a.template = arg.slice(11);
|
|
5112
6037
|
else if (arg.startsWith("--theme=")) a.theme = arg.slice(8);
|
|
5113
6038
|
else if (arg.startsWith("--accent=")) a.theme = arg.slice(9);
|
|
@@ -5207,6 +6132,9 @@ ${TEMPLATES.map((t) => ` ${t.key.padEnd(10)} ${t.description}`).join("\n")}
|
|
|
5207
6132
|
|
|
5208
6133
|
${c("bold", "Options")}
|
|
5209
6134
|
-t, --template <key> Template (${TEMPLATES.map((t) => t.key).join(" | ")})
|
|
6135
|
+
--fullstack Full-stack monorepo: Next.js frontend + Node/Express/
|
|
6136
|
+
MongoDB/Redis backend (JWT auth + CRUD) + shared types
|
|
6137
|
+
${c("dim", "(alias --dynamic; default is --static, a single Next.js app)")}
|
|
5210
6138
|
--with <a,b> Feature add-ons, comma-separated (alias --features)
|
|
5211
6139
|
--theme <name|hex> Accent: a preset, a "#hex", or "from,to" (e.g. --theme lacspace)
|
|
5212
6140
|
--pm <npm|pnpm|yarn|bun> Package manager (default npm)
|
|
@@ -5598,6 +6526,7 @@ ${c("bold", c("magenta", "\u25C6 create-lacspace-app"))} ${c("dim", "\u2014 a go
|
|
|
5598
6526
|
`);
|
|
5599
6527
|
let name = args.name;
|
|
5600
6528
|
let templateKey = args.template;
|
|
6529
|
+
let mode = args.mode ?? "static";
|
|
5601
6530
|
const featureKeys = [...args.features];
|
|
5602
6531
|
if (!args.yes && process$1.stdin.isTTY) {
|
|
5603
6532
|
const rl = promises.createInterface({ input: process$1.stdin, output: process$1.stdout });
|
|
@@ -5614,6 +6543,18 @@ ${c("green", "?")} Template ${c("dim", "(1)")}: `)).trim() || "1";
|
|
|
5614
6543
|
const idx = /^\d+$/.test(ans) ? parseInt(ans, 10) - 1 : TEMPLATES.findIndex((t) => t.key === ans);
|
|
5615
6544
|
templateKey = TEMPLATES[idx]?.key ?? "personal";
|
|
5616
6545
|
}
|
|
6546
|
+
if (args.mode === void 0) {
|
|
6547
|
+
process$1.stdout.write(`
|
|
6548
|
+
What kind of app?
|
|
6549
|
+
`);
|
|
6550
|
+
process$1.stdout.write(` ${c("cyan", "1")}. ${c("bold", "Static / frontend only")} ${c("dim", "\u2014 a single Next.js app (SEO site, marketing, blog, docs). Fast, deploy anywhere.")}
|
|
6551
|
+
`);
|
|
6552
|
+
process$1.stdout.write(` ${c("cyan", "2")}. ${c("bold", "Dynamic / full-stack")} ${c("dim", "\u2014 frontend + a Node\xB7Express\xB7MongoDB\xB7Redis API with working auth & CRUD, wired together.")}
|
|
6553
|
+
`);
|
|
6554
|
+
const ans = (await rl.question(`
|
|
6555
|
+
${c("green", "?")} Type ${c("dim", "(1)")}: `)).trim() || "1";
|
|
6556
|
+
mode = ans === "2" || ans.toLowerCase().startsWith("dyn") || ans.toLowerCase().startsWith("full") ? "dynamic" : "static";
|
|
6557
|
+
}
|
|
5617
6558
|
if (featureKeys.length === 0) {
|
|
5618
6559
|
process$1.stdout.write(`
|
|
5619
6560
|
Add feature add-ons? ${c("dim", "(free & keyless \u2014 local AI by default)")}
|
|
@@ -5655,14 +6596,15 @@ ${c("green", "?")} Add features? ${c("dim", "(comma-separated numbers, or Enter
|
|
|
5655
6596
|
return;
|
|
5656
6597
|
}
|
|
5657
6598
|
const features = normalizeFeatures(featureKeys);
|
|
5658
|
-
const files = buildFiles({ name: projectName, template, features });
|
|
6599
|
+
const files = buildFiles({ name: projectName, template, features, mode });
|
|
5659
6600
|
for (const [rel, content] of Object.entries(files)) {
|
|
5660
6601
|
const full = path.join(dir, rel);
|
|
5661
6602
|
fs.mkdirSync(path.dirname(full), { recursive: true });
|
|
5662
6603
|
fs.writeFileSync(full, content);
|
|
5663
6604
|
}
|
|
6605
|
+
const shape = mode === "dynamic" ? " \xB7 full-stack" : "";
|
|
5664
6606
|
process$1.stdout.write(`
|
|
5665
|
-
${c("green", "\u2714")} Created ${c("bold", name)} ${c("dim", `(${template.label})`)}
|
|
6607
|
+
${c("green", "\u2714")} Created ${c("bold", name)} ${c("dim", `(${template.label}${shape})`)}
|
|
5666
6608
|
`);
|
|
5667
6609
|
if (features.length) process$1.stdout.write(` ${c("green", "\u2714")} Feature add-ons: ${features.map((f) => c("cyan", f.key)).join(", ")}
|
|
5668
6610
|
`);
|
|
@@ -5692,11 +6634,25 @@ ${c("bold", "Done! Next steps")}
|
|
|
5692
6634
|
`);
|
|
5693
6635
|
if (!args.install) process$1.stdout.write(` ${c("cyan", `${args.pm} install`)}
|
|
5694
6636
|
`);
|
|
5695
|
-
|
|
6637
|
+
if (mode === "dynamic") {
|
|
6638
|
+
process$1.stdout.write(` ${c("cyan", "cp .env.example .env")} ${c("dim", "\u2014 then, optionally:")} ${c("cyan", "docker compose up -d")} ${c("dim", "(Mongo + Redis)")}
|
|
5696
6639
|
`);
|
|
5697
|
-
|
|
6640
|
+
process$1.stdout.write(` ${c("cyan", run)} ${c("dim", "\u2014 runs the API (:4000) and the frontend (:3000) together")}
|
|
6641
|
+
`);
|
|
6642
|
+
process$1.stdout.write(`
|
|
6643
|
+
${c("dim", "backend \u2192")} ${c("cyan", "backend/src/")} ${c("dim", "(Express \xB7 MongoDB \xB7 Redis \xB7 JWT auth \xB7 example CRUD)")}
|
|
6644
|
+
`);
|
|
6645
|
+
process$1.stdout.write(` ${c("dim", "frontend \u2192")} ${c("cyan", "frontend/app/")} ${c("dim", "\xB7 shared API types \u2192")} ${c("cyan", "types/src/")}
|
|
6646
|
+
`);
|
|
6647
|
+
process$1.stdout.write(` ${c("dim", "No Docker? Point")} ${c("cyan", "MONGODB_URI")} ${c("dim", "at any MongoDB (e.g. free Atlas); Redis is optional.")}
|
|
6648
|
+
`);
|
|
6649
|
+
} else {
|
|
6650
|
+
process$1.stdout.write(` ${c("cyan", run)}
|
|
6651
|
+
`);
|
|
6652
|
+
process$1.stdout.write(`
|
|
5698
6653
|
Edit ${c("cyan", "lib/site.ts")} (your SEO config) and ${c("cyan", "app/page.tsx")}.
|
|
5699
6654
|
`);
|
|
6655
|
+
}
|
|
5700
6656
|
if (features.length) {
|
|
5701
6657
|
const hasAi = features.some((f) => f.key === "ai-chat" || f.key === "rag");
|
|
5702
6658
|
process$1.stdout.write(`
|