create-lacspace-app 2.5.0 → 2.7.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) {
@@ -2163,6 +2164,117 @@ var FEATURES = [
2163
2164
  "Want semantic search? Upgrade to @lacspace/embeddings + @lacspace/vector (keyless-local via Ollama)."
2164
2165
  ],
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"
2213
+ },
2214
+ {
2215
+ key: "payments",
2216
+ label: "Payments (Nepal)",
2217
+ description: "A checkout wired to eSewa & Khalti \u2014 orders, the signed eSewa flow (works in TEST with NO credentials), Khalti when keyed, integer-safe money. Full-stack.",
2218
+ requiresBackend: true,
2219
+ deps: {},
2220
+ files: () => ({
2221
+ "app/checkout/page.tsx": checkoutPage(),
2222
+ "app/checkout/success/page.tsx": checkoutSuccessPage(),
2223
+ "app/checkout/failed/page.tsx": checkoutFailedPage()
2224
+ }),
2225
+ backend: () => ({
2226
+ deps: { "@lacspace/esewa": "^1.2.0", "@lacspace/khalti": "^1.1.0", "@lacspace/money": "^1.1.0" },
2227
+ files: {
2228
+ "src/models/order.ts": ordersModel(),
2229
+ "src/routes/checkout.ts": checkoutRoutes()
2230
+ },
2231
+ routes: [{ path: "/checkout", handler: "checkoutRoutes", auth: true, importLine: 'import checkoutRoutes from "./checkout.js";' }],
2232
+ env: {
2233
+ ESEWA_MERCHANT_CODE: "eSewa merchant/product code (blank = eSewa TEST sandbox).",
2234
+ ESEWA_SECRET: "eSewa secret key (blank = TEST sandbox \u2014 payments work end-to-end in test).",
2235
+ KHALTI_SECRET: "Khalti secret key (required to enable Khalti; blank shows a 'configure Khalti' message)."
2236
+ }
2237
+ }),
2238
+ nextSteps: [
2239
+ "Sign in, then open http://localhost:3000/checkout and pay with eSewa \u2014 it works in TEST mode with no credentials.",
2240
+ "Enable Khalti by setting KHALTI_SECRET in .env (get a test key from https://khalti.com).",
2241
+ "Go live: set ESEWA_MERCHANT_CODE + ESEWA_SECRET (and a live KHALTI_SECRET)."
2242
+ ],
2243
+ learn: "https://developer.lacspace.com/packages/esewa"
2244
+ },
2245
+ {
2246
+ key: "email",
2247
+ label: "Email",
2248
+ description: "Transactional email \u2014 a ready mail service (@lacspace/mailer) with beautiful templates + address validation. Logs to the console until you add SMTP. Full-stack.",
2249
+ requiresBackend: true,
2250
+ deps: {},
2251
+ files: () => ({ "app/email-test/page.tsx": emailTestPage() }),
2252
+ backend: (ctx) => ({
2253
+ deps: {
2254
+ "@lacspace/mailer": "^1.2.0",
2255
+ "@lacspace/email-templates": "^1.1.0",
2256
+ "@lacspace/email-validate": "^1.1.0"
2257
+ },
2258
+ files: {
2259
+ "src/mail/mailer.ts": mailerLib(ctx),
2260
+ "src/routes/email.ts": emailRoutes()
2261
+ },
2262
+ routes: [{ path: "/email", handler: "emailRoutes", auth: true, importLine: 'import emailRoutes from "./email.js";' }],
2263
+ env: {
2264
+ SMTP_HOST: "SMTP host (blank in dev \u2014 emails are logged to the API console instead of sent).",
2265
+ SMTP_PORT: "SMTP port (default 587).",
2266
+ SMTP_SECURE: "true for implicit TLS on port 465; otherwise false.",
2267
+ SMTP_USER: "SMTP username.",
2268
+ SMTP_PASS: "SMTP password.",
2269
+ SMTP_FROM: 'Default From address, e.g. "Acme <no-reply@acme.com>".'
2270
+ }
2271
+ }),
2272
+ nextSteps: [
2273
+ "Sign in, then open http://localhost:3000/email-test and send yourself a sample email.",
2274
+ "With no SMTP_* set, the email is printed to the API console (dev). Set SMTP_* in .env to send for real.",
2275
+ "Reuse the helpers in backend/src/mail/mailer.ts: sendWelcome / sendVerify / sendReset."
2276
+ ],
2277
+ learn: "https://developer.lacspace.com/packages/mailer"
2166
2278
  }
2167
2279
  ];
2168
2280
  var aiChatRoute = (_ctx) => `import { resolveConfig } from "@lacspace/providers";
@@ -5413,6 +5525,733 @@ export default function SearchPage() {
5413
5525
  );
5414
5526
  }
5415
5527
  `;
5528
+ var authTwoFactorModel = () => `import mongoose from "mongoose";
5529
+ import { uuidv7 } from "@lacspace/id";
5530
+
5531
+ // how this works: a separate collection for 2FA so the base User model stays simple.
5532
+ // NOTE: the TOTP secret is stored as-is here \u2014 in production, encrypt it at rest with
5533
+ // @lacspace/crypto (encrypt/decrypt) using a key from your env.
5534
+ export interface TwoFactorDoc {
5535
+ _id: string;
5536
+ userId: string;
5537
+ secret: string;
5538
+ enabled: boolean;
5539
+ backupHashes: string[];
5540
+ createdAt: Date;
5541
+ updatedAt: Date;
5542
+ }
5543
+
5544
+ const schema = new mongoose.Schema<TwoFactorDoc>(
5545
+ {
5546
+ _id: { type: String, default: () => uuidv7() },
5547
+ userId: { type: String, required: true, unique: true, index: true },
5548
+ secret: { type: String, required: true },
5549
+ enabled: { type: Boolean, default: false },
5550
+ backupHashes: { type: [String], default: [] },
5551
+ },
5552
+ { timestamps: true },
5553
+ );
5554
+
5555
+ export const TwoFactor =
5556
+ (mongoose.models.TwoFactor as mongoose.Model<TwoFactorDoc>) ?? mongoose.model<TwoFactorDoc>("TwoFactor", schema);
5557
+ `;
5558
+ var authAccountRoutes = (ctx) => `import express from "express";
5559
+ import { hash, verify as verifyPassword } from "@lacspace/password";
5560
+ import { setupTotp, verifyTotp, generateBackupCodes, verifyBackupCode } from "@lacspace/otp";
5561
+ import { v } from "@lacspace/validate";
5562
+ import { asyncHandler, HttpError } from "../http.js";
5563
+ import { User } from "../models/user.js";
5564
+ import { TwoFactor } from "../models/two-factor.js";
5565
+
5566
+ // This whole group is mounted behind requireAuth (see routes/index.ts), so
5567
+ // req.user is always set here.
5568
+ const router = express.Router();
5569
+ const ISSUER = "${ctx.name}";
5570
+
5571
+ const ProfileInput = v.object({ name: v.string().min(2).max(80) });
5572
+ const PasswordInput = v.object({ currentPassword: v.string().min(1), newPassword: v.string().min(8).max(200) });
5573
+ const CodeInput = v.object({ code: v.string().min(6).max(12) });
5574
+
5575
+ // GET /account/2fa \u2014 is two-factor enabled?
5576
+ router.get("/2fa", asyncHandler(async (req, res) => {
5577
+ const tf = await TwoFactor.findOne({ userId: req.user!.sub });
5578
+ res.json({ enabled: Boolean(tf?.enabled) });
5579
+ }));
5580
+
5581
+ // PATCH /account/profile \u2014 update your display name.
5582
+ router.patch("/profile", asyncHandler(async (req, res) => {
5583
+ const { name } = ProfileInput.parse(req.body);
5584
+ const user = await User.findByIdAndUpdate(req.user!.sub, { $set: { name } }, { new: true });
5585
+ if (!user) throw new HttpError(404, "User not found");
5586
+ res.json({ id: String(user._id), name: user.name, email: user.email });
5587
+ }));
5588
+
5589
+ // POST /account/password \u2014 change your password (verifies the current one).
5590
+ router.post("/password", asyncHandler(async (req, res) => {
5591
+ const { currentPassword, newPassword } = PasswordInput.parse(req.body);
5592
+ const user = await User.findById(req.user!.sub);
5593
+ if (!user || !(await verifyPassword(currentPassword, user.passwordHash))) {
5594
+ throw new HttpError(401, "Current password is incorrect");
5595
+ }
5596
+ user.passwordHash = await hash(newPassword);
5597
+ await user.save();
5598
+ res.json({ ok: true });
5599
+ }));
5600
+
5601
+ // POST /account/2fa/setup \u2014 create a TOTP secret; show \`uri\` as a QR / \`secret\` to type.
5602
+ router.post("/2fa/setup", asyncHandler(async (req, res) => {
5603
+ const user = await User.findById(req.user!.sub);
5604
+ if (!user) throw new HttpError(404, "User not found");
5605
+ const { secret, uri } = setupTotp({ account: user.email, issuer: ISSUER });
5606
+ await TwoFactor.findOneAndUpdate(
5607
+ { userId: String(user._id) },
5608
+ { $set: { secret, enabled: false } },
5609
+ { upsert: true, new: true },
5610
+ );
5611
+ res.json({ secret, uri });
5612
+ }));
5613
+
5614
+ // POST /account/2fa/enable \u2014 verify a code, turn 2FA on, return one-time backup codes.
5615
+ router.post("/2fa/enable", asyncHandler(async (req, res) => {
5616
+ const { code } = CodeInput.parse(req.body);
5617
+ const tf = await TwoFactor.findOne({ userId: req.user!.sub });
5618
+ if (!tf) throw new HttpError(400, "Run 2FA setup first");
5619
+ if ((await verifyTotp(code, tf.secret, { window: 1 })) === null) throw new HttpError(401, "Invalid code");
5620
+ const { codes, hashes } = await generateBackupCodes(10);
5621
+ tf.enabled = true;
5622
+ tf.backupHashes = hashes;
5623
+ await tf.save();
5624
+ res.json({ enabled: true, backupCodes: codes });
5625
+ }));
5626
+
5627
+ // POST /account/2fa/disable \u2014 verify a TOTP or backup code, then turn 2FA off.
5628
+ router.post("/2fa/disable", asyncHandler(async (req, res) => {
5629
+ const { code } = CodeInput.parse(req.body);
5630
+ const tf = await TwoFactor.findOne({ userId: req.user!.sub });
5631
+ if (!tf || !tf.enabled) { res.json({ enabled: false }); return; }
5632
+ const ok = (await verifyTotp(code, tf.secret, { window: 1 })) !== null || (await verifyBackupCode(code, tf.backupHashes)) >= 0;
5633
+ if (!ok) throw new HttpError(401, "Invalid code");
5634
+ await TwoFactor.deleteOne({ userId: req.user!.sub });
5635
+ res.json({ enabled: false });
5636
+ }));
5637
+
5638
+ export default router;
5639
+ `;
5640
+ var authSettingsPage = () => `"use client";
5641
+ import { useEffect, useState } from "react";
5642
+ import { useRouter } from "next/navigation";
5643
+ import { getToken } from "@/lib/api";
5644
+
5645
+ const API = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:4000";
5646
+
5647
+ async function call<T>(path: string, body?: unknown, method = "POST"): Promise<T> {
5648
+ const token = getToken();
5649
+ const res = await fetch(API + path, {
5650
+ method,
5651
+ headers: { "Content-Type": "application/json", ...(token ? { Authorization: "Bearer " + token } : {}) },
5652
+ body: body === undefined ? undefined : JSON.stringify(body),
5653
+ });
5654
+ const data: unknown = await res.json().catch(() => ({}));
5655
+ if (!res.ok) throw new Error((data as { error?: string }).error ?? "Request failed");
5656
+ return data as T;
5657
+ }
5658
+ const msgOf = (e: unknown) => (e instanceof Error ? e.message : "Something went wrong");
5659
+ const field = "w-full rounded-xl border border-hairline bg-surface px-4 py-2 outline-none";
5660
+ const card = "rounded-2xl border border-hairline p-5 space-y-3";
5661
+ const btn = "rounded-full gradient-bg px-4 py-2 text-sm font-semibold on-accent";
5662
+
5663
+ export default function SettingsPage() {
5664
+ const router = useRouter();
5665
+ const [name, setName] = useState("");
5666
+ const [current, setCurrent] = useState("");
5667
+ const [next, setNext] = useState("");
5668
+ const [enabled, setEnabled] = useState(false);
5669
+ const [setup, setSetup] = useState<{ secret: string; uri: string } | null>(null);
5670
+ const [code, setCode] = useState("");
5671
+ const [backup, setBackup] = useState<string[] | null>(null);
5672
+ const [msg, setMsg] = useState<string | null>(null);
5673
+
5674
+ const flash = (m: string) => { setMsg(m); setTimeout(() => setMsg(null), 3000); };
5675
+
5676
+ useEffect(() => {
5677
+ if (!getToken()) { router.push("/login"); return; }
5678
+ call<{ enabled: boolean }>("/account/2fa", undefined, "GET").then((r) => setEnabled(r.enabled)).catch(() => {});
5679
+ }, [router]);
5680
+
5681
+ async function saveName(e: React.FormEvent) {
5682
+ e.preventDefault();
5683
+ try { await call("/account/profile", { name }, "PATCH"); flash("Profile updated"); } catch (err) { flash(msgOf(err)); }
5684
+ }
5685
+ async function savePassword(e: React.FormEvent) {
5686
+ e.preventDefault();
5687
+ try { await call("/account/password", { currentPassword: current, newPassword: next }); setCurrent(""); setNext(""); flash("Password changed"); } catch (err) { flash(msgOf(err)); }
5688
+ }
5689
+ async function begin2fa() {
5690
+ try { setSetup(await call<{ secret: string; uri: string }>("/account/2fa/setup")); } catch (err) { flash(msgOf(err)); }
5691
+ }
5692
+ async function enable2fa() {
5693
+ try { const r = await call<{ backupCodes: string[] }>("/account/2fa/enable", { code }); setBackup(r.backupCodes); setEnabled(true); setSetup(null); setCode(""); } catch (err) { flash(msgOf(err)); }
5694
+ }
5695
+ async function disable2fa() {
5696
+ const c = window.prompt("Enter a current 2FA code (or a backup code) to disable:");
5697
+ if (!c) return;
5698
+ try { await call("/account/2fa/disable", { code: c }); setEnabled(false); flash("2FA disabled"); } catch (err) { flash(msgOf(err)); }
5699
+ }
5700
+
5701
+ return (
5702
+ <main className="mx-auto max-w-lg space-y-6 px-6 py-16">
5703
+ <h1 className="text-2xl font-bold">Account settings</h1>
5704
+ {msg && <p className="rounded-xl border border-hairline bg-surface px-4 py-2 text-sm">{msg}</p>}
5705
+
5706
+ <form onSubmit={saveName} className={card}>
5707
+ <h2 className="font-semibold">Profile</h2>
5708
+ <input value={name} onChange={(e) => setName(e.target.value)} placeholder="New display name" className={field} />
5709
+ <button className={btn}>Save name</button>
5710
+ </form>
5711
+
5712
+ <form onSubmit={savePassword} className={card}>
5713
+ <h2 className="font-semibold">Change password</h2>
5714
+ <input type="password" value={current} onChange={(e) => setCurrent(e.target.value)} placeholder="Current password" className={field} />
5715
+ <input type="password" value={next} onChange={(e) => setNext(e.target.value)} placeholder="New password (min 8)" className={field} />
5716
+ <button className={btn}>Change password</button>
5717
+ </form>
5718
+
5719
+ <div className={card}>
5720
+ <h2 className="font-semibold">Two-factor authentication {enabled && <span className="text-green-500">\xB7 on</span>}</h2>
5721
+ {!enabled && !setup && <button onClick={begin2fa} className={btn}>Enable 2FA</button>}
5722
+ {!enabled && setup && (
5723
+ <div className="space-y-3">
5724
+ <p className="text-sm text-muted">Add this secret to your authenticator app (Google Authenticator, Authy\u2026):</p>
5725
+ <code className="block break-all rounded-lg bg-surface p-3 text-sm">{setup.secret}</code>
5726
+ <input value={code} onChange={(e) => setCode(e.target.value)} placeholder="6-digit code" className={field} />
5727
+ <button onClick={enable2fa} className={btn}>Verify & enable</button>
5728
+ </div>
5729
+ )}
5730
+ {enabled && <button onClick={disable2fa} className="rounded-full border border-hairline px-4 py-2 text-sm">Disable 2FA</button>}
5731
+ {backup && (
5732
+ <div className="mt-2 space-y-2">
5733
+ <p className="text-sm font-medium">Save these backup codes (shown once):</p>
5734
+ <ul className="grid grid-cols-2 gap-1 rounded-lg bg-surface p-3 font-mono text-sm">
5735
+ {backup.map((b) => <li key={b}>{b}</li>)}
5736
+ </ul>
5737
+ </div>
5738
+ )}
5739
+ </div>
5740
+ </main>
5741
+ );
5742
+ }
5743
+ `;
5744
+ var analyticsEventModel = () => `import mongoose from "mongoose";
5745
+ import { uuidv7 } from "@lacspace/id";
5746
+
5747
+ export interface EventDoc {
5748
+ _id: string;
5749
+ type: string;
5750
+ path: string;
5751
+ referrer: string;
5752
+ screen: string;
5753
+ sid: string;
5754
+ props: Record<string, unknown>;
5755
+ ts: Date;
5756
+ }
5757
+
5758
+ const schema = new mongoose.Schema<EventDoc>({
5759
+ _id: { type: String, default: () => uuidv7() },
5760
+ type: { type: String, default: "pageview", index: true },
5761
+ path: { type: String, default: "/" },
5762
+ referrer: { type: String, default: "" },
5763
+ screen: { type: String, default: "" },
5764
+ sid: { type: String, default: "" },
5765
+ props: { type: mongoose.Schema.Types.Mixed, default: {} },
5766
+ ts: { type: Date, default: Date.now, index: true },
5767
+ });
5768
+
5769
+ export const Event =
5770
+ (mongoose.models.Event as mongoose.Model<EventDoc>) ?? mongoose.model<EventDoc>("Event", schema);
5771
+ `;
5772
+ var analyticsEventsRoutes = () => `import express from "express";
5773
+ import { asyncHandler } from "../http.js";
5774
+ import { requireAuth } from "../middleware/auth.js";
5775
+ import { Event } from "../models/event.js";
5776
+
5777
+ const router = express.Router();
5778
+
5779
+ // POST /events \u2014 the tracker beacon posts here. Public + cookieless (no PII stored).
5780
+ router.post("/", asyncHandler(async (req, res) => {
5781
+ const b = (req.body ?? {}) as Record<string, unknown>;
5782
+ await Event.create({
5783
+ type: String(b.type ?? "pageview"),
5784
+ path: String(b.path ?? "/"),
5785
+ referrer: String(b.referrer ?? ""),
5786
+ screen: String(b.screen ?? ""),
5787
+ sid: String(b.sid ?? ""),
5788
+ props: b.props && typeof b.props === "object" ? (b.props as Record<string, unknown>) : {},
5789
+ });
5790
+ res.status(204).end();
5791
+ }));
5792
+
5793
+ // GET /events/summary \u2014 dashboard aggregates (protected: only signed-in owners).
5794
+ router.get("/summary", requireAuth, asyncHandler(async (_req, res) => {
5795
+ const since = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
5796
+ const [total, pageviews, topPaths, byDay] = await Promise.all([
5797
+ Event.countDocuments({}),
5798
+ Event.countDocuments({ type: "pageview" }),
5799
+ Event.aggregate([
5800
+ { $match: { type: "pageview" } },
5801
+ { $group: { _id: "$path", count: { $sum: 1 } } },
5802
+ { $sort: { count: -1 } },
5803
+ { $limit: 8 },
5804
+ ]),
5805
+ Event.aggregate([
5806
+ { $match: { ts: { $gte: since } } },
5807
+ { $group: { _id: { $dateToString: { format: "%Y-%m-%d", date: "$ts" } }, count: { $sum: 1 } } },
5808
+ { $sort: { _id: 1 } },
5809
+ ]),
5810
+ ]);
5811
+ res.json({
5812
+ total,
5813
+ pageviews,
5814
+ topPaths: topPaths.map((p: { _id: string; count: number }) => ({ path: p._id, count: p.count })),
5815
+ byDay: byDay.map((d: { _id: string; count: number }) => ({ day: d._id, count: d.count })),
5816
+ });
5817
+ }));
5818
+
5819
+ export default router;
5820
+ `;
5821
+ var analyticsComponent = (ctx) => `"use client";
5822
+ import { useEffect } from "react";
5823
+ import { createAnalytics } from "@lacspace/analytics-lite";
5824
+
5825
+ // how this works: cookieless, privacy-first tracking. It POSTs page views + events to
5826
+ // your backend /events collector (stored in MongoDB). No cookies, no localStorage, no
5827
+ // personal data. Respects the browser's Do-Not-Track.
5828
+ const ENDPOINT = (process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:4000") + "/events";
5829
+
5830
+ export function Analytics() {
5831
+ useEffect(() => {
5832
+ const a = createAnalytics({ endpoint: ENDPOINT, siteId: ${JSON.stringify(ctx.name)}, respectDNT: true });
5833
+ a.pageview();
5834
+ return a.autoTrack();
5835
+ }, []);
5836
+ return null;
5837
+ }
5838
+ `;
5839
+ var analyticsDashboard = () => `"use client";
5840
+ import { useEffect, useState } from "react";
5841
+ import { useRouter } from "next/navigation";
5842
+ import { getToken } from "@/lib/api";
5843
+
5844
+ const API = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:4000";
5845
+
5846
+ interface Summary {
5847
+ total: number;
5848
+ pageviews: number;
5849
+ topPaths: { path: string; count: number }[];
5850
+ byDay: { day: string; count: number }[];
5851
+ }
5852
+
5853
+ export default function AnalyticsPage() {
5854
+ const router = useRouter();
5855
+ const [data, setData] = useState<Summary | null>(null);
5856
+ const [error, setError] = useState<string | null>(null);
5857
+
5858
+ useEffect(() => {
5859
+ const token = getToken();
5860
+ if (!token) { router.push("/login"); return; }
5861
+ fetch(API + "/events/summary", { headers: { Authorization: "Bearer " + token } })
5862
+ .then((r) => (r.ok ? r.json() : Promise.reject(new Error("Please sign in"))))
5863
+ .then(setData)
5864
+ .catch((e) => setError(e instanceof Error ? e.message : "Failed to load"));
5865
+ }, [router]);
5866
+
5867
+ if (error) return <main className="mx-auto max-w-3xl px-6 py-16 text-muted">{error}</main>;
5868
+ if (!data) return <main className="mx-auto max-w-3xl px-6 py-16 text-muted">Loading\u2026</main>;
5869
+ const max = Math.max(1, ...data.byDay.map((d) => d.count));
5870
+
5871
+ return (
5872
+ <main className="mx-auto max-w-3xl px-6 py-16">
5873
+ <h1 className="text-3xl font-bold">Analytics</h1>
5874
+ <p className="mt-1 text-muted">Cookieless, privacy-first \u2014 last 30 days.</p>
5875
+ <div className="mt-6 grid grid-cols-2 gap-4">
5876
+ <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>
5877
+ <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>
5878
+ </div>
5879
+ <h2 className="mt-8 font-semibold">Top pages</h2>
5880
+ <ul className="mt-3 space-y-2">
5881
+ {data.topPaths.length === 0 && <li className="text-muted">No data yet \u2014 browse your site with &lt;Analytics/&gt; mounted.</li>}
5882
+ {data.topPaths.map((p) => (
5883
+ <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>
5884
+ ))}
5885
+ </ul>
5886
+ <h2 className="mt-8 font-semibold">Events per day</h2>
5887
+ <div className="mt-3 flex items-end gap-1" style={{ height: 120 }}>
5888
+ {data.byDay.map((d) => (
5889
+ <div key={d.day} className="flex-1 rounded-t" style={{ height: (d.count / max) * 100 + "%", backgroundColor: "var(--accent, #6366f1)" }} title={d.day + ": " + d.count} />
5890
+ ))}
5891
+ </div>
5892
+ </main>
5893
+ );
5894
+ }
5895
+ `;
5896
+ var ordersModel = () => `import mongoose from "mongoose";
5897
+ import { uuidv7 } from "@lacspace/id";
5898
+
5899
+ export interface OrderDoc {
5900
+ _id: string;
5901
+ userId: string;
5902
+ label: string;
5903
+ amountPaisa: number;
5904
+ currency: string;
5905
+ status: "pending" | "paid" | "failed";
5906
+ gateway: string;
5907
+ ref: string;
5908
+ createdAt: Date;
5909
+ updatedAt: Date;
5910
+ }
5911
+
5912
+ const schema = new mongoose.Schema<OrderDoc>(
5913
+ {
5914
+ _id: { type: String, default: () => uuidv7() },
5915
+ userId: { type: String, required: true, index: true },
5916
+ label: { type: String, required: true },
5917
+ amountPaisa: { type: Number, required: true },
5918
+ currency: { type: String, default: "NPR" },
5919
+ status: { type: String, enum: ["pending", "paid", "failed"], default: "pending" },
5920
+ gateway: { type: String, default: "" },
5921
+ ref: { type: String, default: "" },
5922
+ },
5923
+ { timestamps: true },
5924
+ );
5925
+
5926
+ export const Order =
5927
+ (mongoose.models.Order as mongoose.Model<OrderDoc>) ?? mongoose.model<OrderDoc>("Order", schema);
5928
+ `;
5929
+ var checkoutRoutes = () => `import express from "express";
5930
+ import {
5931
+ buildForm, verifyResponse, paisaToRupees, generateTransactionUuid,
5932
+ ESEWA_TEST_SECRET, ESEWA_TEST_PRODUCT_CODE,
5933
+ } from "@lacspace/esewa";
5934
+ import { initiate, lookup } from "@lacspace/khalti";
5935
+ import { Money, formatBasic } from "@lacspace/money";
5936
+ import { v } from "@lacspace/validate";
5937
+ import { asyncHandler, HttpError } from "../http.js";
5938
+ import { env } from "../env.js";
5939
+ import { Order } from "../models/order.js";
5940
+
5941
+ // how this works: create an order, then start a gateway payment. eSewa works in TEST
5942
+ // mode with the package's baked-in sandbox keys (no credentials!). Khalti needs a real
5943
+ // secret. After the customer returns, the frontend calls /verify \u2014 never trust the
5944
+ // redirect alone, always confirm server-side.
5945
+ const router = express.Router();
5946
+ const web = () => env.CORS_ORIGIN.split(",")[0]!.trim();
5947
+
5948
+ const CreateInput = v.object({ label: v.string().min(1).max(120), amount: v.number().positive() });
5949
+
5950
+ // POST /checkout \u2014 create a pending order (amount in RUPEES from the UI \u2192 stored as paisa).
5951
+ router.post("/", asyncHandler(async (req, res) => {
5952
+ const { label, amount } = CreateInput.parse(req.body);
5953
+ const amountPaisa = Money.of(amount, "NPR").toMinor();
5954
+ const order = await Order.create({ userId: req.user!.sub, label, amountPaisa });
5955
+ res.status(201).json({ id: String(order._id), label, amountPaisa, display: formatBasic(Money.fromMinor(amountPaisa, "NPR")) });
5956
+ }));
5957
+
5958
+ // POST /checkout/:id/esewa \u2014 build the signed eSewa form to auto-POST from the browser.
5959
+ router.post("/:id/esewa", asyncHandler(async (req, res) => {
5960
+ const order = await Order.findOne({ _id: req.params.id, userId: req.user!.sub });
5961
+ if (!order) throw new HttpError(404, "Order not found");
5962
+ const secret = process.env.ESEWA_SECRET ?? ESEWA_TEST_SECRET;
5963
+ const productCode = process.env.ESEWA_MERCHANT_CODE ?? ESEWA_TEST_PRODUCT_CODE;
5964
+ const esewaEnv: "test" | "prod" = process.env.ESEWA_SECRET ? "prod" : "test";
5965
+ const uuid = generateTransactionUuid();
5966
+ order.ref = uuid;
5967
+ order.gateway = "esewa";
5968
+ await order.save();
5969
+ const form = await buildForm(
5970
+ {
5971
+ amount: paisaToRupees(order.amountPaisa),
5972
+ transactionUuid: uuid,
5973
+ productCode,
5974
+ successUrl: web() + "/checkout/success?orderId=" + String(order._id),
5975
+ failureUrl: web() + "/checkout/failed?orderId=" + String(order._id),
5976
+ },
5977
+ { secret, env: esewaEnv },
5978
+ );
5979
+ res.json(form);
5980
+ }));
5981
+
5982
+ // POST /checkout/:id/esewa/verify \u2014 verify the base64 \`data\` eSewa returned; mark paid.
5983
+ router.post("/:id/esewa/verify", asyncHandler(async (req, res) => {
5984
+ const { data } = v.object({ data: v.string().min(1) }).parse(req.body);
5985
+ const order = await Order.findOne({ _id: req.params.id, userId: req.user!.sub });
5986
+ if (!order) throw new HttpError(404, "Order not found");
5987
+ const secret = process.env.ESEWA_SECRET ?? ESEWA_TEST_SECRET;
5988
+ const result = await verifyResponse(data, secret);
5989
+ const status = String((result.data as { status?: string }).status ?? "");
5990
+ if (!result.valid || status !== "COMPLETE") throw new HttpError(400, "Payment could not be verified");
5991
+ order.status = "paid";
5992
+ await order.save();
5993
+ res.json({ id: String(order._id), status: "paid" });
5994
+ }));
5995
+
5996
+ // POST /checkout/:id/khalti \u2014 start a Khalti payment (needs KHALTI_SECRET, else 501).
5997
+ router.post("/:id/khalti", asyncHandler(async (req, res) => {
5998
+ const secretKey = process.env.KHALTI_SECRET;
5999
+ if (!secretKey) throw new HttpError(501, "Set KHALTI_SECRET in .env to enable Khalti (see .env.example).");
6000
+ const order = await Order.findOne({ _id: req.params.id, userId: req.user!.sub });
6001
+ if (!order) throw new HttpError(404, "Order not found");
6002
+ order.gateway = "khalti";
6003
+ await order.save();
6004
+ const r = await initiate(
6005
+ {
6006
+ return_url: web() + "/checkout/success?orderId=" + String(order._id),
6007
+ website_url: web(),
6008
+ amount: order.amountPaisa,
6009
+ purchase_order_id: String(order._id),
6010
+ purchase_order_name: order.label,
6011
+ },
6012
+ { secretKey, env: "test" },
6013
+ );
6014
+ order.ref = r.pidx;
6015
+ await order.save();
6016
+ res.json({ paymentUrl: r.payment_url, pidx: r.pidx });
6017
+ }));
6018
+
6019
+ // POST /checkout/:id/khalti/verify \u2014 authoritative lookup by pidx; mark paid.
6020
+ router.post("/:id/khalti/verify", asyncHandler(async (req, res) => {
6021
+ const secretKey = process.env.KHALTI_SECRET;
6022
+ if (!secretKey) throw new HttpError(501, "Khalti is not configured");
6023
+ const { pidx } = v.object({ pidx: v.string().min(1) }).parse(req.body);
6024
+ const order = await Order.findOne({ _id: req.params.id, userId: req.user!.sub });
6025
+ if (!order) throw new HttpError(404, "Order not found");
6026
+ const r = await lookup(pidx, { secretKey, env: "test" });
6027
+ if (r.status !== "Completed") throw new HttpError(400, "Payment status: " + String(r.status));
6028
+ order.status = "paid";
6029
+ await order.save();
6030
+ res.json({ id: String(order._id), status: "paid" });
6031
+ }));
6032
+
6033
+ export default router;
6034
+ `;
6035
+ var checkoutPage = () => `"use client";
6036
+ import { useState } from "react";
6037
+ import { getToken } from "@/lib/api";
6038
+
6039
+ const API = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:4000";
6040
+ const msgOf = (e: unknown) => (e instanceof Error ? e.message : "Something went wrong");
6041
+
6042
+ async function call<T>(path: string, body: unknown): Promise<T> {
6043
+ const token = getToken();
6044
+ const res = await fetch(API + path, {
6045
+ method: "POST",
6046
+ headers: { "Content-Type": "application/json", ...(token ? { Authorization: "Bearer " + token } : {}) },
6047
+ body: JSON.stringify(body),
6048
+ });
6049
+ const data: unknown = await res.json().catch(() => ({}));
6050
+ if (!res.ok) throw new Error((data as { error?: string }).error ?? "Request failed");
6051
+ return data as T;
6052
+ }
6053
+
6054
+ export default function CheckoutPage() {
6055
+ const [label, setLabel] = useState("Pro plan");
6056
+ const [amount, setAmount] = useState(1000);
6057
+ const [orderId, setOrderId] = useState<string | null>(null);
6058
+ const [msg, setMsg] = useState<string | null>(null);
6059
+
6060
+ async function createOrder(e: React.FormEvent) {
6061
+ e.preventDefault();
6062
+ try {
6063
+ const o = await call<{ id: string; display: string }>("/checkout", { label, amount });
6064
+ setOrderId(o.id);
6065
+ setMsg("Order " + o.display + " created \u2014 choose how to pay.");
6066
+ } catch (err) { setMsg(msgOf(err)); }
6067
+ }
6068
+ async function payEsewa() {
6069
+ if (!orderId) return;
6070
+ try {
6071
+ const form = await call<{ action: string; fields: Record<string, string> }>("/checkout/" + orderId + "/esewa", {});
6072
+ const f = document.createElement("form");
6073
+ f.method = "POST";
6074
+ f.action = form.action;
6075
+ for (const [k, val] of Object.entries(form.fields)) {
6076
+ const i = document.createElement("input");
6077
+ i.type = "hidden"; i.name = k; i.value = val;
6078
+ f.appendChild(i);
6079
+ }
6080
+ document.body.appendChild(f);
6081
+ f.submit();
6082
+ } catch (err) { setMsg(msgOf(err)); }
6083
+ }
6084
+ async function payKhalti() {
6085
+ if (!orderId) return;
6086
+ try {
6087
+ const r = await call<{ paymentUrl: string }>("/checkout/" + orderId + "/khalti", {});
6088
+ window.location.href = r.paymentUrl;
6089
+ } catch (err) { setMsg(msgOf(err)); }
6090
+ }
6091
+
6092
+ return (
6093
+ <main className="mx-auto max-w-md px-6 py-16">
6094
+ <h1 className="text-2xl font-bold">Checkout</h1>
6095
+ <p className="mt-1 text-sm text-muted">Sign in first, then create an order and pay.</p>
6096
+ <form onSubmit={createOrder} className="mt-6 space-y-3 rounded-2xl border border-hairline p-5">
6097
+ <input value={label} onChange={(e) => setLabel(e.target.value)} placeholder="What are you buying?" className="w-full rounded-xl border border-hairline bg-surface px-4 py-2 outline-none" />
6098
+ <input type="number" min={10} value={amount} onChange={(e) => setAmount(Number(e.target.value))} placeholder="Amount (NPR)" className="w-full rounded-xl border border-hairline bg-surface px-4 py-2 outline-none" />
6099
+ <button className="w-full rounded-full gradient-bg px-4 py-2 font-semibold on-accent">Create order</button>
6100
+ </form>
6101
+ {msg && <p className="mt-4 text-sm text-muted">{msg}</p>}
6102
+ {orderId && (
6103
+ <div className="mt-6 space-y-3">
6104
+ <button onClick={payEsewa} className="w-full rounded-full border border-hairline px-4 py-3 font-semibold transition hover:bg-surface">Pay with eSewa <span className="text-muted">(works in test)</span></button>
6105
+ <button onClick={payKhalti} className="w-full rounded-full border border-hairline px-4 py-3 font-semibold transition hover:bg-surface">Pay with Khalti</button>
6106
+ </div>
6107
+ )}
6108
+ <p className="mt-6 text-xs text-muted">eSewa works out-of-the-box in test mode. Khalti needs KHALTI_SECRET in .env.</p>
6109
+ </main>
6110
+ );
6111
+ }
6112
+ `;
6113
+ var checkoutSuccessPage = () => `"use client";
6114
+ import { useEffect, useState } from "react";
6115
+ import Link from "next/link";
6116
+ import { getToken } from "@/lib/api";
6117
+
6118
+ const API = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:4000";
6119
+
6120
+ export default function CheckoutSuccessPage() {
6121
+ const [status, setStatus] = useState<"verifying" | "paid" | "failed">("verifying");
6122
+ const [detail, setDetail] = useState("");
6123
+
6124
+ useEffect(() => {
6125
+ const q = new URLSearchParams(window.location.search);
6126
+ const orderId = q.get("orderId");
6127
+ const data = q.get("data"); // eSewa returns a base64 \`data\` param
6128
+ const pidx = q.get("pidx"); // Khalti returns \`pidx\`
6129
+ const token = getToken();
6130
+ if (!orderId || !token) { setStatus("failed"); setDetail("Missing order or session \u2014 please sign in."); return; }
6131
+ (async () => {
6132
+ let path = ""; let body: Record<string, string> = {};
6133
+ if (data) { path = "/checkout/" + orderId + "/esewa/verify"; body = { data }; }
6134
+ else if (pidx) { path = "/checkout/" + orderId + "/khalti/verify"; body = { pidx }; }
6135
+ else { setStatus("failed"); setDetail("No payment token was returned."); return; }
6136
+ try {
6137
+ const res = await fetch(API + path, {
6138
+ method: "POST",
6139
+ headers: { "Content-Type": "application/json", Authorization: "Bearer " + token },
6140
+ body: JSON.stringify(body),
6141
+ });
6142
+ if (!res.ok) { const e: unknown = await res.json().catch(() => ({})); throw new Error((e as { error?: string }).error ?? "Verification failed"); }
6143
+ setStatus("paid");
6144
+ } catch (e) { setStatus("failed"); setDetail(e instanceof Error ? e.message : "Verification failed"); }
6145
+ })();
6146
+ }, []);
6147
+
6148
+ return (
6149
+ <main className="mx-auto max-w-md px-6 py-24 text-center">
6150
+ {status === "verifying" && <p className="text-muted">Verifying your payment\u2026</p>}
6151
+ {status === "paid" && (<><h1 className="text-3xl font-bold">Payment successful \u{1F389}</h1><p className="mt-2 text-muted">Thank you \u2014 your order is paid.</p></>)}
6152
+ {status === "failed" && (<><h1 className="text-2xl font-bold">Payment not completed</h1><p className="mt-2 text-muted">{detail}</p></>)}
6153
+ <Link href="/checkout" className="mt-6 inline-block rounded-full border border-hairline px-4 py-2 text-sm">Back to checkout</Link>
6154
+ </main>
6155
+ );
6156
+ }
6157
+ `;
6158
+ var checkoutFailedPage = () => `import Link from "next/link";
6159
+
6160
+ export default function CheckoutFailedPage() {
6161
+ return (
6162
+ <main className="mx-auto max-w-md px-6 py-24 text-center">
6163
+ <h1 className="text-2xl font-bold">Payment cancelled</h1>
6164
+ <p className="mt-2 text-muted">Your payment was not completed.</p>
6165
+ <Link href="/checkout" className="mt-6 inline-block rounded-full border border-hairline px-4 py-2 text-sm">Try again</Link>
6166
+ </main>
6167
+ );
6168
+ }
6169
+ `;
6170
+ var mailerLib = (ctx) => `import { createTransport, createJsonTransport, mailerFromEnv, type Transport } from "@lacspace/mailer";
6171
+ import { welcomeEmail, verifyEmail, passwordResetEmail, toPlainText } from "@lacspace/email-templates";
6172
+
6173
+ // how this works: if SMTP_* env vars are set, it sends real email over SMTP; otherwise
6174
+ // it logs the full message to the console (so the app runs with NO credentials). Adding
6175
+ // SMTP_* later switches to real delivery with no code change.
6176
+ export const transport: Transport = process.env.SMTP_HOST
6177
+ ? createTransport(mailerFromEnv())
6178
+ : createJsonTransport((json) => console.log("\\n[email:dev] set SMTP_* in .env to deliver for real:\\n" + json + "\\n"));
6179
+
6180
+ const FROM = process.env.SMTP_FROM ?? ${JSON.stringify(ctx.name + " <no-reply@example.com>")};
6181
+ const brand = { brandName: ${JSON.stringify(ctx.name)} };
6182
+
6183
+ export function sendWelcome(to: string, name?: string) {
6184
+ const html = welcomeEmail({ name, message: "Thanks for joining " + brand.brandName + "!", ...brand });
6185
+ return transport.send({ from: FROM, to, subject: "Welcome to " + brand.brandName, html, text: toPlainText(html) });
6186
+ }
6187
+ export function sendVerify(to: string, verifyUrl: string) {
6188
+ const html = verifyEmail({ verifyUrl, expiresMinutes: 30, ...brand });
6189
+ return transport.send({ from: FROM, to, subject: "Verify your email", html, text: toPlainText(html) });
6190
+ }
6191
+ export function sendReset(to: string, resetUrl: string) {
6192
+ const html = passwordResetEmail({ resetUrl, expiresMinutes: 30, ...brand });
6193
+ return transport.send({ from: FROM, to, subject: "Reset your password", html, text: toPlainText(html) });
6194
+ }
6195
+ `;
6196
+ var emailRoutes = () => `import express from "express";
6197
+ import { validateEmail } from "@lacspace/email-validate";
6198
+ import { asyncHandler, HttpError } from "../http.js";
6199
+ import { sendWelcome } from "../mail/mailer.js";
6200
+
6201
+ const router = express.Router();
6202
+
6203
+ // POST /email/test \u2014 send a sample welcome email (validates the address first).
6204
+ router.post("/test", asyncHandler(async (req, res) => {
6205
+ const to = String((req.body ?? {}).to ?? "").trim();
6206
+ const check = validateEmail(to);
6207
+ if (!check.valid) throw new HttpError(400, check.reason ?? "Invalid email address");
6208
+ const result = await sendWelcome(check.normalized ?? to);
6209
+ res.json({ ok: true, messageId: result.messageId });
6210
+ }));
6211
+
6212
+ export default router;
6213
+ `;
6214
+ var emailTestPage = () => `"use client";
6215
+ import { useState } from "react";
6216
+ import { getToken } from "@/lib/api";
6217
+
6218
+ const API = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:4000";
6219
+
6220
+ export default function EmailTestPage() {
6221
+ const [to, setTo] = useState("");
6222
+ const [msg, setMsg] = useState<string | null>(null);
6223
+ const [busy, setBusy] = useState(false);
6224
+
6225
+ async function send(e: React.FormEvent) {
6226
+ e.preventDefault();
6227
+ setBusy(true); setMsg(null);
6228
+ try {
6229
+ const token = getToken();
6230
+ const res = await fetch(API + "/email/test", {
6231
+ method: "POST",
6232
+ headers: { "Content-Type": "application/json", ...(token ? { Authorization: "Bearer " + token } : {}) },
6233
+ body: JSON.stringify({ to }),
6234
+ });
6235
+ const data: unknown = await res.json().catch(() => ({}));
6236
+ if (!res.ok) throw new Error((data as { error?: string }).error ?? "Failed to send");
6237
+ setMsg("Sent! If no SMTP is configured, check the API console for the email.");
6238
+ } catch (err) { setMsg(err instanceof Error ? err.message : "Failed"); }
6239
+ finally { setBusy(false); }
6240
+ }
6241
+
6242
+ return (
6243
+ <main className="mx-auto max-w-md px-6 py-16">
6244
+ <h1 className="text-2xl font-bold">Send a test email</h1>
6245
+ <p className="mt-1 text-muted">With no SMTP configured, the email is logged to the API console.</p>
6246
+ <form onSubmit={send} className="mt-6 space-y-3">
6247
+ <input type="email" required value={to} onChange={(e) => setTo(e.target.value)} placeholder="you@example.com" className="w-full rounded-xl border border-hairline bg-surface px-4 py-3 outline-none" />
6248
+ <button disabled={busy} className="w-full rounded-full gradient-bg px-4 py-3 font-semibold on-accent disabled:opacity-60">{busy ? "Sending\u2026" : "Send test email"}</button>
6249
+ </form>
6250
+ {msg && <p className="mt-4 text-sm text-muted">{msg}</p>}
6251
+ </main>
6252
+ );
6253
+ }
6254
+ `;
5416
6255
  var scope = (ctx) => `@${ctx.name}`;
5417
6256
  var typesPkgJson = (ctx) => JSON.stringify({
5418
6257
  name: `${scope(ctx)}/types`,
@@ -5812,44 +6651,67 @@ function buildFullStack(ctx) {
5812
6651
  out[".gitignore"] = rootGitignore();
5813
6652
  out[".env.example"] = rootEnvExample(ctx);
5814
6653
  out["README.md"] = rootReadme(ctx);
6654
+ const envBase = out[".env.example"];
6655
+ const seen = new Set(
6656
+ (envBase.match(/^#?\s*([A-Z0-9_]+)=/gm) ?? []).map((l) => l.replace(/^#?\s*/, "").replace(/=.*/, ""))
6657
+ );
6658
+ const lines = [];
6659
+ for (const f of ctx.features) {
6660
+ const b = f.backend?.(ctx);
6661
+ if (!b?.env) continue;
6662
+ const fresh = Object.entries(b.env).filter(([name]) => !seen.has(name));
6663
+ if (!fresh.length) continue;
6664
+ lines.push("", `# --- ${f.label} (${f.key}) ---`);
6665
+ for (const [name, comment] of fresh) {
6666
+ if (comment) lines.push(`# ${comment}`);
6667
+ lines.push(`${name}=`);
6668
+ seen.add(name);
6669
+ }
6670
+ }
6671
+ if (lines.length) out[".env.example"] = envBase.replace(/\n?$/, "\n") + lines.join("\n") + "\n";
5815
6672
  return out;
5816
6673
  }
5817
- var backendPkgJson = (ctx) => JSON.stringify({
5818
- name: `${scope(ctx)}/backend`,
5819
- version: "0.1.0",
5820
- private: true,
5821
- type: "module",
5822
- main: "dist/index.js",
5823
- scripts: {
5824
- dev: "tsx watch src/index.ts",
5825
- build: "tsc -p tsconfig.json",
5826
- start: "node dist/index.js",
5827
- typecheck: "tsc -p tsconfig.json --noEmit"
5828
- },
5829
- dependencies: {
5830
- express: "^4.21.2",
5831
- cors: "^2.8.5",
5832
- mongoose: "^8.9.0",
5833
- ioredis: "^5.4.2",
5834
- dotenv: "^16.4.7",
5835
- // ✨ Backend built on zero-dep @lacspace/* packages instead of the usual grab-bag.
5836
- "@lacspace/env": "^1.1.0",
5837
- "@lacspace/jwt": "^1.4.0",
5838
- "@lacspace/password": "^1.1.0",
5839
- "@lacspace/validate": "^1.1.0",
5840
- "@lacspace/id": "^1.1.0",
5841
- "@lacspace/rate-limit": "^1.2.0",
5842
- "@lacspace/cache": "^1.1.0",
5843
- [`${scope(ctx)}/types`]: "*"
5844
- },
5845
- devDependencies: {
5846
- typescript: "^5.7.0",
5847
- tsx: "^4.19.2",
5848
- "@types/node": "^22.10.0",
5849
- "@types/express": "^4.17.21",
5850
- "@types/cors": "^2.8.17"
5851
- }
5852
- }, null, 2) + "\n";
6674
+ var backendPkgJson = (ctx) => {
6675
+ const featureDeps = {};
6676
+ for (const f of ctx.features) Object.assign(featureDeps, f.backend?.(ctx)?.deps ?? {});
6677
+ return JSON.stringify({
6678
+ name: `${scope(ctx)}/backend`,
6679
+ version: "0.1.0",
6680
+ private: true,
6681
+ type: "module",
6682
+ main: "dist/index.js",
6683
+ scripts: {
6684
+ dev: "tsx watch src/index.ts",
6685
+ build: "tsc -p tsconfig.json",
6686
+ start: "node dist/index.js",
6687
+ typecheck: "tsc -p tsconfig.json --noEmit"
6688
+ },
6689
+ dependencies: {
6690
+ express: "^4.21.2",
6691
+ cors: "^2.8.5",
6692
+ mongoose: "^8.9.0",
6693
+ ioredis: "^5.4.2",
6694
+ dotenv: "^16.4.7",
6695
+ // ✨ Backend built on zero-dep @lacspace/* packages instead of the usual grab-bag.
6696
+ "@lacspace/env": "^1.1.0",
6697
+ "@lacspace/jwt": "^1.4.0",
6698
+ "@lacspace/password": "^1.1.0",
6699
+ "@lacspace/validate": "^1.1.0",
6700
+ "@lacspace/id": "^1.1.0",
6701
+ "@lacspace/rate-limit": "^1.2.0",
6702
+ "@lacspace/cache": "^1.1.0",
6703
+ ...featureDeps,
6704
+ [`${scope(ctx)}/types`]: "*"
6705
+ },
6706
+ devDependencies: {
6707
+ typescript: "^5.7.0",
6708
+ tsx: "^4.19.2",
6709
+ "@types/node": "^22.10.0",
6710
+ "@types/express": "^4.17.21",
6711
+ "@types/cors": "^2.8.17"
6712
+ }
6713
+ }, null, 2) + "\n";
6714
+ };
5853
6715
  var backendTsconfig = (ctx) => JSON.stringify({
5854
6716
  compilerOptions: {
5855
6717
  target: "ES2022",
@@ -6275,35 +7137,49 @@ router.delete("/:id", asyncHandler(async (req, res) => {
6275
7137
  export default router;
6276
7138
  `;
6277
7139
  var backendApp = (ctx) => `import express from "express";
6278
- import type { RequestHandler } from "express";
6279
7140
  import cors from "cors";
6280
- import { rateLimit, expressRateLimit } from "@lacspace/rate-limit";
6281
7141
  import { env } from "./env.js";
6282
7142
  import { errorHandler } from "./middleware/error.js";
6283
- import authRoutes from "./routes/auth.js";
6284
- import noteRoutes from "./routes/notes.js";
7143
+ import { registerRoutes } from "./routes/index.js";
6285
7144
 
6286
7145
  // how this works: assembles the Express app \u2014 CORS for the frontend, JSON parsing,
6287
- // a health check, the auth + notes routers, then the error handler LAST.
7146
+ // a health check, all route groups (see routes/index.ts), then the error handler LAST.
6288
7147
  export function createApp(): express.Express {
6289
7148
  const app = express();
6290
7149
 
6291
7150
  app.use(cors({ origin: env.CORS_ORIGIN.split(",").map((o) => o.trim()), credentials: true }));
6292
7151
  app.use(express.json());
6293
7152
 
6294
- // Brute-force protection on auth: 20 requests / minute / IP (@lacspace/rate-limit).
6295
- const authLimiter = expressRateLimit(rateLimit({ limit: 20, windowMs: 60_000 })) as unknown as RequestHandler;
6296
-
6297
7153
  app.get("/health", (_req, res) => { res.json({ ok: true, service: "${ctx.name}-api" }); });
6298
- app.use("/auth", authLimiter, authRoutes);
6299
- app.use("/notes", noteRoutes);
7154
+ registerRoutes(app);
6300
7155
 
6301
7156
  app.use(errorHandler);
6302
7157
  return app;
6303
7158
  }
6304
7159
  `;
7160
+ var backendRoutesIndex = (ctx) => {
7161
+ const featureRoutes = ctx.features.flatMap((f) => f.backend?.(ctx)?.routes ?? []);
7162
+ const needsAuth = featureRoutes.some((r) => r.auth);
7163
+ const importLines = featureRoutes.map((r) => r.importLine).join("\n");
7164
+ const mountLines = featureRoutes.map((r) => ` app.use(${JSON.stringify(r.path)}, ${r.auth ? "requireAuth, " : ""}${r.handler});`).join("\n");
7165
+ return `import type { Express, RequestHandler } from "express";
7166
+ import { rateLimit, expressRateLimit } from "@lacspace/rate-limit";
7167
+ ${needsAuth ? 'import { requireAuth } from "../middleware/auth.js";\n' : ""}import authRoutes from "./auth.js";
7168
+ import noteRoutes from "./notes.js";
7169
+ ${importLines ? importLines + "\n" : ""}
7170
+ // how this works: every route group is mounted here. Add a new resource by creating
7171
+ // a router in routes/ and adding one app.use(...) line below.
7172
+ export function registerRoutes(app: Express): void {
7173
+ // Brute-force protection on auth: 20 requests / minute / IP (@lacspace/rate-limit).
7174
+ const authLimiter = expressRateLimit(rateLimit({ limit: 20, windowMs: 60_000 })) as unknown as RequestHandler;
7175
+ app.use("/auth", authLimiter, authRoutes);
7176
+ app.use("/notes", noteRoutes);
7177
+ ${mountLines}
7178
+ }
7179
+ `;
7180
+ };
6305
7181
  function backendFiles(ctx) {
6306
- return {
7182
+ const files = {
6307
7183
  "backend/package.json": backendPkgJson(ctx),
6308
7184
  "backend/tsconfig.json": backendTsconfig(ctx),
6309
7185
  "backend/.gitignore": backendGitignore(),
@@ -6322,8 +7198,15 @@ function backendFiles(ctx) {
6322
7198
  "backend/src/models/user.ts": backendUserModel(),
6323
7199
  "backend/src/models/note.ts": backendNoteModel(),
6324
7200
  "backend/src/routes/auth.ts": backendAuthRoutes(ctx),
6325
- "backend/src/routes/notes.ts": backendNoteRoutes(ctx)
7201
+ "backend/src/routes/notes.ts": backendNoteRoutes(ctx),
7202
+ "backend/src/routes/index.ts": backendRoutesIndex(ctx)
6326
7203
  };
7204
+ for (const f of ctx.features) {
7205
+ const b = f.backend?.(ctx);
7206
+ if (!b?.files) continue;
7207
+ for (const [rel, content] of Object.entries(b.files)) files["backend/" + rel] = content;
7208
+ }
7209
+ return files;
6327
7210
  }
6328
7211
  var splitList = (s) => s.split(",").map((x) => x.trim()).filter(Boolean);
6329
7212
  function parseArgs(list) {