create-lacspace-app 2.4.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lib.js CHANGED
@@ -37,7 +37,8 @@ function resolveContext(options = {}) {
37
37
  const seg = raw.split(/[\\/]/).filter(Boolean).pop() ?? "my-app";
38
38
  const name = seg.toLowerCase().replace(/[^a-z0-9-_]/g, "-").replace(/^-+|-+$/g, "") || "my-app";
39
39
  const features = normalizeFeatures(options.features);
40
- const mode = options.mode === "dynamic" ? "dynamic" : "static";
40
+ let mode = options.mode === "dynamic" ? "dynamic" : "static";
41
+ if (mode === "static" && features.some((f) => f.requiresBackend)) mode = "dynamic";
41
42
  return { name, template, features, mode };
42
43
  }
43
44
  function normalizeFeatures(requested) {
@@ -2118,6 +2119,97 @@ var FEATURES = [
2118
2119
  "Run `npm run dev` and open http://localhost:3000/ask."
2119
2120
  ],
2120
2121
  learn: "https://developer.lacspace.com/packages/rag"
2122
+ },
2123
+ {
2124
+ key: "content",
2125
+ label: "Content / blog",
2126
+ description: "A markdown content section (/updates) for any template \u2014 plus an RSS feed and an llms.txt. Drop in .md files, get pages.",
2127
+ deps: {
2128
+ "@lacspace/markdown": "^1.1.0",
2129
+ "@lacspace/rss": "^1.4.0",
2130
+ "@lacspace/llms-txt": "^1.4.0"
2131
+ },
2132
+ files: (ctx) => ({
2133
+ "content/updates/welcome.md": contentSampleWelcome(ctx),
2134
+ "content/updates/building-in-public.md": contentSampleSecond(),
2135
+ "lib/content.ts": contentLib(),
2136
+ "app/updates/page.tsx": updatesListPage(),
2137
+ "app/updates/[slug]/page.tsx": updatePostPage(),
2138
+ "app/feed.xml/route.ts": feedRoute(),
2139
+ "app/llms.txt/route.ts": llmsRoute()
2140
+ }),
2141
+ nextSteps: [
2142
+ "Add markdown files to content/updates/ \u2014 each becomes a page at /updates/<name>.",
2143
+ "Run `npm run dev` and open http://localhost:3000/updates, /feed.xml and /llms.txt.",
2144
+ "Set NEXT_PUBLIC_SITE_URL in .env so the feed and llms.txt links are absolute."
2145
+ ],
2146
+ learn: "https://developer.lacspace.com/packages/markdown"
2147
+ },
2148
+ {
2149
+ key: "search",
2150
+ label: "Search",
2151
+ description: "Instant, keyless full-text search (BM25) over your markdown content \u2014 a search box + /search page + API route. No key, no service.",
2152
+ deps: {
2153
+ "@lacspace/rerank": "^1.0.0",
2154
+ "@lacspace/markdown": "^1.1.0"
2155
+ },
2156
+ files: () => ({
2157
+ "app/api/search/route.ts": searchRoute(),
2158
+ "components/search.tsx": searchBox(),
2159
+ "app/search/page.tsx": searchPage()
2160
+ }),
2161
+ nextSteps: [
2162
+ "Add markdown to content/ (e.g. the `content` add-on's content/updates/) \u2014 search indexes it automatically.",
2163
+ "Run `npm run dev` and open http://localhost:3000/search, or drop <Search /> into your header.",
2164
+ "Want semantic search? Upgrade to @lacspace/embeddings + @lacspace/vector (keyless-local via Ollama)."
2165
+ ],
2166
+ learn: "https://developer.lacspace.com/packages/rerank"
2167
+ },
2168
+ {
2169
+ key: "auth-pages",
2170
+ label: "Auth & account",
2171
+ description: "Account management on top of the built-in login/register: edit profile, change password, and TOTP two-factor auth (2FA) with backup codes. Full-stack.",
2172
+ requiresBackend: true,
2173
+ deps: {},
2174
+ files: () => ({ "app/account/settings/page.tsx": authSettingsPage() }),
2175
+ backend: (ctx) => ({
2176
+ deps: { "@lacspace/otp": "^1.2.0" },
2177
+ files: {
2178
+ "src/models/two-factor.ts": authTwoFactorModel(),
2179
+ "src/routes/account.ts": authAccountRoutes(ctx)
2180
+ },
2181
+ routes: [{ path: "/account", handler: "accountRoutes", auth: true, importLine: 'import accountRoutes from "./account.js";' }]
2182
+ }),
2183
+ nextSteps: [
2184
+ "Sign in, then open http://localhost:3000/account/settings.",
2185
+ "Enable 2FA: add the shown secret to an authenticator app (Google Authenticator, Authy\u2026), then verify.",
2186
+ "Backup codes are shown once on enable \u2014 store them somewhere safe."
2187
+ ],
2188
+ learn: "https://developer.lacspace.com/packages/otp"
2189
+ },
2190
+ {
2191
+ key: "analytics",
2192
+ label: "Analytics",
2193
+ description: "Privacy-first, cookieless web analytics: a tracker (@lacspace/analytics-lite), a collector that stores events in MongoDB, and a dashboard. Full-stack.",
2194
+ requiresBackend: true,
2195
+ deps: { "@lacspace/analytics-lite": "^1.1.0" },
2196
+ files: (ctx) => ({
2197
+ "components/analytics.tsx": analyticsComponent(ctx),
2198
+ "app/analytics/page.tsx": analyticsDashboard()
2199
+ }),
2200
+ backend: () => ({
2201
+ files: {
2202
+ "src/models/event.ts": analyticsEventModel(),
2203
+ "src/routes/events.ts": analyticsEventsRoutes()
2204
+ },
2205
+ routes: [{ path: "/events", handler: "eventRoutes", auth: false, importLine: 'import eventRoutes from "./events.js";' }]
2206
+ }),
2207
+ nextSteps: [
2208
+ "Add <Analytics /> to app/layout.tsx (inside <body>) to start tracking page views.",
2209
+ "Browse your site, then open http://localhost:3000/analytics (sign in) to see the dashboard.",
2210
+ "It's cookieless and stores no personal data \u2014 privacy-first by default."
2211
+ ],
2212
+ learn: "https://developer.lacspace.com/packages/analytics-lite"
2121
2213
  }
2122
2214
  ];
2123
2215
  var aiChatRoute = (_ctx) => `import { resolveConfig } from "@lacspace/providers";
@@ -5096,6 +5188,646 @@ var faqSection = (ctx) => {
5096
5188
  </div>
5097
5189
  </section>`;
5098
5190
  };
5191
+ var contentLib = () => `import fs from "node:fs";
5192
+ import path from "node:path";
5193
+ import { parseFrontmatter, markdownToHtml, excerpt } from "@lacspace/markdown";
5194
+
5195
+ // how this works: every .md file in content/updates/ becomes a post. Frontmatter
5196
+ // (title/date/description) is read with @lacspace/markdown; the body is rendered to
5197
+ // safe HTML (raw HTML in the source is escaped, so this is XSS-safe by construction).
5198
+ const DIR = path.join(process.cwd(), "content/updates");
5199
+
5200
+ export interface PostMeta { slug: string; title: string; date: string; description: string; }
5201
+ export interface Post extends PostMeta { html: string; }
5202
+
5203
+ function read(slug: string): Post | null {
5204
+ const file = path.join(DIR, slug + ".md");
5205
+ if (!fs.existsSync(file)) return null;
5206
+ const { data, content } = parseFrontmatter(fs.readFileSync(file, "utf8"));
5207
+ return {
5208
+ slug,
5209
+ title: String(data.title ?? slug),
5210
+ date: String(data.date ?? ""),
5211
+ description: String(data.description ?? excerpt(content, { length: 160 })),
5212
+ html: markdownToHtml(content, { headingIds: true, openLinksInNewTab: true }),
5213
+ };
5214
+ }
5215
+
5216
+ export function getAllPosts(): PostMeta[] {
5217
+ if (!fs.existsSync(DIR)) return [];
5218
+ return fs.readdirSync(DIR)
5219
+ .filter((f) => f.endsWith(".md"))
5220
+ .map((f) => read(f.replace(/\\.md$/, ""))!)
5221
+ .filter(Boolean)
5222
+ .sort((a, b) => (a.date < b.date ? 1 : -1));
5223
+ }
5224
+
5225
+ export function getPost(slug: string): Post | null {
5226
+ return read(slug);
5227
+ }
5228
+ `;
5229
+ var updatesListPage = () => `import Link from "next/link";
5230
+ import { site } from "@/lib/site";
5231
+ import { getAllPosts } from "@/lib/content";
5232
+
5233
+ export const metadata = site.meta({ title: "Updates", path: "/updates" });
5234
+
5235
+ export default function UpdatesPage() {
5236
+ const posts = getAllPosts();
5237
+ return (
5238
+ <main className="mx-auto max-w-3xl px-6 py-16">
5239
+ <h1 className="text-3xl font-bold">Updates</h1>
5240
+ <p className="mt-2 text-muted">News, notes and posts. <a href="/feed.xml" className="underline">RSS</a></p>
5241
+ {posts.length === 0 && (
5242
+ <p className="mt-8 text-muted">No posts yet \u2014 add a markdown file in <code>content/updates/</code>.</p>
5243
+ )}
5244
+ <ul className="mt-8 space-y-6">
5245
+ {posts.map((p) => (
5246
+ <li key={p.slug} className="border-b border-hairline pb-6">
5247
+ <Link href={\`/updates/\${p.slug}\`} className="text-xl font-semibold hover:underline">{p.title}</Link>
5248
+ {p.date && <p className="mt-1 text-sm text-muted">{p.date}</p>}
5249
+ <p className="mt-2 text-muted">{p.description}</p>
5250
+ </li>
5251
+ ))}
5252
+ </ul>
5253
+ </main>
5254
+ );
5255
+ }
5256
+ `;
5257
+ var updatePostPage = () => `import Link from "next/link";
5258
+ import { notFound } from "next/navigation";
5259
+ import { site } from "@/lib/site";
5260
+ import { getAllPosts, getPost } from "@/lib/content";
5261
+
5262
+ export function generateStaticParams() {
5263
+ return getAllPosts().map((p) => ({ slug: p.slug }));
5264
+ }
5265
+
5266
+ export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
5267
+ const { slug } = await params;
5268
+ const post = getPost(slug);
5269
+ return site.meta({ title: post?.title ?? "Updates", path: \`/updates/\${slug}\` });
5270
+ }
5271
+
5272
+ export default async function PostPage({ params }: { params: Promise<{ slug: string }> }) {
5273
+ const { slug } = await params;
5274
+ const post = getPost(slug);
5275
+ if (!post) notFound();
5276
+ return (
5277
+ <main className="mx-auto max-w-2xl px-6 py-16">
5278
+ <Link href="/updates" className="text-sm text-muted hover:underline">\u2190 Updates</Link>
5279
+ <h1 className="mt-4 text-3xl font-bold">{post.title}</h1>
5280
+ {post.date && <p className="mt-1 text-sm text-muted">{post.date}</p>}
5281
+ <article
5282
+ className="mt-8 leading-7 [&_h2]:mt-8 [&_h2]:text-2xl [&_h2]:font-bold [&_h3]:mt-6 [&_h3]:text-xl [&_h3]:font-semibold [&_p]:mt-4 [&_p]:text-muted [&_a]:underline [&_ul]:mt-4 [&_ul]:list-disc [&_ul]:pl-6 [&_li]:mt-1 [&_pre]:mt-4 [&_pre]:overflow-x-auto [&_pre]:rounded-xl [&_pre]:bg-surface [&_pre]:p-4 [&_pre]:text-sm [&_code]:text-sm"
5283
+ dangerouslySetInnerHTML={{ __html: post.html }}
5284
+ />
5285
+ </main>
5286
+ );
5287
+ }
5288
+ `;
5289
+ var feedRoute = () => `import { rssResponse } from "@lacspace/rss";
5290
+ import { getAllPosts } from "@/lib/content";
5291
+
5292
+ export const dynamic = "force-static";
5293
+
5294
+ export function GET() {
5295
+ const base = process.env.NEXT_PUBLIC_SITE_URL ?? "http://localhost:3000";
5296
+ const items = getAllPosts().map((p) => ({
5297
+ title: p.title,
5298
+ link: base + "/updates/" + p.slug,
5299
+ description: p.description,
5300
+ // Only pass a date the feed can parse (rfc822Date throws on bad input).
5301
+ date: p.date && !Number.isNaN(Date.parse(p.date)) ? p.date : undefined,
5302
+ }));
5303
+ return rssResponse(
5304
+ { title: "Updates", link: base, description: "The latest posts and updates.", feedUrl: base + "/feed.xml" },
5305
+ items,
5306
+ );
5307
+ }
5308
+ `;
5309
+ var llmsRoute = () => `import { llmsTxtFromPages } from "@lacspace/llms-txt";
5310
+ import { getAllPosts } from "@/lib/content";
5311
+
5312
+ export const dynamic = "force-static";
5313
+
5314
+ export function GET() {
5315
+ const base = process.env.NEXT_PUBLIC_SITE_URL ?? "http://localhost:3000";
5316
+ const txt = llmsTxtFromPages(
5317
+ getAllPosts().map((p) => ({ title: p.title, url: base + "/updates/" + p.slug, content: p.description, section: "Updates" })),
5318
+ { title: "Updates", summary: "A content index for large language models." },
5319
+ );
5320
+ return new Response(txt, { headers: { "content-type": "text/plain; charset=utf-8" } });
5321
+ }
5322
+ `;
5323
+ var contentSampleWelcome = (ctx) => `---
5324
+ title: Welcome to ${ctx.template.siteName}'s content section
5325
+ date: 2026-01-15
5326
+ description: This markdown file became a page automatically \u2014 here's how it works.
5327
+ ---
5328
+
5329
+ ## It just works
5330
+
5331
+ Drop any \\\`.md\\\` file into \\\`content/updates/\\\` and it becomes a page at \\\`/updates/<filename>\\\`, listed on \\\`/updates\\\`, and included in \\\`/feed.xml\\\` and \\\`/llms.txt\\\`.
5332
+
5333
+ - Frontmatter \\\`title\\\`, \\\`date\\\` and \\\`description\\\` are read automatically.
5334
+ - The body is rendered safely with \\\`@lacspace/markdown\\\` \u2014 raw HTML is escaped, so it's XSS-safe.
5335
+ - Delete this file when you're ready to write your own.
5336
+ `;
5337
+ var contentSampleSecond = () => `---
5338
+ title: Building in public
5339
+ date: 2026-01-10
5340
+ description: A second example post so the list and feed have something to show.
5341
+ ---
5342
+
5343
+ ## Why a content section?
5344
+
5345
+ Every product needs a place for changelog posts, announcements and notes. This one is
5346
+ Markdown-powered, needs no database, and ships an RSS feed and an \\\`llms.txt\\\` for free.
5347
+
5348
+ ### Add your own
5349
+
5350
+ 1. Create \\\`content/updates/my-post.md\\\`.
5351
+ 2. Add frontmatter (\\\`title\\\`, \\\`date\\\`, \\\`description\\\`).
5352
+ 3. Write. That's it \u2014 it appears at \\\`/updates/my-post\\\`.
5353
+ `;
5354
+ var searchRoute = () => `import fs from "node:fs";
5355
+ import path from "node:path";
5356
+ import { parseFrontmatter, toPlainText, excerpt } from "@lacspace/markdown";
5357
+ import { rerank } from "@lacspace/rerank";
5358
+
5359
+ // how this works: full-text search with BM25 ranking \u2014 no external service, no API
5360
+ // key, no Ollama. It scans your markdown at request time and ranks matches. (For a
5361
+ // big site, precompute the corpus at build time and cache it instead.)
5362
+ export const runtime = "nodejs";
5363
+ export const dynamic = "force-dynamic";
5364
+
5365
+ const ROOT = path.join(process.cwd(), "content");
5366
+ // Map a content/<dir>/ to the route it renders under.
5367
+ const SECTION: Record<string, string> = { updates: "/updates", posts: "/blog", docs: "/docs" };
5368
+
5369
+ interface Entry { id: string; title: string; url: string; text: string; }
5370
+
5371
+ function corpus(): Entry[] {
5372
+ if (!fs.existsSync(ROOT)) return [];
5373
+ const out: Entry[] = [];
5374
+ for (const dir of fs.readdirSync(ROOT)) {
5375
+ const full = path.join(ROOT, dir);
5376
+ if (!fs.statSync(full).isDirectory()) continue;
5377
+ const base = SECTION[dir] ?? "/" + dir;
5378
+ for (const file of fs.readdirSync(full)) {
5379
+ if (!file.endsWith(".md")) continue;
5380
+ const slug = file.replace(/\\.md$/, "");
5381
+ const { data, content } = parseFrontmatter(fs.readFileSync(path.join(full, file), "utf8"));
5382
+ out.push({ id: dir + "/" + slug, title: String(data.title ?? slug), url: base + "/" + slug, text: toPlainText(content) });
5383
+ }
5384
+ }
5385
+ return out;
5386
+ }
5387
+
5388
+ export async function GET(req: Request) {
5389
+ const q = new URL(req.url).searchParams.get("q")?.trim() ?? "";
5390
+ if (!q) return Response.json([]);
5391
+ const docs = corpus().map((e) => ({ id: e.id, text: e.title + "\\n" + e.text, metadata: { title: e.title, url: e.url } }));
5392
+ const hits = await rerank(q, docs, { method: "bm25", k: 8 });
5393
+ return Response.json(hits.map((h) => ({
5394
+ title: String(h.metadata?.title ?? ""),
5395
+ url: String(h.metadata?.url ?? "#"),
5396
+ snippet: excerpt(h.text.split("\\n").slice(1).join(" "), { length: 140 }),
5397
+ })));
5398
+ }
5399
+ `;
5400
+ var searchBox = () => `"use client";
5401
+ import { useState, useEffect, useRef } from "react";
5402
+
5403
+ interface Result { title: string; url: string; snippet: string; }
5404
+
5405
+ export function Search() {
5406
+ const [q, setQ] = useState("");
5407
+ const [results, setResults] = useState<Result[]>([]);
5408
+ const [open, setOpen] = useState(false);
5409
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
5410
+
5411
+ useEffect(() => {
5412
+ if (timer.current) clearTimeout(timer.current);
5413
+ if (!q.trim()) { setResults([]); return; }
5414
+ timer.current = setTimeout(async () => {
5415
+ const res = await fetch("/api/search?q=" + encodeURIComponent(q));
5416
+ setResults(await res.json());
5417
+ setOpen(true);
5418
+ }, 200);
5419
+ return () => { if (timer.current) clearTimeout(timer.current); };
5420
+ }, [q]);
5421
+
5422
+ return (
5423
+ <div className="relative w-full max-w-md">
5424
+ <input
5425
+ value={q}
5426
+ onChange={(e) => setQ(e.target.value)}
5427
+ onFocus={() => { if (results.length) setOpen(true); }}
5428
+ onBlur={() => setTimeout(() => setOpen(false), 150)}
5429
+ placeholder="Search\u2026"
5430
+ className="w-full rounded-xl border border-hairline bg-surface px-4 py-2 outline-none"
5431
+ />
5432
+ {open && results.length > 0 && (
5433
+ <ul className="absolute z-20 mt-2 w-full overflow-hidden rounded-xl border border-hairline bg-app shadow-lg">
5434
+ {results.map((r) => (
5435
+ <li key={r.url}>
5436
+ <a href={r.url} className="block px-4 py-3 transition hover:bg-surface">
5437
+ <p className="font-medium">{r.title}</p>
5438
+ <p className="mt-0.5 text-sm text-muted">{r.snippet}</p>
5439
+ </a>
5440
+ </li>
5441
+ ))}
5442
+ </ul>
5443
+ )}
5444
+ </div>
5445
+ );
5446
+ }
5447
+ `;
5448
+ var searchPage = () => `import { site } from "@/lib/site";
5449
+ import { Search } from "@/components/search";
5450
+
5451
+ export const metadata = site.meta({ title: "Search", path: "/search" });
5452
+
5453
+ export default function SearchPage() {
5454
+ return (
5455
+ <main className="mx-auto max-w-2xl px-6 py-16">
5456
+ <h1 className="text-3xl font-bold">Search</h1>
5457
+ <p className="mt-2 text-muted">Instant, keyless full-text search over your content.</p>
5458
+ <div className="mt-8"><Search /></div>
5459
+ </main>
5460
+ );
5461
+ }
5462
+ `;
5463
+ var authTwoFactorModel = () => `import mongoose from "mongoose";
5464
+ import { uuidv7 } from "@lacspace/id";
5465
+
5466
+ // how this works: a separate collection for 2FA so the base User model stays simple.
5467
+ // NOTE: the TOTP secret is stored as-is here \u2014 in production, encrypt it at rest with
5468
+ // @lacspace/crypto (encrypt/decrypt) using a key from your env.
5469
+ export interface TwoFactorDoc {
5470
+ _id: string;
5471
+ userId: string;
5472
+ secret: string;
5473
+ enabled: boolean;
5474
+ backupHashes: string[];
5475
+ createdAt: Date;
5476
+ updatedAt: Date;
5477
+ }
5478
+
5479
+ const schema = new mongoose.Schema<TwoFactorDoc>(
5480
+ {
5481
+ _id: { type: String, default: () => uuidv7() },
5482
+ userId: { type: String, required: true, unique: true, index: true },
5483
+ secret: { type: String, required: true },
5484
+ enabled: { type: Boolean, default: false },
5485
+ backupHashes: { type: [String], default: [] },
5486
+ },
5487
+ { timestamps: true },
5488
+ );
5489
+
5490
+ export const TwoFactor =
5491
+ (mongoose.models.TwoFactor as mongoose.Model<TwoFactorDoc>) ?? mongoose.model<TwoFactorDoc>("TwoFactor", schema);
5492
+ `;
5493
+ var authAccountRoutes = (ctx) => `import express from "express";
5494
+ import { hash, verify as verifyPassword } from "@lacspace/password";
5495
+ import { setupTotp, verifyTotp, generateBackupCodes, verifyBackupCode } from "@lacspace/otp";
5496
+ import { v } from "@lacspace/validate";
5497
+ import { asyncHandler, HttpError } from "../http.js";
5498
+ import { User } from "../models/user.js";
5499
+ import { TwoFactor } from "../models/two-factor.js";
5500
+
5501
+ // This whole group is mounted behind requireAuth (see routes/index.ts), so
5502
+ // req.user is always set here.
5503
+ const router = express.Router();
5504
+ const ISSUER = "${ctx.name}";
5505
+
5506
+ const ProfileInput = v.object({ name: v.string().min(2).max(80) });
5507
+ const PasswordInput = v.object({ currentPassword: v.string().min(1), newPassword: v.string().min(8).max(200) });
5508
+ const CodeInput = v.object({ code: v.string().min(6).max(12) });
5509
+
5510
+ // GET /account/2fa \u2014 is two-factor enabled?
5511
+ router.get("/2fa", asyncHandler(async (req, res) => {
5512
+ const tf = await TwoFactor.findOne({ userId: req.user!.sub });
5513
+ res.json({ enabled: Boolean(tf?.enabled) });
5514
+ }));
5515
+
5516
+ // PATCH /account/profile \u2014 update your display name.
5517
+ router.patch("/profile", asyncHandler(async (req, res) => {
5518
+ const { name } = ProfileInput.parse(req.body);
5519
+ const user = await User.findByIdAndUpdate(req.user!.sub, { $set: { name } }, { new: true });
5520
+ if (!user) throw new HttpError(404, "User not found");
5521
+ res.json({ id: String(user._id), name: user.name, email: user.email });
5522
+ }));
5523
+
5524
+ // POST /account/password \u2014 change your password (verifies the current one).
5525
+ router.post("/password", asyncHandler(async (req, res) => {
5526
+ const { currentPassword, newPassword } = PasswordInput.parse(req.body);
5527
+ const user = await User.findById(req.user!.sub);
5528
+ if (!user || !(await verifyPassword(currentPassword, user.passwordHash))) {
5529
+ throw new HttpError(401, "Current password is incorrect");
5530
+ }
5531
+ user.passwordHash = await hash(newPassword);
5532
+ await user.save();
5533
+ res.json({ ok: true });
5534
+ }));
5535
+
5536
+ // POST /account/2fa/setup \u2014 create a TOTP secret; show \`uri\` as a QR / \`secret\` to type.
5537
+ router.post("/2fa/setup", asyncHandler(async (req, res) => {
5538
+ const user = await User.findById(req.user!.sub);
5539
+ if (!user) throw new HttpError(404, "User not found");
5540
+ const { secret, uri } = setupTotp({ account: user.email, issuer: ISSUER });
5541
+ await TwoFactor.findOneAndUpdate(
5542
+ { userId: String(user._id) },
5543
+ { $set: { secret, enabled: false } },
5544
+ { upsert: true, new: true },
5545
+ );
5546
+ res.json({ secret, uri });
5547
+ }));
5548
+
5549
+ // POST /account/2fa/enable \u2014 verify a code, turn 2FA on, return one-time backup codes.
5550
+ router.post("/2fa/enable", asyncHandler(async (req, res) => {
5551
+ const { code } = CodeInput.parse(req.body);
5552
+ const tf = await TwoFactor.findOne({ userId: req.user!.sub });
5553
+ if (!tf) throw new HttpError(400, "Run 2FA setup first");
5554
+ if ((await verifyTotp(code, tf.secret, { window: 1 })) === null) throw new HttpError(401, "Invalid code");
5555
+ const { codes, hashes } = await generateBackupCodes(10);
5556
+ tf.enabled = true;
5557
+ tf.backupHashes = hashes;
5558
+ await tf.save();
5559
+ res.json({ enabled: true, backupCodes: codes });
5560
+ }));
5561
+
5562
+ // POST /account/2fa/disable \u2014 verify a TOTP or backup code, then turn 2FA off.
5563
+ router.post("/2fa/disable", asyncHandler(async (req, res) => {
5564
+ const { code } = CodeInput.parse(req.body);
5565
+ const tf = await TwoFactor.findOne({ userId: req.user!.sub });
5566
+ if (!tf || !tf.enabled) { res.json({ enabled: false }); return; }
5567
+ const ok = (await verifyTotp(code, tf.secret, { window: 1 })) !== null || (await verifyBackupCode(code, tf.backupHashes)) >= 0;
5568
+ if (!ok) throw new HttpError(401, "Invalid code");
5569
+ await TwoFactor.deleteOne({ userId: req.user!.sub });
5570
+ res.json({ enabled: false });
5571
+ }));
5572
+
5573
+ export default router;
5574
+ `;
5575
+ var authSettingsPage = () => `"use client";
5576
+ import { useEffect, useState } from "react";
5577
+ import { useRouter } from "next/navigation";
5578
+ import { getToken } from "@/lib/api";
5579
+
5580
+ const API = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:4000";
5581
+
5582
+ async function call<T>(path: string, body?: unknown, method = "POST"): Promise<T> {
5583
+ const token = getToken();
5584
+ const res = await fetch(API + path, {
5585
+ method,
5586
+ headers: { "Content-Type": "application/json", ...(token ? { Authorization: "Bearer " + token } : {}) },
5587
+ body: body === undefined ? undefined : JSON.stringify(body),
5588
+ });
5589
+ const data: unknown = await res.json().catch(() => ({}));
5590
+ if (!res.ok) throw new Error((data as { error?: string }).error ?? "Request failed");
5591
+ return data as T;
5592
+ }
5593
+ const msgOf = (e: unknown) => (e instanceof Error ? e.message : "Something went wrong");
5594
+ const field = "w-full rounded-xl border border-hairline bg-surface px-4 py-2 outline-none";
5595
+ const card = "rounded-2xl border border-hairline p-5 space-y-3";
5596
+ const btn = "rounded-full gradient-bg px-4 py-2 text-sm font-semibold on-accent";
5597
+
5598
+ export default function SettingsPage() {
5599
+ const router = useRouter();
5600
+ const [name, setName] = useState("");
5601
+ const [current, setCurrent] = useState("");
5602
+ const [next, setNext] = useState("");
5603
+ const [enabled, setEnabled] = useState(false);
5604
+ const [setup, setSetup] = useState<{ secret: string; uri: string } | null>(null);
5605
+ const [code, setCode] = useState("");
5606
+ const [backup, setBackup] = useState<string[] | null>(null);
5607
+ const [msg, setMsg] = useState<string | null>(null);
5608
+
5609
+ const flash = (m: string) => { setMsg(m); setTimeout(() => setMsg(null), 3000); };
5610
+
5611
+ useEffect(() => {
5612
+ if (!getToken()) { router.push("/login"); return; }
5613
+ call<{ enabled: boolean }>("/account/2fa", undefined, "GET").then((r) => setEnabled(r.enabled)).catch(() => {});
5614
+ }, [router]);
5615
+
5616
+ async function saveName(e: React.FormEvent) {
5617
+ e.preventDefault();
5618
+ try { await call("/account/profile", { name }, "PATCH"); flash("Profile updated"); } catch (err) { flash(msgOf(err)); }
5619
+ }
5620
+ async function savePassword(e: React.FormEvent) {
5621
+ e.preventDefault();
5622
+ try { await call("/account/password", { currentPassword: current, newPassword: next }); setCurrent(""); setNext(""); flash("Password changed"); } catch (err) { flash(msgOf(err)); }
5623
+ }
5624
+ async function begin2fa() {
5625
+ try { setSetup(await call<{ secret: string; uri: string }>("/account/2fa/setup")); } catch (err) { flash(msgOf(err)); }
5626
+ }
5627
+ async function enable2fa() {
5628
+ try { const r = await call<{ backupCodes: string[] }>("/account/2fa/enable", { code }); setBackup(r.backupCodes); setEnabled(true); setSetup(null); setCode(""); } catch (err) { flash(msgOf(err)); }
5629
+ }
5630
+ async function disable2fa() {
5631
+ const c = window.prompt("Enter a current 2FA code (or a backup code) to disable:");
5632
+ if (!c) return;
5633
+ try { await call("/account/2fa/disable", { code: c }); setEnabled(false); flash("2FA disabled"); } catch (err) { flash(msgOf(err)); }
5634
+ }
5635
+
5636
+ return (
5637
+ <main className="mx-auto max-w-lg space-y-6 px-6 py-16">
5638
+ <h1 className="text-2xl font-bold">Account settings</h1>
5639
+ {msg && <p className="rounded-xl border border-hairline bg-surface px-4 py-2 text-sm">{msg}</p>}
5640
+
5641
+ <form onSubmit={saveName} className={card}>
5642
+ <h2 className="font-semibold">Profile</h2>
5643
+ <input value={name} onChange={(e) => setName(e.target.value)} placeholder="New display name" className={field} />
5644
+ <button className={btn}>Save name</button>
5645
+ </form>
5646
+
5647
+ <form onSubmit={savePassword} className={card}>
5648
+ <h2 className="font-semibold">Change password</h2>
5649
+ <input type="password" value={current} onChange={(e) => setCurrent(e.target.value)} placeholder="Current password" className={field} />
5650
+ <input type="password" value={next} onChange={(e) => setNext(e.target.value)} placeholder="New password (min 8)" className={field} />
5651
+ <button className={btn}>Change password</button>
5652
+ </form>
5653
+
5654
+ <div className={card}>
5655
+ <h2 className="font-semibold">Two-factor authentication {enabled && <span className="text-green-500">\xB7 on</span>}</h2>
5656
+ {!enabled && !setup && <button onClick={begin2fa} className={btn}>Enable 2FA</button>}
5657
+ {!enabled && setup && (
5658
+ <div className="space-y-3">
5659
+ <p className="text-sm text-muted">Add this secret to your authenticator app (Google Authenticator, Authy\u2026):</p>
5660
+ <code className="block break-all rounded-lg bg-surface p-3 text-sm">{setup.secret}</code>
5661
+ <input value={code} onChange={(e) => setCode(e.target.value)} placeholder="6-digit code" className={field} />
5662
+ <button onClick={enable2fa} className={btn}>Verify & enable</button>
5663
+ </div>
5664
+ )}
5665
+ {enabled && <button onClick={disable2fa} className="rounded-full border border-hairline px-4 py-2 text-sm">Disable 2FA</button>}
5666
+ {backup && (
5667
+ <div className="mt-2 space-y-2">
5668
+ <p className="text-sm font-medium">Save these backup codes (shown once):</p>
5669
+ <ul className="grid grid-cols-2 gap-1 rounded-lg bg-surface p-3 font-mono text-sm">
5670
+ {backup.map((b) => <li key={b}>{b}</li>)}
5671
+ </ul>
5672
+ </div>
5673
+ )}
5674
+ </div>
5675
+ </main>
5676
+ );
5677
+ }
5678
+ `;
5679
+ var analyticsEventModel = () => `import mongoose from "mongoose";
5680
+ import { uuidv7 } from "@lacspace/id";
5681
+
5682
+ export interface EventDoc {
5683
+ _id: string;
5684
+ type: string;
5685
+ path: string;
5686
+ referrer: string;
5687
+ screen: string;
5688
+ sid: string;
5689
+ props: Record<string, unknown>;
5690
+ ts: Date;
5691
+ }
5692
+
5693
+ const schema = new mongoose.Schema<EventDoc>({
5694
+ _id: { type: String, default: () => uuidv7() },
5695
+ type: { type: String, default: "pageview", index: true },
5696
+ path: { type: String, default: "/" },
5697
+ referrer: { type: String, default: "" },
5698
+ screen: { type: String, default: "" },
5699
+ sid: { type: String, default: "" },
5700
+ props: { type: mongoose.Schema.Types.Mixed, default: {} },
5701
+ ts: { type: Date, default: Date.now, index: true },
5702
+ });
5703
+
5704
+ export const Event =
5705
+ (mongoose.models.Event as mongoose.Model<EventDoc>) ?? mongoose.model<EventDoc>("Event", schema);
5706
+ `;
5707
+ var analyticsEventsRoutes = () => `import express from "express";
5708
+ import { asyncHandler } from "../http.js";
5709
+ import { requireAuth } from "../middleware/auth.js";
5710
+ import { Event } from "../models/event.js";
5711
+
5712
+ const router = express.Router();
5713
+
5714
+ // POST /events \u2014 the tracker beacon posts here. Public + cookieless (no PII stored).
5715
+ router.post("/", asyncHandler(async (req, res) => {
5716
+ const b = (req.body ?? {}) as Record<string, unknown>;
5717
+ await Event.create({
5718
+ type: String(b.type ?? "pageview"),
5719
+ path: String(b.path ?? "/"),
5720
+ referrer: String(b.referrer ?? ""),
5721
+ screen: String(b.screen ?? ""),
5722
+ sid: String(b.sid ?? ""),
5723
+ props: b.props && typeof b.props === "object" ? (b.props as Record<string, unknown>) : {},
5724
+ });
5725
+ res.status(204).end();
5726
+ }));
5727
+
5728
+ // GET /events/summary \u2014 dashboard aggregates (protected: only signed-in owners).
5729
+ router.get("/summary", requireAuth, asyncHandler(async (_req, res) => {
5730
+ const since = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
5731
+ const [total, pageviews, topPaths, byDay] = await Promise.all([
5732
+ Event.countDocuments({}),
5733
+ Event.countDocuments({ type: "pageview" }),
5734
+ Event.aggregate([
5735
+ { $match: { type: "pageview" } },
5736
+ { $group: { _id: "$path", count: { $sum: 1 } } },
5737
+ { $sort: { count: -1 } },
5738
+ { $limit: 8 },
5739
+ ]),
5740
+ Event.aggregate([
5741
+ { $match: { ts: { $gte: since } } },
5742
+ { $group: { _id: { $dateToString: { format: "%Y-%m-%d", date: "$ts" } }, count: { $sum: 1 } } },
5743
+ { $sort: { _id: 1 } },
5744
+ ]),
5745
+ ]);
5746
+ res.json({
5747
+ total,
5748
+ pageviews,
5749
+ topPaths: topPaths.map((p: { _id: string; count: number }) => ({ path: p._id, count: p.count })),
5750
+ byDay: byDay.map((d: { _id: string; count: number }) => ({ day: d._id, count: d.count })),
5751
+ });
5752
+ }));
5753
+
5754
+ export default router;
5755
+ `;
5756
+ var analyticsComponent = (ctx) => `"use client";
5757
+ import { useEffect } from "react";
5758
+ import { createAnalytics } from "@lacspace/analytics-lite";
5759
+
5760
+ // how this works: cookieless, privacy-first tracking. It POSTs page views + events to
5761
+ // your backend /events collector (stored in MongoDB). No cookies, no localStorage, no
5762
+ // personal data. Respects the browser's Do-Not-Track.
5763
+ const ENDPOINT = (process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:4000") + "/events";
5764
+
5765
+ export function Analytics() {
5766
+ useEffect(() => {
5767
+ const a = createAnalytics({ endpoint: ENDPOINT, siteId: ${JSON.stringify(ctx.name)}, respectDNT: true });
5768
+ a.pageview();
5769
+ return a.autoTrack();
5770
+ }, []);
5771
+ return null;
5772
+ }
5773
+ `;
5774
+ var analyticsDashboard = () => `"use client";
5775
+ import { useEffect, useState } from "react";
5776
+ import { useRouter } from "next/navigation";
5777
+ import { getToken } from "@/lib/api";
5778
+
5779
+ const API = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:4000";
5780
+
5781
+ interface Summary {
5782
+ total: number;
5783
+ pageviews: number;
5784
+ topPaths: { path: string; count: number }[];
5785
+ byDay: { day: string; count: number }[];
5786
+ }
5787
+
5788
+ export default function AnalyticsPage() {
5789
+ const router = useRouter();
5790
+ const [data, setData] = useState<Summary | null>(null);
5791
+ const [error, setError] = useState<string | null>(null);
5792
+
5793
+ useEffect(() => {
5794
+ const token = getToken();
5795
+ if (!token) { router.push("/login"); return; }
5796
+ fetch(API + "/events/summary", { headers: { Authorization: "Bearer " + token } })
5797
+ .then((r) => (r.ok ? r.json() : Promise.reject(new Error("Please sign in"))))
5798
+ .then(setData)
5799
+ .catch((e) => setError(e instanceof Error ? e.message : "Failed to load"));
5800
+ }, [router]);
5801
+
5802
+ if (error) return <main className="mx-auto max-w-3xl px-6 py-16 text-muted">{error}</main>;
5803
+ if (!data) return <main className="mx-auto max-w-3xl px-6 py-16 text-muted">Loading\u2026</main>;
5804
+ const max = Math.max(1, ...data.byDay.map((d) => d.count));
5805
+
5806
+ return (
5807
+ <main className="mx-auto max-w-3xl px-6 py-16">
5808
+ <h1 className="text-3xl font-bold">Analytics</h1>
5809
+ <p className="mt-1 text-muted">Cookieless, privacy-first \u2014 last 30 days.</p>
5810
+ <div className="mt-6 grid grid-cols-2 gap-4">
5811
+ <div className="rounded-2xl border border-hairline p-5"><p className="text-sm text-muted">Total events</p><p className="text-3xl font-bold">{data.total}</p></div>
5812
+ <div className="rounded-2xl border border-hairline p-5"><p className="text-sm text-muted">Page views</p><p className="text-3xl font-bold">{data.pageviews}</p></div>
5813
+ </div>
5814
+ <h2 className="mt-8 font-semibold">Top pages</h2>
5815
+ <ul className="mt-3 space-y-2">
5816
+ {data.topPaths.length === 0 && <li className="text-muted">No data yet \u2014 browse your site with &lt;Analytics/&gt; mounted.</li>}
5817
+ {data.topPaths.map((p) => (
5818
+ <li key={p.path} className="flex justify-between border-b border-hairline pb-2"><span className="truncate">{p.path}</span><span className="text-muted">{p.count}</span></li>
5819
+ ))}
5820
+ </ul>
5821
+ <h2 className="mt-8 font-semibold">Events per day</h2>
5822
+ <div className="mt-3 flex items-end gap-1" style={{ height: 120 }}>
5823
+ {data.byDay.map((d) => (
5824
+ <div key={d.day} className="flex-1 rounded-t" style={{ height: (d.count / max) * 100 + "%", backgroundColor: "var(--accent, #6366f1)" }} title={d.day + ": " + d.count} />
5825
+ ))}
5826
+ </div>
5827
+ </main>
5828
+ );
5829
+ }
5830
+ `;
5099
5831
  var scope = (ctx) => `@${ctx.name}`;
5100
5832
  var typesPkgJson = (ctx) => JSON.stringify({
5101
5833
  name: `${scope(ctx)}/types`,
@@ -5495,44 +6227,67 @@ function buildFullStack(ctx) {
5495
6227
  out[".gitignore"] = rootGitignore();
5496
6228
  out[".env.example"] = rootEnvExample(ctx);
5497
6229
  out["README.md"] = rootReadme(ctx);
6230
+ const envBase = out[".env.example"];
6231
+ const seen = new Set(
6232
+ (envBase.match(/^#?\s*([A-Z0-9_]+)=/gm) ?? []).map((l) => l.replace(/^#?\s*/, "").replace(/=.*/, ""))
6233
+ );
6234
+ const lines = [];
6235
+ for (const f of ctx.features) {
6236
+ const b = f.backend?.(ctx);
6237
+ if (!b?.env) continue;
6238
+ const fresh = Object.entries(b.env).filter(([name]) => !seen.has(name));
6239
+ if (!fresh.length) continue;
6240
+ lines.push("", `# --- ${f.label} (${f.key}) ---`);
6241
+ for (const [name, comment] of fresh) {
6242
+ if (comment) lines.push(`# ${comment}`);
6243
+ lines.push(`${name}=`);
6244
+ seen.add(name);
6245
+ }
6246
+ }
6247
+ if (lines.length) out[".env.example"] = envBase.replace(/\n?$/, "\n") + lines.join("\n") + "\n";
5498
6248
  return out;
5499
6249
  }
5500
- var backendPkgJson = (ctx) => JSON.stringify({
5501
- name: `${scope(ctx)}/backend`,
5502
- version: "0.1.0",
5503
- private: true,
5504
- type: "module",
5505
- main: "dist/index.js",
5506
- scripts: {
5507
- dev: "tsx watch src/index.ts",
5508
- build: "tsc -p tsconfig.json",
5509
- start: "node dist/index.js",
5510
- typecheck: "tsc -p tsconfig.json --noEmit"
5511
- },
5512
- dependencies: {
5513
- express: "^4.21.2",
5514
- cors: "^2.8.5",
5515
- mongoose: "^8.9.0",
5516
- ioredis: "^5.4.2",
5517
- dotenv: "^16.4.7",
5518
- // ✨ Backend built on zero-dep @lacspace/* packages instead of the usual grab-bag.
5519
- "@lacspace/env": "^1.1.0",
5520
- "@lacspace/jwt": "^1.4.0",
5521
- "@lacspace/password": "^1.1.0",
5522
- "@lacspace/validate": "^1.1.0",
5523
- "@lacspace/id": "^1.1.0",
5524
- "@lacspace/rate-limit": "^1.2.0",
5525
- "@lacspace/cache": "^1.1.0",
5526
- [`${scope(ctx)}/types`]: "*"
5527
- },
5528
- devDependencies: {
5529
- typescript: "^5.7.0",
5530
- tsx: "^4.19.2",
5531
- "@types/node": "^22.10.0",
5532
- "@types/express": "^4.17.21",
5533
- "@types/cors": "^2.8.17"
5534
- }
5535
- }, null, 2) + "\n";
6250
+ var backendPkgJson = (ctx) => {
6251
+ const featureDeps = {};
6252
+ for (const f of ctx.features) Object.assign(featureDeps, f.backend?.(ctx)?.deps ?? {});
6253
+ return JSON.stringify({
6254
+ name: `${scope(ctx)}/backend`,
6255
+ version: "0.1.0",
6256
+ private: true,
6257
+ type: "module",
6258
+ main: "dist/index.js",
6259
+ scripts: {
6260
+ dev: "tsx watch src/index.ts",
6261
+ build: "tsc -p tsconfig.json",
6262
+ start: "node dist/index.js",
6263
+ typecheck: "tsc -p tsconfig.json --noEmit"
6264
+ },
6265
+ dependencies: {
6266
+ express: "^4.21.2",
6267
+ cors: "^2.8.5",
6268
+ mongoose: "^8.9.0",
6269
+ ioredis: "^5.4.2",
6270
+ dotenv: "^16.4.7",
6271
+ // ✨ Backend built on zero-dep @lacspace/* packages instead of the usual grab-bag.
6272
+ "@lacspace/env": "^1.1.0",
6273
+ "@lacspace/jwt": "^1.4.0",
6274
+ "@lacspace/password": "^1.1.0",
6275
+ "@lacspace/validate": "^1.1.0",
6276
+ "@lacspace/id": "^1.1.0",
6277
+ "@lacspace/rate-limit": "^1.2.0",
6278
+ "@lacspace/cache": "^1.1.0",
6279
+ ...featureDeps,
6280
+ [`${scope(ctx)}/types`]: "*"
6281
+ },
6282
+ devDependencies: {
6283
+ typescript: "^5.7.0",
6284
+ tsx: "^4.19.2",
6285
+ "@types/node": "^22.10.0",
6286
+ "@types/express": "^4.17.21",
6287
+ "@types/cors": "^2.8.17"
6288
+ }
6289
+ }, null, 2) + "\n";
6290
+ };
5536
6291
  var backendTsconfig = (ctx) => JSON.stringify({
5537
6292
  compilerOptions: {
5538
6293
  target: "ES2022",
@@ -5958,35 +6713,49 @@ router.delete("/:id", asyncHandler(async (req, res) => {
5958
6713
  export default router;
5959
6714
  `;
5960
6715
  var backendApp = (ctx) => `import express from "express";
5961
- import type { RequestHandler } from "express";
5962
6716
  import cors from "cors";
5963
- import { rateLimit, expressRateLimit } from "@lacspace/rate-limit";
5964
6717
  import { env } from "./env.js";
5965
6718
  import { errorHandler } from "./middleware/error.js";
5966
- import authRoutes from "./routes/auth.js";
5967
- import noteRoutes from "./routes/notes.js";
6719
+ import { registerRoutes } from "./routes/index.js";
5968
6720
 
5969
6721
  // how this works: assembles the Express app \u2014 CORS for the frontend, JSON parsing,
5970
- // a health check, the auth + notes routers, then the error handler LAST.
6722
+ // a health check, all route groups (see routes/index.ts), then the error handler LAST.
5971
6723
  export function createApp(): express.Express {
5972
6724
  const app = express();
5973
6725
 
5974
6726
  app.use(cors({ origin: env.CORS_ORIGIN.split(",").map((o) => o.trim()), credentials: true }));
5975
6727
  app.use(express.json());
5976
6728
 
5977
- // Brute-force protection on auth: 20 requests / minute / IP (@lacspace/rate-limit).
5978
- const authLimiter = expressRateLimit(rateLimit({ limit: 20, windowMs: 60_000 })) as unknown as RequestHandler;
5979
-
5980
6729
  app.get("/health", (_req, res) => { res.json({ ok: true, service: "${ctx.name}-api" }); });
5981
- app.use("/auth", authLimiter, authRoutes);
5982
- app.use("/notes", noteRoutes);
6730
+ registerRoutes(app);
5983
6731
 
5984
6732
  app.use(errorHandler);
5985
6733
  return app;
5986
6734
  }
5987
6735
  `;
6736
+ var backendRoutesIndex = (ctx) => {
6737
+ const featureRoutes = ctx.features.flatMap((f) => f.backend?.(ctx)?.routes ?? []);
6738
+ const needsAuth = featureRoutes.some((r) => r.auth);
6739
+ const importLines = featureRoutes.map((r) => r.importLine).join("\n");
6740
+ const mountLines = featureRoutes.map((r) => ` app.use(${JSON.stringify(r.path)}, ${r.auth ? "requireAuth, " : ""}${r.handler});`).join("\n");
6741
+ return `import type { Express, RequestHandler } from "express";
6742
+ import { rateLimit, expressRateLimit } from "@lacspace/rate-limit";
6743
+ ${needsAuth ? 'import { requireAuth } from "../middleware/auth.js";\n' : ""}import authRoutes from "./auth.js";
6744
+ import noteRoutes from "./notes.js";
6745
+ ${importLines ? importLines + "\n" : ""}
6746
+ // how this works: every route group is mounted here. Add a new resource by creating
6747
+ // a router in routes/ and adding one app.use(...) line below.
6748
+ export function registerRoutes(app: Express): void {
6749
+ // Brute-force protection on auth: 20 requests / minute / IP (@lacspace/rate-limit).
6750
+ const authLimiter = expressRateLimit(rateLimit({ limit: 20, windowMs: 60_000 })) as unknown as RequestHandler;
6751
+ app.use("/auth", authLimiter, authRoutes);
6752
+ app.use("/notes", noteRoutes);
6753
+ ${mountLines}
6754
+ }
6755
+ `;
6756
+ };
5988
6757
  function backendFiles(ctx) {
5989
- return {
6758
+ const files = {
5990
6759
  "backend/package.json": backendPkgJson(ctx),
5991
6760
  "backend/tsconfig.json": backendTsconfig(ctx),
5992
6761
  "backend/.gitignore": backendGitignore(),
@@ -6005,8 +6774,15 @@ function backendFiles(ctx) {
6005
6774
  "backend/src/models/user.ts": backendUserModel(),
6006
6775
  "backend/src/models/note.ts": backendNoteModel(),
6007
6776
  "backend/src/routes/auth.ts": backendAuthRoutes(ctx),
6008
- "backend/src/routes/notes.ts": backendNoteRoutes(ctx)
6777
+ "backend/src/routes/notes.ts": backendNoteRoutes(ctx),
6778
+ "backend/src/routes/index.ts": backendRoutesIndex(ctx)
6009
6779
  };
6780
+ for (const f of ctx.features) {
6781
+ const b = f.backend?.(ctx);
6782
+ if (!b?.files) continue;
6783
+ for (const [rel, content] of Object.entries(b.files)) files["backend/" + rel] = content;
6784
+ }
6785
+ return files;
6010
6786
  }
6011
6787
  var splitList = (s) => s.split(",").map((x) => x.trim()).filter(Boolean);
6012
6788
  function parseArgs(list) {