create-lacspace-app 2.5.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/README.md +6 -0
- package/dist/index.js +508 -49
- package/dist/lib.cjs +508 -49
- package/dist/lib.d.cts +34 -1
- package/dist/lib.d.ts +34 -1
- package/dist/lib.js +508 -49
- package/package.json +1 -1
package/dist/lib.d.ts
CHANGED
|
@@ -34,6 +34,39 @@ interface FeatureDef {
|
|
|
34
34
|
nextSteps: string[];
|
|
35
35
|
/** Optional "learn more" URL for `LEARN.md`. */
|
|
36
36
|
learn?: string;
|
|
37
|
+
/**
|
|
38
|
+
* When true, this add-on needs the full-stack backend (a database + a real API).
|
|
39
|
+
* Requesting it in `static` mode automatically upgrades the project to `dynamic`.
|
|
40
|
+
*/
|
|
41
|
+
requiresBackend?: boolean;
|
|
42
|
+
/**
|
|
43
|
+
* Optional backend (Express) contribution — applied **only in dynamic mode**.
|
|
44
|
+
* Lets an add-on drop backend files, register routes, add backend deps and
|
|
45
|
+
* document backend env vars. See {@link FeatureBackend}.
|
|
46
|
+
*/
|
|
47
|
+
backend?: (ctx: Ctx) => FeatureBackend;
|
|
48
|
+
}
|
|
49
|
+
/** An add-on's contribution to the `backend/` workspace (dynamic mode only). */
|
|
50
|
+
interface FeatureBackend {
|
|
51
|
+
/** Files under `backend/` — e.g. `"src/routes/payments.ts"`, `"src/models/payment.ts"`. */
|
|
52
|
+
files?: Record<string, string>;
|
|
53
|
+
/** Extra backend deps, merged into `backend/package.json`. */
|
|
54
|
+
deps?: Record<string, string>;
|
|
55
|
+
/** Express route groups this add-on mounts (assembled in `src/routes/index.ts`). */
|
|
56
|
+
routes?: FeatureRoute[];
|
|
57
|
+
/** Extra root `.env.example` entries — `NAME: "explanatory comment"`. */
|
|
58
|
+
env?: Record<string, string>;
|
|
59
|
+
}
|
|
60
|
+
/** One Express route group registered by a backend add-on. */
|
|
61
|
+
interface FeatureRoute {
|
|
62
|
+
/** Mount path, e.g. `"/payments"`. */
|
|
63
|
+
path: string;
|
|
64
|
+
/** The exact import line, e.g. `import paymentRoutes from "./payments.js";`. */
|
|
65
|
+
importLine: string;
|
|
66
|
+
/** The router identifier used in `app.use`, e.g. `"paymentRoutes"`. */
|
|
67
|
+
handler: string;
|
|
68
|
+
/** Protect the group with the shared `requireAuth` middleware. */
|
|
69
|
+
auth?: boolean;
|
|
37
70
|
}
|
|
38
71
|
interface Ctx {
|
|
39
72
|
name: string;
|
|
@@ -129,4 +162,4 @@ interface ScaffoldResult {
|
|
|
129
162
|
*/
|
|
130
163
|
declare function scaffold(options?: ScaffoldOptions): Promise<ScaffoldResult>;
|
|
131
164
|
|
|
132
|
-
export { type FeatureDef, type GenerateOptions, type ProjectFiles, type ScaffoldOptions, type ScaffoldResult, type TemplateDef, generateProject, getFeature, getSection, getTemplate, listFeatures, listSections, listTemplates, scaffold, templateKeys, templates };
|
|
165
|
+
export { type FeatureBackend, type FeatureDef, type FeatureRoute, type GenerateOptions, type ProjectFiles, type ScaffoldOptions, type ScaffoldResult, type TemplateDef, generateProject, getFeature, getSection, getTemplate, listFeatures, listSections, listTemplates, scaffold, templateKeys, templates };
|
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
|
-
|
|
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,52 @@ 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"
|
|
2166
2213
|
}
|
|
2167
2214
|
];
|
|
2168
2215
|
var aiChatRoute = (_ctx) => `import { resolveConfig } from "@lacspace/providers";
|
|
@@ -5413,6 +5460,374 @@ export default function SearchPage() {
|
|
|
5413
5460
|
);
|
|
5414
5461
|
}
|
|
5415
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 <Analytics/> 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
|
+
`;
|
|
5416
5831
|
var scope = (ctx) => `@${ctx.name}`;
|
|
5417
5832
|
var typesPkgJson = (ctx) => JSON.stringify({
|
|
5418
5833
|
name: `${scope(ctx)}/types`,
|
|
@@ -5812,44 +6227,67 @@ function buildFullStack(ctx) {
|
|
|
5812
6227
|
out[".gitignore"] = rootGitignore();
|
|
5813
6228
|
out[".env.example"] = rootEnvExample(ctx);
|
|
5814
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";
|
|
5815
6248
|
return out;
|
|
5816
6249
|
}
|
|
5817
|
-
var backendPkgJson = (ctx) =>
|
|
5818
|
-
|
|
5819
|
-
|
|
5820
|
-
|
|
5821
|
-
|
|
5822
|
-
|
|
5823
|
-
|
|
5824
|
-
|
|
5825
|
-
|
|
5826
|
-
|
|
5827
|
-
|
|
5828
|
-
|
|
5829
|
-
|
|
5830
|
-
|
|
5831
|
-
|
|
5832
|
-
|
|
5833
|
-
|
|
5834
|
-
|
|
5835
|
-
|
|
5836
|
-
|
|
5837
|
-
|
|
5838
|
-
|
|
5839
|
-
|
|
5840
|
-
|
|
5841
|
-
|
|
5842
|
-
|
|
5843
|
-
|
|
5844
|
-
|
|
5845
|
-
|
|
5846
|
-
|
|
5847
|
-
|
|
5848
|
-
|
|
5849
|
-
|
|
5850
|
-
|
|
5851
|
-
|
|
5852
|
-
|
|
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
|
+
};
|
|
5853
6291
|
var backendTsconfig = (ctx) => JSON.stringify({
|
|
5854
6292
|
compilerOptions: {
|
|
5855
6293
|
target: "ES2022",
|
|
@@ -6275,35 +6713,49 @@ router.delete("/:id", asyncHandler(async (req, res) => {
|
|
|
6275
6713
|
export default router;
|
|
6276
6714
|
`;
|
|
6277
6715
|
var backendApp = (ctx) => `import express from "express";
|
|
6278
|
-
import type { RequestHandler } from "express";
|
|
6279
6716
|
import cors from "cors";
|
|
6280
|
-
import { rateLimit, expressRateLimit } from "@lacspace/rate-limit";
|
|
6281
6717
|
import { env } from "./env.js";
|
|
6282
6718
|
import { errorHandler } from "./middleware/error.js";
|
|
6283
|
-
import
|
|
6284
|
-
import noteRoutes from "./routes/notes.js";
|
|
6719
|
+
import { registerRoutes } from "./routes/index.js";
|
|
6285
6720
|
|
|
6286
6721
|
// how this works: assembles the Express app \u2014 CORS for the frontend, JSON parsing,
|
|
6287
|
-
// a health check,
|
|
6722
|
+
// a health check, all route groups (see routes/index.ts), then the error handler LAST.
|
|
6288
6723
|
export function createApp(): express.Express {
|
|
6289
6724
|
const app = express();
|
|
6290
6725
|
|
|
6291
6726
|
app.use(cors({ origin: env.CORS_ORIGIN.split(",").map((o) => o.trim()), credentials: true }));
|
|
6292
6727
|
app.use(express.json());
|
|
6293
6728
|
|
|
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
6729
|
app.get("/health", (_req, res) => { res.json({ ok: true, service: "${ctx.name}-api" }); });
|
|
6298
|
-
app
|
|
6299
|
-
app.use("/notes", noteRoutes);
|
|
6730
|
+
registerRoutes(app);
|
|
6300
6731
|
|
|
6301
6732
|
app.use(errorHandler);
|
|
6302
6733
|
return app;
|
|
6303
6734
|
}
|
|
6304
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
|
+
};
|
|
6305
6757
|
function backendFiles(ctx) {
|
|
6306
|
-
|
|
6758
|
+
const files = {
|
|
6307
6759
|
"backend/package.json": backendPkgJson(ctx),
|
|
6308
6760
|
"backend/tsconfig.json": backendTsconfig(ctx),
|
|
6309
6761
|
"backend/.gitignore": backendGitignore(),
|
|
@@ -6322,8 +6774,15 @@ function backendFiles(ctx) {
|
|
|
6322
6774
|
"backend/src/models/user.ts": backendUserModel(),
|
|
6323
6775
|
"backend/src/models/note.ts": backendNoteModel(),
|
|
6324
6776
|
"backend/src/routes/auth.ts": backendAuthRoutes(ctx),
|
|
6325
|
-
"backend/src/routes/notes.ts": backendNoteRoutes(ctx)
|
|
6777
|
+
"backend/src/routes/notes.ts": backendNoteRoutes(ctx),
|
|
6778
|
+
"backend/src/routes/index.ts": backendRoutesIndex(ctx)
|
|
6326
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;
|
|
6327
6786
|
}
|
|
6328
6787
|
var splitList = (s) => s.split(",").map((x) => x.trim()).filter(Boolean);
|
|
6329
6788
|
function parseArgs(list) {
|