create-lacspace-app 2.2.2 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lib.js CHANGED
@@ -36,7 +36,25 @@ function resolveContext(options = {}) {
36
36
  const raw = options.name ?? "my-app";
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
- return { name, template };
39
+ const features = normalizeFeatures(options.features);
40
+ const mode = options.mode === "dynamic" ? "dynamic" : "static";
41
+ return { name, template, features, mode };
42
+ }
43
+ function normalizeFeatures(requested) {
44
+ if (!requested || requested.length === 0) return [];
45
+ const seen = /* @__PURE__ */ new Set();
46
+ const out = [];
47
+ const unknown = [];
48
+ for (const raw of requested) {
49
+ const key = String(raw).toLowerCase().trim();
50
+ if (!key || seen.has(key)) continue;
51
+ seen.add(key);
52
+ const def = FEATURES.find((f) => f.key === key);
53
+ if (def) out.push(def);
54
+ else unknown.push(key);
55
+ }
56
+ if (unknown.length) console.warn(`create-lacspace-app: ignoring unknown feature(s): ${unknown.join(", ")}`);
57
+ return out;
40
58
  }
41
59
  var pkgJson = (ctx) => JSON.stringify({
42
60
  name: ctx.name,
@@ -1893,6 +1911,10 @@ Because posts are just Markdown files, you can:
1893
1911
  Check the [first post](/blog/welcome) for the full Markdown reference.
1894
1912
  `;
1895
1913
  function buildFiles(ctx) {
1914
+ if (ctx.mode === "dynamic") return buildFullStack(ctx);
1915
+ return buildApp(ctx);
1916
+ }
1917
+ function buildApp(ctx) {
1896
1918
  const isBlog = ctx.template.key === "blog";
1897
1919
  const isDocs = ctx.template.key === "docs";
1898
1920
  const files = {
@@ -1963,8 +1985,529 @@ function buildFiles(ctx) {
1963
1985
  files["content/docs/installation.md"] = sampleDocInstall();
1964
1986
  files["content/docs/writing-content.md"] = sampleDocWriting();
1965
1987
  }
1988
+ applyFeatures(files, ctx);
1966
1989
  return files;
1967
1990
  }
1991
+ function applyFeatures(files, ctx) {
1992
+ const features = ctx.features;
1993
+ if (!features.length) return;
1994
+ for (const feat of features) {
1995
+ for (const [rel, content] of Object.entries(feat.files(ctx))) {
1996
+ files[rel] = content;
1997
+ }
1998
+ }
1999
+ const addDeps = {};
2000
+ const addScripts = {};
2001
+ for (const feat of features) {
2002
+ Object.assign(addDeps, feat.deps);
2003
+ if (feat.scripts) Object.assign(addScripts, feat.scripts);
2004
+ }
2005
+ if (files["package.json"]) {
2006
+ const pkg = JSON.parse(files["package.json"]);
2007
+ pkg.dependencies = { ...pkg.dependencies ?? {}, ...addDeps };
2008
+ if (Object.keys(addScripts).length) pkg.scripts = { ...pkg.scripts ?? {}, ...addScripts };
2009
+ files["package.json"] = JSON.stringify(pkg, null, 2) + "\n";
2010
+ }
2011
+ const existingEnv = new Set(
2012
+ (files[".env.example"] ?? "").split("\n").map((l) => l.match(/^\s*#?\s*([A-Z0-9_]+)=/)?.[1]).filter(Boolean)
2013
+ );
2014
+ const envLines = [];
2015
+ for (const feat of features) {
2016
+ if (!feat.env || Object.keys(feat.env).length === 0) continue;
2017
+ const fresh = Object.entries(feat.env).filter(([name]) => !existingEnv.has(name));
2018
+ if (fresh.length === 0) continue;
2019
+ envLines.push("", `# --- ${feat.label} (${feat.key}) ---`);
2020
+ for (const [name, comment] of fresh) {
2021
+ if (comment) envLines.push(`# ${comment}`);
2022
+ envLines.push(`${name}=`);
2023
+ existingEnv.add(name);
2024
+ }
2025
+ }
2026
+ if (envLines.length) {
2027
+ const base = files[".env.example"] ?? "";
2028
+ files[".env.example"] = (base.endsWith("\n") || base === "" ? base : base + "\n") + envLines.join("\n") + "\n";
2029
+ }
2030
+ files["LEARN.md"] = learnMd(ctx, features);
2031
+ }
2032
+ function learnMd(ctx, features) {
2033
+ const blocks = features.map((f) => {
2034
+ const steps = f.nextSteps.map((s) => `- [ ] ${s}`).join("\n");
2035
+ const learn = f.learn ? `
2036
+
2037
+ Learn more \u2192 ${f.learn}` : "";
2038
+ return `## ${f.label} \`(${f.key})\`
2039
+
2040
+ ${f.description}
2041
+
2042
+ ${steps}${learn}`;
2043
+ }).join("\n\n");
2044
+ return `# \u{1F9ED} Learn ${ctx.name}
2045
+
2046
+ You scaffolded **${ctx.template.label}** with ${features.length} feature add-on${features.length === 1 ? "" : "s"}:
2047
+ ${features.map((f) => `\`${f.key}\``).join(" \xB7 ")}.
2048
+
2049
+ Work through the checklist below \u2014 each item is a real next step.
2050
+
2051
+ ${blocks}
2052
+
2053
+ ---
2054
+
2055
+ Every add-on is built from zero-dependency \`@lacspace/*\` packages. Browse them all \u2192 https://lacspace.com/packages
2056
+ `;
2057
+ }
2058
+ var FEATURES = [
2059
+ {
2060
+ key: "ai-chat",
2061
+ label: "AI chat",
2062
+ description: "A streaming AI chat route + UI \u2014 free & local by default (Ollama), keyless.",
2063
+ deps: {
2064
+ "@lacspace/ai": "^1.1.0",
2065
+ "@lacspace/prompt": "^1.1.0",
2066
+ "@lacspace/stream": "^1.1.0",
2067
+ "@lacspace/providers": "^1.0.0",
2068
+ "@lacspace/memory": "^1.0.0",
2069
+ "@lacspace/moderation": "^1.0.0"
2070
+ },
2071
+ env: {
2072
+ LACSPACE_AI_PROVIDER: "Which provider preset to use (default: ollama \u2014 free & local, no key).",
2073
+ LACSPACE_AI_BASE_URL: "Override the provider base URL (default Ollama: http://localhost:11434).",
2074
+ LACSPACE_AI_MODEL: "Chat model id (default: llama3.2).",
2075
+ LACSPACE_AI_API_KEY: "Only needed for a hosted provider \u2014 leave blank for local Ollama."
2076
+ },
2077
+ files: (ctx) => ({
2078
+ "app/api/chat/route.ts": aiChatRoute(),
2079
+ "app/chat/page.tsx": aiChatPage(ctx)
2080
+ }),
2081
+ nextSteps: [
2082
+ "\u{1F193} Free local AI \u2014 install Ollama (https://ollama.com), then run `ollama pull llama3.2`.",
2083
+ "Run `npm run dev` and open http://localhost:3000/chat.",
2084
+ "Prefer a hosted model? Set LACSPACE_AI_* in .env (e.g. LACSPACE_AI_PROVIDER=groq + LACSPACE_AI_API_KEY=\u2026)."
2085
+ ],
2086
+ learn: "https://developer.lacspace.com/packages/ai"
2087
+ },
2088
+ {
2089
+ key: "rag",
2090
+ label: "RAG \u2014 chat with your docs",
2091
+ description: "Index your markdown/text and answer grounded questions with cited sources. Keyless & local (Ollama).",
2092
+ deps: {
2093
+ "@lacspace/rag": "^1.0.0",
2094
+ "@lacspace/embeddings": "^1.0.0",
2095
+ "@lacspace/vector": "^1.0.0",
2096
+ "@lacspace/chunk": "^1.1.0",
2097
+ "@lacspace/rerank": "^1.0.0",
2098
+ "@lacspace/providers": "^1.0.0",
2099
+ "@lacspace/ai": "^1.1.0"
2100
+ },
2101
+ scripts: { "rag:index": "node scripts/index-content.mjs" },
2102
+ env: {
2103
+ LACSPACE_AI_PROVIDER: "Which provider preset to use (default: ollama \u2014 free & local, no key).",
2104
+ LACSPACE_AI_BASE_URL: "Override the provider base URL (default Ollama: http://localhost:11434).",
2105
+ LACSPACE_AI_MODEL: "Chat model id used to answer (default: llama3.2).",
2106
+ LACSPACE_AI_API_KEY: "Only needed for a hosted provider \u2014 leave blank for local Ollama.",
2107
+ LACSPACE_EMBED_MODEL: "Embedding model id (default: nomic-embed-text)."
2108
+ },
2109
+ files: (ctx) => ({
2110
+ "content/welcome.md": ragSampleDoc(ctx),
2111
+ "scripts/index-content.mjs": ragIndexScript(),
2112
+ "app/api/ask/route.ts": ragAskRoute(),
2113
+ "app/ask/page.tsx": ragAskPage(ctx)
2114
+ }),
2115
+ nextSteps: [
2116
+ "\u{1F193} Free & local \u2014 install Ollama (https://ollama.com), then `ollama pull nomic-embed-text` and `ollama pull llama3.2`.",
2117
+ "Add markdown/text files to content/, then run `npm run rag:index` to build .rag-index.json.",
2118
+ "Run `npm run dev` and open http://localhost:3000/ask."
2119
+ ],
2120
+ learn: "https://developer.lacspace.com/packages/rag"
2121
+ }
2122
+ ];
2123
+ var aiChatRoute = (_ctx) => `import { resolveConfig } from "@lacspace/providers";
2124
+ import { stream } from "@lacspace/ai";
2125
+ import type { Message } from "@lacspace/ai";
2126
+ import { detectPromptInjection } from "@lacspace/moderation";
2127
+ import { toReadableStream } from "@lacspace/stream";
2128
+
2129
+ // This route runs on Node (it talks to your local Ollama / a hosted LLM).
2130
+ export const runtime = "nodejs";
2131
+ export const dynamic = "force-dynamic";
2132
+
2133
+ export async function POST(req: Request) {
2134
+ // 1. Read the conversation the <ChatUI/> sent us.
2135
+ const { messages } = (await req.json()) as { messages: Message[] };
2136
+
2137
+ // 2. Guard the newest user turn against prompt-injection / jailbreak attempts.
2138
+ // Learn more \u2192 https://developer.lacspace.com/packages/moderation
2139
+ const lastUser = [...messages].reverse().find((m) => m.role === "user");
2140
+ const userText = typeof lastUser?.content === "string" ? lastUser.content : "";
2141
+ const check = detectPromptInjection(userText);
2142
+ if (check.flagged) {
2143
+ return new Response(JSON.stringify({ error: "That message was blocked by the safety guard." }), {
2144
+ status: 400,
2145
+ headers: { "Content-Type": "application/json" },
2146
+ });
2147
+ }
2148
+
2149
+ // 3. Resolve provider config from env \u2014 KEYLESS by default (local Ollama).
2150
+ // Learn more \u2192 https://developer.lacspace.com/packages/providers
2151
+ const cfg = resolveConfig(process.env.LACSPACE_AI_PROVIDER ?? "ollama", {
2152
+ baseUrl: process.env.LACSPACE_AI_BASE_URL, // default: http://localhost:11434
2153
+ model: process.env.LACSPACE_AI_MODEL, // default: llama3.2
2154
+ apiKey: process.env.LACSPACE_AI_API_KEY, // only for hosted providers
2155
+ });
2156
+
2157
+ // Ollama speaks its own dialect but also exposes an OpenAI-compatible surface
2158
+ // at /v1 \u2014 so we always call it (and any hosted provider) as "openai-compatible".
2159
+ const baseUrl = cfg.apiStyle === "ollama" ? cfg.baseUrl.replace(/\\/+$/, "") + "/v1" : cfg.baseUrl;
2160
+ const model = cfg.model ?? "llama3.2";
2161
+
2162
+ // 4. Stream the reply. @lacspace/ai yields unified {type:"text", delta} chunks;
2163
+ // we encode each token and hand the stream to the browser via @lacspace/stream.
2164
+ // Learn more \u2192 https://developer.lacspace.com/packages/ai
2165
+ const encoder = new TextEncoder();
2166
+ async function* tokens() {
2167
+ for await (const chunk of stream({
2168
+ provider: "openai-compatible",
2169
+ baseUrl,
2170
+ apiKey: cfg.apiKey,
2171
+ model,
2172
+ headers: cfg.headers,
2173
+ messages,
2174
+ })) {
2175
+ if (chunk.type === "text") yield encoder.encode(chunk.delta);
2176
+ }
2177
+ }
2178
+
2179
+ // Learn more \u2192 https://developer.lacspace.com/packages/stream
2180
+ return new Response(toReadableStream(tokens()), {
2181
+ headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-cache" },
2182
+ });
2183
+ }
2184
+ `;
2185
+ var aiChatPage = (ctx) => `"use client";
2186
+
2187
+ import { useState, useRef, useEffect } from "react";
2188
+
2189
+ interface Msg { role: "user" | "assistant"; content: string; }
2190
+
2191
+ export default function ChatPage() {
2192
+ const [messages, setMessages] = useState<Msg[]>([]);
2193
+ const [input, setInput] = useState("");
2194
+ const [busy, setBusy] = useState(false);
2195
+ const scroller = useRef<HTMLDivElement>(null);
2196
+
2197
+ useEffect(() => {
2198
+ scroller.current?.scrollTo({ top: scroller.current.scrollHeight, behavior: "smooth" });
2199
+ }, [messages]);
2200
+
2201
+ async function send(e: React.FormEvent) {
2202
+ e.preventDefault();
2203
+ const text = input.trim();
2204
+ if (!text || busy) return;
2205
+ setInput("");
2206
+ setBusy(true);
2207
+
2208
+ const next: Msg[] = [...messages, { role: "user", content: text }];
2209
+ setMessages([...next, { role: "assistant", content: "" }]);
2210
+
2211
+ try {
2212
+ const res = await fetch("/api/chat", {
2213
+ method: "POST",
2214
+ headers: { "Content-Type": "application/json" },
2215
+ body: JSON.stringify({ messages: next }),
2216
+ });
2217
+ if (!res.ok || !res.body) throw new Error("The chat endpoint returned an error.");
2218
+
2219
+ // Read the streamed reply token-by-token and append it live.
2220
+ const reader = res.body.getReader();
2221
+ const decoder = new TextDecoder();
2222
+ let acc = "";
2223
+ for (;;) {
2224
+ const { done, value } = await reader.read();
2225
+ if (done) break;
2226
+ acc += decoder.decode(value, { stream: true });
2227
+ setMessages([...next, { role: "assistant", content: acc }]);
2228
+ }
2229
+ } catch {
2230
+ setMessages([...next, { role: "assistant", content: "\u26A0\uFE0F Couldn't reach the model. Is Ollama running? (ollama.com)" }]);
2231
+ } finally {
2232
+ setBusy(false);
2233
+ }
2234
+ }
2235
+
2236
+ return (
2237
+ <section className="mx-auto flex min-h-[calc(100vh-4rem)] max-w-2xl flex-col px-6 py-10">
2238
+ <header className="mb-6">
2239
+ <p className="text-sm font-semibold uppercase tracking-widest gradient-text">AI \xB7 ${ctx.template.siteName}</p>
2240
+ <h1 className="mt-2 text-3xl font-bold sm:text-4xl">Chat</h1>
2241
+ <p className="mt-2 text-muted">Free &amp; local by default \u2014 powered by Ollama and the Lacspace AI Kit. No key required.</p>
2242
+ </header>
2243
+
2244
+ <div ref={scroller} className="flex-1 space-y-4 overflow-y-auto rounded-2xl border border-hairline bg-surface p-4">
2245
+ {messages.length === 0 && (
2246
+ <p className="py-16 text-center text-muted">Ask me anything to get started.</p>
2247
+ )}
2248
+ {messages.map((m, i) => (
2249
+ <div key={i} className={m.role === "user" ? "flex justify-end" : "flex justify-start"}>
2250
+ <div className={
2251
+ "max-w-[85%] whitespace-pre-wrap rounded-2xl px-4 py-2.5 text-sm leading-relaxed " +
2252
+ (m.role === "user" ? "gradient-bg on-accent" : "border border-hairline bg-app")
2253
+ }>
2254
+ {m.content || (busy ? "\u2026" : "")}
2255
+ </div>
2256
+ </div>
2257
+ ))}
2258
+ </div>
2259
+
2260
+ <form onSubmit={send} className="mt-4 flex gap-2">
2261
+ <input
2262
+ value={input}
2263
+ onChange={(e) => setInput(e.target.value)}
2264
+ placeholder="Type a message\u2026"
2265
+ className="w-full rounded-xl border border-hairline bg-surface px-4 py-3 outline-none focus:border-hairline"
2266
+ />
2267
+ <button
2268
+ type="submit"
2269
+ disabled={busy || !input.trim()}
2270
+ className="rounded-xl gradient-bg on-accent px-5 py-3 text-sm font-semibold shimmer disabled:opacity-50"
2271
+ >
2272
+ {busy ? "\u2026" : "Send"}
2273
+ </button>
2274
+ </form>
2275
+ </section>
2276
+ );
2277
+ }
2278
+ `;
2279
+ var ragSampleDoc = (ctx) => `# Welcome to ${ctx.template.siteName}
2280
+
2281
+ This markdown file lives in \`content/\`. Run \`npm run rag:index\` to chunk and embed
2282
+ everything under \`content/\` into a local vector index (\`.rag-index.json\`), then open
2283
+ \`/ask\` to ask grounded questions about it.
2284
+
2285
+ ## How this works
2286
+
2287
+ - **Chunking** \u2014 \`@lacspace/chunk\` splits each document into overlapping passages.
2288
+ - **Embeddings** \u2014 \`@lacspace/embeddings\` turns each passage into a vector using a
2289
+ local Ollama model (\`nomic-embed-text\`) \u2014 no API key needed.
2290
+ - **Retrieval** \u2014 \`@lacspace/vector\` + \`@lacspace/rag\` find the passages closest to
2291
+ your question, and \`@lacspace/rerank\` re-orders them for relevance.
2292
+ - **Answering** \u2014 \`@lacspace/ai\` writes a grounded answer and cites its sources.
2293
+
2294
+ ## Tips
2295
+
2296
+ Add your own \`.md\` or \`.txt\` files here, re-run \`npm run rag:index\`, and ask away.
2297
+ Everything runs on your machine \u2014 free, keyless and private.
2298
+ `;
2299
+ var ragIndexScript = (_ctx) => `// Build a local vector index from everything under content/.
2300
+ // Run: npm run rag:index (needs Ollama: \`ollama pull nomic-embed-text\`)
2301
+ import { readdir, readFile, writeFile, stat } from "node:fs/promises";
2302
+ import { join, extname, relative } from "node:path";
2303
+ import { splitText } from "@lacspace/chunk";
2304
+ import { embed } from "@lacspace/embeddings";
2305
+ import { createVectorStore } from "@lacspace/vector";
2306
+
2307
+ const ROOT = process.cwd();
2308
+ const CONTENT_DIR = join(ROOT, "content");
2309
+ const OUT = join(ROOT, ".rag-index.json");
2310
+
2311
+ // Which files to index (add more extensions if you like).
2312
+ const EXTS = new Set([".md", ".markdown", ".txt", ".mdx"]);
2313
+
2314
+ // Recursively collect readable files under content/.
2315
+ async function walk(dir) {
2316
+ const out = [];
2317
+ let entries = [];
2318
+ try { entries = await readdir(dir, { withFileTypes: true }); }
2319
+ catch { return out; }
2320
+ for (const e of entries) {
2321
+ const full = join(dir, e.name);
2322
+ if (e.isDirectory()) out.push(...(await walk(full)));
2323
+ else if (EXTS.has(extname(e.name).toLowerCase())) out.push(full);
2324
+ }
2325
+ return out;
2326
+ }
2327
+
2328
+ async function main() {
2329
+ const files = await walk(CONTENT_DIR);
2330
+ if (files.length === 0) {
2331
+ console.error("No content found. Add .md/.txt files under content/ and re-run.");
2332
+ process.exit(1);
2333
+ }
2334
+
2335
+ // 1. Chunk every document into overlapping passages via @lacspace/chunk.
2336
+ const records = [];
2337
+ for (const file of files) {
2338
+ const raw = await readFile(file, "utf8");
2339
+ const source = relative(CONTENT_DIR, file);
2340
+ const chunks = splitText(raw, { chunkSize: 900, chunkOverlap: 150 });
2341
+ chunks.forEach((chunk, i) => {
2342
+ records.push({ id: \`\${source}#\${i}\`, text: chunk.text, source });
2343
+ });
2344
+ }
2345
+
2346
+ // 2. Embed all passages with a local Ollama model (keyless) via @lacspace/embeddings.
2347
+ const model = process.env.LACSPACE_EMBED_MODEL ?? "nomic-embed-text";
2348
+ const baseUrl = process.env.LACSPACE_AI_BASE_URL ?? "http://localhost:11434";
2349
+ console.log(\`Embedding \${records.length} chunks with \${model}\u2026\`);
2350
+ const vectors = await embed(records.map((r) => r.text), { provider: "ollama", model, baseUrl });
2351
+
2352
+ // 3. Store them in an in-memory vector store, then serialise to .rag-index.json.
2353
+ const store = createVectorStore({ metric: "cosine" });
2354
+ store.upsert(records.map((r, i) => ({ id: r.id, vector: vectors[i], text: r.text, metadata: { source: r.source } })));
2355
+
2356
+ await writeFile(OUT, JSON.stringify(store.toJSON()));
2357
+ console.log(\`\u2713 Wrote \${OUT} (\${records.length} chunks from \${files.length} files).\`);
2358
+ }
2359
+
2360
+ main().catch((err) => { console.error(err); process.exit(1); });
2361
+ `;
2362
+ var ragAskRoute = (_ctx) => `import { readFile } from "node:fs/promises";
2363
+ import { join } from "node:path";
2364
+ import { fromJSON } from "@lacspace/vector";
2365
+ import { createEmbedder } from "@lacspace/embeddings";
2366
+ import { createRag } from "@lacspace/rag";
2367
+ import { rerank } from "@lacspace/rerank";
2368
+ import { resolveConfig } from "@lacspace/providers";
2369
+ import { chat } from "@lacspace/ai";
2370
+ import type { Message } from "@lacspace/ai";
2371
+
2372
+ export const runtime = "nodejs";
2373
+ export const dynamic = "force-dynamic";
2374
+
2375
+ export async function POST(req: Request) {
2376
+ const { question } = (await req.json()) as { question: string };
2377
+ if (!question || !question.trim()) {
2378
+ return Response.json({ error: "Ask a question." }, { status: 400 });
2379
+ }
2380
+
2381
+ // 1. Load the local index built by \`npm run rag:index\`.
2382
+ let store;
2383
+ try {
2384
+ const raw = await readFile(join(process.cwd(), ".rag-index.json"), "utf8");
2385
+ store = fromJSON(JSON.parse(raw));
2386
+ } catch {
2387
+ return Response.json({ error: "No index found. Run \`npm run rag:index\` first." }, { status: 503 });
2388
+ }
2389
+
2390
+ // 2. Config \u2014 keyless local Ollama by default.
2391
+ // Learn more \u2192 https://developer.lacspace.com/packages/providers
2392
+ const cfg = resolveConfig(process.env.LACSPACE_AI_PROVIDER ?? "ollama", {
2393
+ baseUrl: process.env.LACSPACE_AI_BASE_URL,
2394
+ model: process.env.LACSPACE_AI_MODEL,
2395
+ apiKey: process.env.LACSPACE_AI_API_KEY,
2396
+ });
2397
+ const embedModel = process.env.LACSPACE_EMBED_MODEL ?? "nomic-embed-text";
2398
+ const embedBaseUrl = cfg.apiStyle === "ollama" ? cfg.baseUrl : (process.env.LACSPACE_AI_BASE_URL ?? "http://localhost:11434");
2399
+
2400
+ // 3. Retrieve the closest passages via @lacspace/rag + @lacspace/embeddings.
2401
+ // Learn more \u2192 https://developer.lacspace.com/packages/rag
2402
+ const embedder = createEmbedder({ provider: "ollama", model: embedModel, baseUrl: embedBaseUrl });
2403
+ const rag = createRag({ embed: embedder, store });
2404
+ const hits = await rag.retrieve(question, { k: 8 });
2405
+
2406
+ // 4. Re-rank for relevance and keep the best few. @lacspace/rerank blends the
2407
+ // vector score with a lexical match \u2014 no second model call needed.
2408
+ // Learn more \u2192 https://developer.lacspace.com/packages/rerank
2409
+ const ranked = await rerank(question, hits.map((h) => ({ id: h.id, text: h.text, score: h.score })), { k: 4 });
2410
+
2411
+ // 5. Build a grounded prompt and answer with @lacspace/ai.
2412
+ // Learn more \u2192 https://developer.lacspace.com/packages/ai
2413
+ const context = ranked.map((d, i) => \`[\${i + 1}] \${d.text}\`).join("\\n\\n");
2414
+ const messages: Message[] = [
2415
+ { role: "system", content: "You answer strictly from the provided context. If the answer isn't there, say you don't know. Cite sources as [n]." },
2416
+ { role: "user", content: \`Context:\\n\${context}\\n\\nQuestion: \${question}\` },
2417
+ ];
2418
+
2419
+ const baseUrl = cfg.apiStyle === "ollama" ? cfg.baseUrl.replace(/\\/+$/, "") + "/v1" : cfg.baseUrl;
2420
+ const res = await chat({
2421
+ provider: "openai-compatible",
2422
+ baseUrl,
2423
+ apiKey: cfg.apiKey,
2424
+ model: cfg.model ?? "llama3.2",
2425
+ headers: cfg.headers,
2426
+ messages,
2427
+ });
2428
+
2429
+ const sources = ranked.map((d, i) => ({ n: i + 1, id: d.id }));
2430
+ return Response.json({ answer: res.text, sources });
2431
+ }
2432
+ `;
2433
+ var ragAskPage = (ctx) => `"use client";
2434
+
2435
+ import { useState } from "react";
2436
+
2437
+ interface Source { n: number; id: string; }
2438
+
2439
+ export default function AskPage() {
2440
+ const [question, setQuestion] = useState("");
2441
+ const [answer, setAnswer] = useState("");
2442
+ const [sources, setSources] = useState<Source[]>([]);
2443
+ const [busy, setBusy] = useState(false);
2444
+ const [error, setError] = useState("");
2445
+
2446
+ async function ask(e: React.FormEvent) {
2447
+ e.preventDefault();
2448
+ const q = question.trim();
2449
+ if (!q || busy) return;
2450
+ setBusy(true); setError(""); setAnswer(""); setSources([]);
2451
+ try {
2452
+ const res = await fetch("/api/ask", {
2453
+ method: "POST",
2454
+ headers: { "Content-Type": "application/json" },
2455
+ body: JSON.stringify({ question: q }),
2456
+ });
2457
+ const data = await res.json();
2458
+ if (!res.ok) throw new Error(data.error || "Something went wrong.");
2459
+ setAnswer(data.answer);
2460
+ setSources(data.sources ?? []);
2461
+ } catch (err) {
2462
+ setError(err instanceof Error ? err.message : "Something went wrong.");
2463
+ } finally {
2464
+ setBusy(false);
2465
+ }
2466
+ }
2467
+
2468
+ return (
2469
+ <section className="mx-auto max-w-2xl px-6 py-16">
2470
+ <p className="text-sm font-semibold uppercase tracking-widest gradient-text">RAG \xB7 ${ctx.template.siteName}</p>
2471
+ <h1 className="mt-2 text-3xl font-bold sm:text-4xl">Ask your content</h1>
2472
+ <p className="mt-2 text-muted">Grounded answers from your own docs \u2014 indexed and answered locally. Run <code className="rounded bg-panel px-1.5 py-0.5 text-sm">npm run rag:index</code> first.</p>
2473
+
2474
+ <form onSubmit={ask} className="mt-8 flex gap-2">
2475
+ <input
2476
+ value={question}
2477
+ onChange={(e) => setQuestion(e.target.value)}
2478
+ placeholder="What is this project about?"
2479
+ className="w-full rounded-xl border border-hairline bg-surface px-4 py-3 outline-none focus:border-hairline"
2480
+ />
2481
+ <button
2482
+ type="submit"
2483
+ disabled={busy || !question.trim()}
2484
+ className="rounded-xl gradient-bg on-accent px-5 py-3 text-sm font-semibold shimmer disabled:opacity-50"
2485
+ >
2486
+ {busy ? "\u2026" : "Ask"}
2487
+ </button>
2488
+ </form>
2489
+
2490
+ {error && <p className="mt-6 rounded-xl border border-red-400/40 bg-red-400/10 px-4 py-3 text-sm text-red-400">{error}</p>}
2491
+
2492
+ {answer && (
2493
+ <div className="mt-8 card p-6">
2494
+ <p className="whitespace-pre-wrap leading-relaxed">{answer}</p>
2495
+ {sources.length > 0 && (
2496
+ <div className="mt-5 border-t border-hairline pt-4">
2497
+ <p className="text-xs font-semibold uppercase tracking-widest text-muted">Sources</p>
2498
+ <ul className="mt-2 space-y-1 text-sm text-muted">
2499
+ {sources.map((s) => (
2500
+ <li key={s.n}>[{s.n}] <code className="text-fg">{s.id}</code></li>
2501
+ ))}
2502
+ </ul>
2503
+ </div>
2504
+ )}
2505
+ </div>
2506
+ )}
2507
+ </section>
2508
+ );
2509
+ }
2510
+ `;
1968
2511
  function pagesFor(ctx) {
1969
2512
  const k = ctx.template.key;
1970
2513
  if (k === "dashboard") {
@@ -4553,8 +5096,921 @@ var faqSection = (ctx) => {
4553
5096
  </div>
4554
5097
  </section>`;
4555
5098
  };
5099
+ var scope = (ctx) => `@${ctx.name}`;
5100
+ var typesPkgJson = (ctx) => JSON.stringify({
5101
+ name: `${scope(ctx)}/types`,
5102
+ version: "0.1.0",
5103
+ private: true,
5104
+ // Type-only package: it ships a single .d.ts (no runtime code, nothing to build).
5105
+ types: "./index.d.ts",
5106
+ exports: { ".": { types: "./index.d.ts" } }
5107
+ }, null, 2) + "\n";
5108
+ var sharedTypes = () => `// Shared API contract \u2014 imported by BOTH the frontend and the backend, so the two
5109
+ // can never drift. These are TYPE-ONLY (no runtime code), so importing them adds
5110
+ // nothing to either bundle. Edit here once; both sides update. Use \`import type\`.
5111
+
5112
+ /** A user, as returned by the API (no password; dates are ISO strings). */
5113
+ export interface User {
5114
+ id: string;
5115
+ email: string;
5116
+ name: string;
5117
+ createdAt: string;
5118
+ }
5119
+
5120
+ /** The response from POST /auth/register and POST /auth/login. */
5121
+ export interface AuthResponse {
5122
+ token: string;
5123
+ user: User;
5124
+ }
5125
+
5126
+ /** The shape of an error response from the API. */
5127
+ export interface ApiError {
5128
+ error: string;
5129
+ fields?: Record<string, string>;
5130
+ }
5131
+
5132
+ /** The example CRUD resource. Rename "Note" to your real domain object. */
5133
+ export interface Note {
5134
+ id: string;
5135
+ title: string;
5136
+ body: string;
5137
+ userId: string;
5138
+ createdAt: string;
5139
+ updatedAt: string;
5140
+ }
5141
+
5142
+ export interface CreateNoteInput {
5143
+ title: string;
5144
+ body?: string;
5145
+ }
5146
+
5147
+ export interface UpdateNoteInput {
5148
+ title?: string;
5149
+ body?: string;
5150
+ }
5151
+ `;
5152
+ var rootPkgJson = (ctx) => JSON.stringify({
5153
+ name: ctx.name,
5154
+ version: "0.1.0",
5155
+ private: true,
5156
+ workspaces: ["types", "backend", "frontend"],
5157
+ scripts: {
5158
+ // Run the API and the frontend together (concurrently), colourised + kill-all.
5159
+ dev: 'concurrently -k -n api,web -c blue,magenta "npm:dev:api" "npm:dev:web"',
5160
+ "dev:api": `npm run dev --workspace ${scope(ctx)}/backend`,
5161
+ "dev:web": `npm run dev --workspace ${scope(ctx)}/frontend`,
5162
+ build: `npm run build --workspace ${scope(ctx)}/backend && npm run build --workspace ${scope(ctx)}/frontend`,
5163
+ start: 'concurrently -k -n api,web -c blue,magenta "npm:start:api" "npm:start:web"',
5164
+ "start:api": `npm run start --workspace ${scope(ctx)}/backend`,
5165
+ "start:web": `npm run start --workspace ${scope(ctx)}/frontend`,
5166
+ typecheck: `npm run typecheck --workspace ${scope(ctx)}/backend`
5167
+ },
5168
+ devDependencies: { concurrently: "^9.1.0" },
5169
+ engines: { node: ">=18" }
5170
+ }, null, 2) + "\n";
5171
+ var dockerCompose = (ctx) => `# Local infrastructure for ${ctx.name}. Start it with: docker compose up -d
5172
+ # Optional \u2014 the API also runs with NO Redis, and against any MongoDB (e.g. Atlas).
5173
+ services:
5174
+ mongo:
5175
+ image: mongo:7
5176
+ restart: unless-stopped
5177
+ ports:
5178
+ - "27017:27017"
5179
+ volumes:
5180
+ - mongo-data:/data/db
5181
+ redis:
5182
+ image: redis:7-alpine
5183
+ restart: unless-stopped
5184
+ ports:
5185
+ - "6379:6379"
5186
+
5187
+ volumes:
5188
+ mongo-data:
5189
+ `;
5190
+ var rootGitignore = () => `node_modules
5191
+ .env
5192
+ .env.local
5193
+ *.log
5194
+ .DS_Store
5195
+ dist
5196
+ .next
5197
+ `;
5198
+ var rootEnvExample = (ctx) => `# ${ctx.name} \u2014 ONE .env for the whole monorepo. Copy it: cp .env.example .env
5199
+ # The defaults below let the app run locally with zero changes.
5200
+
5201
+ # --- Backend ---
5202
+ NODE_ENV=development
5203
+ PORT=4000
5204
+
5205
+ # MongoDB. With Docker (docker compose up -d) the default just works. Or paste a
5206
+ # free MongoDB Atlas connection string here.
5207
+ MONGODB_URI=mongodb://localhost:27017/${ctx.name}
5208
+
5209
+ # Signs JWTs. In production generate a strong value: openssl rand -hex 32
5210
+ JWT_SECRET=dev-secret-change-me
5211
+
5212
+ # Redis is OPTIONAL \u2014 leave empty to use the in-memory cache fallback.
5213
+ # With Docker, set it to: redis://localhost:6379
5214
+ REDIS_URL=
5215
+
5216
+ # Who may call the API (the frontend origin). Comma-separate for multiple.
5217
+ CORS_ORIGIN=http://localhost:3000
5218
+
5219
+ # --- Frontend ---
5220
+ # Where the browser calls the API. Unset = http://localhost:4000 (local default).
5221
+ # NEXT_PUBLIC_API_URL=http://localhost:4000
5222
+ `;
5223
+ var rootReadme = (ctx) => `# ${ctx.name}
5224
+
5225
+ A full-stack app scaffolded with [create-lacspace-app](https://www.npmjs.com/package/create-lacspace-app) \u2014 a **${ctx.template.label}** frontend + a real backend, wired together.
5226
+
5227
+ \`\`\`
5228
+ ${ctx.name}/
5229
+ \u251C\u2500 frontend/ Next.js 15 app (your UI) \u2014 talks to the API
5230
+ \u251C\u2500 backend/ Node \xB7 Express \xB7 MongoDB \xB7 Redis \xB7 TypeScript API
5231
+ \u251C\u2500 types/ Shared API types \u2014 imported by BOTH sides, so they can't drift
5232
+ \u2514\u2500 docker-compose.yml Mongo + Redis for local dev (optional)
5233
+ \`\`\`
5234
+
5235
+ ## Quick start
5236
+
5237
+ \`\`\`bash
5238
+ cp .env.example .env # one env file for everything (sensible defaults)
5239
+ docker compose up -d # optional: starts MongoDB + Redis locally
5240
+ npm install # installs all three workspaces at once
5241
+ npm run dev # runs the API (:4000) and the frontend (:3000) together
5242
+ \`\`\`
5243
+
5244
+ Then open **http://localhost:3000** \u2192 visit **/register**, create an account, and you'll land on **/account** \u2014 a protected page that reads/writes the example "notes" resource through the API.
5245
+
5246
+ **No Docker?** Point \`MONGODB_URI\` at any MongoDB (a free [Atlas](https://www.mongodb.com/atlas) cluster works). Redis is optional \u2014 leave \`REDIS_URL\` empty and the API uses an in-memory cache instead.
5247
+
5248
+ ## What's already built
5249
+
5250
+ - **Auth** \u2014 \`POST /auth/register\`, \`POST /auth/login\` (JWT), \`GET /auth/me\`. Passwords hashed with \`@lacspace/password\`, tokens signed/verified with \`@lacspace/jwt\`.
5251
+ - **Example CRUD** \u2014 \`/notes\` (list \xB7 create \xB7 read \xB7 update \xB7 delete), protected, per-user, with a per-user cache (Redis or in-memory) that busts on writes.
5252
+ - **Validation** \u2014 request bodies validated with \`@lacspace/validate\`; failures return a clean 400.
5253
+ - **Rate limiting** \u2014 auth endpoints throttled with \`@lacspace/rate-limit\`.
5254
+ - **Typed env** \u2014 \`@lacspace/env\` fails fast at boot if config is wrong.
5255
+
5256
+ Everything on the backend is built from zero-dependency \`@lacspace/*\` packages \u2192 https://lacspace.com/packages
5257
+
5258
+ ## Make it yours
5259
+
5260
+ Rename the \`Note\` resource (in \`types/index.d.ts\`, \`backend/src/models/note.ts\`, \`backend/src/routes/notes.ts\`) to your real domain object, then follow the same pattern for more resources. The shared \`types/\` package keeps the frontend and backend in lock-step.
5261
+ `;
5262
+ var frontendApiClient = (ctx) => `import type { AuthResponse, User, Note, CreateNoteInput, ApiError } from "${scope(ctx)}/types";
5263
+
5264
+ // how this works: a tiny typed fetch wrapper around the backend API. The response
5265
+ // shapes come from the shared "${scope(ctx)}/types" package \u2014 the SAME types the
5266
+ // backend uses \u2014 so the client and server can never disagree about the contract.
5267
+ const BASE = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:4000";
5268
+ const TOKEN_KEY = "${ctx.name}_token";
5269
+
5270
+ export function getToken(): string | null {
5271
+ if (typeof window === "undefined") return null;
5272
+ try { return localStorage.getItem(TOKEN_KEY); } catch { return null; }
5273
+ }
5274
+ export function setToken(token: string | null): void {
5275
+ if (typeof window === "undefined") return;
5276
+ try { token ? localStorage.setItem(TOKEN_KEY, token) : localStorage.removeItem(TOKEN_KEY); } catch {}
5277
+ }
5278
+
5279
+ async function request<T>(path: string, init?: RequestInit): Promise<T> {
5280
+ const token = getToken();
5281
+ const res = await fetch(\`\${BASE}\${path}\`, {
5282
+ ...init,
5283
+ headers: {
5284
+ "Content-Type": "application/json",
5285
+ ...(token ? { Authorization: \`Bearer \${token}\` } : {}),
5286
+ ...(init?.headers ?? {}),
5287
+ },
5288
+ });
5289
+ if (!res.ok) {
5290
+ let message = "Request failed";
5291
+ try { message = ((await res.json()) as ApiError).error ?? message; } catch {}
5292
+ throw new Error(message);
5293
+ }
5294
+ if (res.status === 204) return undefined as T;
5295
+ return (await res.json()) as T;
5296
+ }
5297
+
5298
+ export const api = {
5299
+ register: (input: { name: string; email: string; password: string }) =>
5300
+ request<AuthResponse>("/auth/register", { method: "POST", body: JSON.stringify(input) }),
5301
+ login: (input: { email: string; password: string }) =>
5302
+ request<AuthResponse>("/auth/login", { method: "POST", body: JSON.stringify(input) }),
5303
+ me: () => request<User>("/auth/me"),
5304
+ listNotes: () => request<Note[]>("/notes"),
5305
+ createNote: (input: CreateNoteInput) =>
5306
+ request<Note>("/notes", { method: "POST", body: JSON.stringify(input) }),
5307
+ deleteNote: (id: string) => request<void>(\`/notes/\${id}\`, { method: "DELETE" }),
5308
+ };
5309
+ `;
5310
+ var frontendLoginPage = () => `"use client";
5311
+ import { useState } from "react";
5312
+ import { useRouter } from "next/navigation";
5313
+ import Link from "next/link";
5314
+ import { api, setToken } from "@/lib/api";
5315
+
5316
+ // how this works: posts to the backend /auth/login, stores the returned JWT, then
5317
+ // redirects to /account. Every request after this sends the token automatically.
5318
+ export default function LoginPage() {
5319
+ const router = useRouter();
5320
+ const [email, setEmail] = useState("");
5321
+ const [password, setPassword] = useState("");
5322
+ const [error, setError] = useState<string | null>(null);
5323
+ const [busy, setBusy] = useState(false);
5324
+
5325
+ async function onSubmit(e: React.FormEvent) {
5326
+ e.preventDefault();
5327
+ setBusy(true); setError(null);
5328
+ try {
5329
+ const { token } = await api.login({ email, password });
5330
+ setToken(token);
5331
+ router.push("/account");
5332
+ } catch (err) {
5333
+ setError(err instanceof Error ? err.message : "Something went wrong");
5334
+ } finally { setBusy(false); }
5335
+ }
5336
+
5337
+ return (
5338
+ <main className="mx-auto flex min-h-[70vh] max-w-sm flex-col justify-center px-6">
5339
+ <h1 className="text-2xl font-bold">Welcome back</h1>
5340
+ <p className="mt-1 text-muted">Sign in to your account.</p>
5341
+ <form onSubmit={onSubmit} className="mt-6 space-y-4">
5342
+ <input value={email} onChange={(e) => setEmail(e.target.value)} type="email" required placeholder="you@example.com" className="w-full rounded-xl border border-hairline bg-surface px-4 py-3 outline-none" />
5343
+ <input value={password} onChange={(e) => setPassword(e.target.value)} type="password" required placeholder="Password" className="w-full rounded-xl border border-hairline bg-surface px-4 py-3 outline-none" />
5344
+ {error && <p className="text-sm text-red-400">{error}</p>}
5345
+ <button disabled={busy} className="w-full rounded-full gradient-bg px-4 py-3 font-semibold on-accent transition hover:opacity-90 disabled:opacity-60">{busy ? "Signing in\u2026" : "Sign in"}</button>
5346
+ </form>
5347
+ <p className="mt-4 text-sm text-muted">No account? <Link href="/register" className="underline">Create one</Link></p>
5348
+ </main>
5349
+ );
5350
+ }
5351
+ `;
5352
+ var frontendRegisterPage = () => `"use client";
5353
+ import { useState } from "react";
5354
+ import { useRouter } from "next/navigation";
5355
+ import Link from "next/link";
5356
+ import { api, setToken } from "@/lib/api";
5357
+
5358
+ // how this works: posts to /auth/register, stores the JWT, redirects to /account.
5359
+ export default function RegisterPage() {
5360
+ const router = useRouter();
5361
+ const [name, setName] = useState("");
5362
+ const [email, setEmail] = useState("");
5363
+ const [password, setPassword] = useState("");
5364
+ const [error, setError] = useState<string | null>(null);
5365
+ const [busy, setBusy] = useState(false);
5366
+
5367
+ async function onSubmit(e: React.FormEvent) {
5368
+ e.preventDefault();
5369
+ setBusy(true); setError(null);
5370
+ try {
5371
+ const { token } = await api.register({ name, email, password });
5372
+ setToken(token);
5373
+ router.push("/account");
5374
+ } catch (err) {
5375
+ setError(err instanceof Error ? err.message : "Something went wrong");
5376
+ } finally { setBusy(false); }
5377
+ }
5378
+
5379
+ return (
5380
+ <main className="mx-auto flex min-h-[70vh] max-w-sm flex-col justify-center px-6">
5381
+ <h1 className="text-2xl font-bold">Create your account</h1>
5382
+ <p className="mt-1 text-muted">It takes a few seconds.</p>
5383
+ <form onSubmit={onSubmit} className="mt-6 space-y-4">
5384
+ <input value={name} onChange={(e) => setName(e.target.value)} required placeholder="Your name" className="w-full rounded-xl border border-hairline bg-surface px-4 py-3 outline-none" />
5385
+ <input value={email} onChange={(e) => setEmail(e.target.value)} type="email" required placeholder="you@example.com" className="w-full rounded-xl border border-hairline bg-surface px-4 py-3 outline-none" />
5386
+ <input value={password} onChange={(e) => setPassword(e.target.value)} type="password" required minLength={8} placeholder="Password (min 8 chars)" className="w-full rounded-xl border border-hairline bg-surface px-4 py-3 outline-none" />
5387
+ {error && <p className="text-sm text-red-400">{error}</p>}
5388
+ <button disabled={busy} className="w-full rounded-full gradient-bg px-4 py-3 font-semibold on-accent transition hover:opacity-90 disabled:opacity-60">{busy ? "Creating\u2026" : "Create account"}</button>
5389
+ </form>
5390
+ <p className="mt-4 text-sm text-muted">Already have one? <Link href="/login" className="underline">Sign in</Link></p>
5391
+ </main>
5392
+ );
5393
+ }
5394
+ `;
5395
+ var frontendAccountPage = (ctx) => `"use client";
5396
+ import { useEffect, useState } from "react";
5397
+ import { useRouter } from "next/navigation";
5398
+ import { api, getToken, setToken } from "@/lib/api";
5399
+ import type { User, Note } from "${scope(ctx)}/types";
5400
+
5401
+ // how this works: a PROTECTED page. On mount it calls /auth/me with the stored
5402
+ // token; if that fails it bounces to /login. Notes are the example CRUD resource.
5403
+ export default function AccountPage() {
5404
+ const router = useRouter();
5405
+ const [user, setUser] = useState<User | null>(null);
5406
+ const [notes, setNotes] = useState<Note[]>([]);
5407
+ const [title, setTitle] = useState("");
5408
+ const [body, setBody] = useState("");
5409
+ const [error, setError] = useState<string | null>(null);
5410
+
5411
+ useEffect(() => {
5412
+ if (!getToken()) { router.push("/login"); return; }
5413
+ (async () => {
5414
+ try {
5415
+ setUser(await api.me());
5416
+ setNotes(await api.listNotes());
5417
+ } catch { setToken(null); router.push("/login"); }
5418
+ })();
5419
+ }, [router]);
5420
+
5421
+ async function addNote(e: React.FormEvent) {
5422
+ e.preventDefault();
5423
+ setError(null);
5424
+ try {
5425
+ const note = await api.createNote({ title, body });
5426
+ setNotes((prev) => [note, ...prev]);
5427
+ setTitle(""); setBody("");
5428
+ } catch (err) { setError(err instanceof Error ? err.message : "Failed to save"); }
5429
+ }
5430
+ async function remove(id: string) {
5431
+ await api.deleteNote(id);
5432
+ setNotes((prev) => prev.filter((n) => n.id !== id));
5433
+ }
5434
+ function signOut() { setToken(null); router.push("/login"); }
5435
+
5436
+ if (!user) return <main className="mx-auto max-w-2xl px-6 py-16 text-muted">Loading\u2026</main>;
5437
+
5438
+ return (
5439
+ <main className="mx-auto max-w-2xl px-6 py-16">
5440
+ <div className="flex items-center justify-between">
5441
+ <div>
5442
+ <h1 className="text-2xl font-bold">Hi, {user.name}</h1>
5443
+ <p className="text-muted">{user.email}</p>
5444
+ </div>
5445
+ <button onClick={signOut} className="rounded-full border border-hairline px-4 py-2 text-sm transition hover:bg-surface">Sign out</button>
5446
+ </div>
5447
+
5448
+ <form onSubmit={addNote} className="mt-8 space-y-3 rounded-2xl border border-hairline bg-surface p-5">
5449
+ <h2 className="font-semibold">Add a note</h2>
5450
+ <input value={title} onChange={(e) => setTitle(e.target.value)} required placeholder="Title" className="w-full rounded-xl border border-hairline bg-app px-4 py-2 outline-none" />
5451
+ <textarea value={body} onChange={(e) => setBody(e.target.value)} placeholder="Write something\u2026" rows={3} className="w-full rounded-xl border border-hairline bg-app px-4 py-2 outline-none" />
5452
+ {error && <p className="text-sm text-red-400">{error}</p>}
5453
+ <button className="rounded-full gradient-bg px-4 py-2 text-sm font-semibold on-accent">Save note</button>
5454
+ </form>
5455
+
5456
+ <ul className="mt-6 space-y-3">
5457
+ {notes.length === 0 && <li className="text-muted">No notes yet \u2014 add your first above.</li>}
5458
+ {notes.map((n) => (
5459
+ <li key={n.id} className="flex items-start justify-between rounded-2xl border border-hairline p-4">
5460
+ <div>
5461
+ <p className="font-medium">{n.title}</p>
5462
+ {n.body && <p className="mt-1 text-sm text-muted">{n.body}</p>}
5463
+ </div>
5464
+ <button onClick={() => remove(n.id)} className="shrink-0 text-sm text-muted transition hover:text-red-400">Delete</button>
5465
+ </li>
5466
+ ))}
5467
+ </ul>
5468
+ </main>
5469
+ );
5470
+ }
5471
+ `;
5472
+ function buildFullStack(ctx) {
5473
+ const out = {};
5474
+ const s = scope(ctx);
5475
+ const app = buildApp(ctx);
5476
+ for (const [rel, content] of Object.entries(app)) out[`frontend/${rel}`] = content;
5477
+ const fpkg = JSON.parse(out["frontend/package.json"]);
5478
+ fpkg.name = `${s}/frontend`;
5479
+ fpkg.dependencies[`${s}/types`] = "*";
5480
+ out["frontend/package.json"] = JSON.stringify(fpkg, null, 2) + "\n";
5481
+ const fts = JSON.parse(out["frontend/tsconfig.json"]);
5482
+ fts.compilerOptions.paths[`${s}/types`] = ["../types/index.d.ts"];
5483
+ out["frontend/tsconfig.json"] = JSON.stringify(fts, null, 2) + "\n";
5484
+ const fenv = out["frontend/.env.example"] ?? "";
5485
+ out["frontend/.env.example"] = (fenv.endsWith("\n") || fenv === "" ? fenv : fenv + "\n") + "\n# The backend API base URL. Unset = http://localhost:4000 (local default).\n# NEXT_PUBLIC_API_URL=http://localhost:4000\n";
5486
+ out["frontend/lib/api.ts"] = frontendApiClient(ctx);
5487
+ out["frontend/app/login/page.tsx"] = frontendLoginPage();
5488
+ out["frontend/app/register/page.tsx"] = frontendRegisterPage();
5489
+ out["frontend/app/account/page.tsx"] = frontendAccountPage(ctx);
5490
+ Object.assign(out, backendFiles(ctx));
5491
+ out["types/package.json"] = typesPkgJson(ctx);
5492
+ out["types/index.d.ts"] = sharedTypes();
5493
+ out["package.json"] = rootPkgJson(ctx);
5494
+ out["docker-compose.yml"] = dockerCompose(ctx);
5495
+ out[".gitignore"] = rootGitignore();
5496
+ out[".env.example"] = rootEnvExample(ctx);
5497
+ out["README.md"] = rootReadme(ctx);
5498
+ return out;
5499
+ }
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";
5536
+ var backendTsconfig = (ctx) => JSON.stringify({
5537
+ compilerOptions: {
5538
+ target: "ES2022",
5539
+ module: "NodeNext",
5540
+ moduleResolution: "NodeNext",
5541
+ lib: ["ES2022"],
5542
+ esModuleInterop: true,
5543
+ allowSyntheticDefaultImports: true,
5544
+ strict: true,
5545
+ skipLibCheck: true,
5546
+ resolveJsonModule: true,
5547
+ outDir: "dist",
5548
+ rootDir: "src",
5549
+ sourceMap: true,
5550
+ types: ["node"],
5551
+ baseUrl: ".",
5552
+ paths: { [`${scope(ctx)}/types`]: ["../types/index.d.ts"] }
5553
+ },
5554
+ include: ["src/**/*"],
5555
+ exclude: ["node_modules", "dist"]
5556
+ }, null, 2) + "\n";
5557
+ var backendGitignore = () => `node_modules
5558
+ dist
5559
+ .env
5560
+ *.log
5561
+ `;
5562
+ var backendReadme = (ctx) => `# ${ctx.name} \u2014 API
5563
+
5564
+ Node \xB7 Express \xB7 MongoDB \xB7 Redis (optional) \xB7 TypeScript. Built on zero-dependency \`@lacspace/*\` packages.
5565
+
5566
+ Run it from the repo root with \`npm run dev\` (starts this API + the frontend). Standalone: \`npm run dev\` inside this folder.
5567
+
5568
+ ## Endpoints
5569
+
5570
+ | Method | Path | Auth | Description |
5571
+ |--------|------------------|------|--------------------------------|
5572
+ | GET | \`/health\` | \u2014 | Liveness check |
5573
+ | POST | \`/auth/register\` | \u2014 | Create an account \u2192 JWT + user |
5574
+ | POST | \`/auth/login\` | \u2014 | Log in \u2192 JWT + user |
5575
+ | GET | \`/auth/me\` | \u2713 | The current user |
5576
+ | GET | \`/notes\` | \u2713 | List your notes (cached) |
5577
+ | POST | \`/notes\` | \u2713 | Create a note |
5578
+ | GET | \`/notes/:id\` | \u2713 | Read one note |
5579
+ | PATCH | \`/notes/:id\` | \u2713 | Update a note |
5580
+ | DELETE | \`/notes/:id\` | \u2713 | Delete a note |
5581
+
5582
+ Send \`Authorization: Bearer <token>\` for the \u2713 routes (you get the token from register/login).
5583
+
5584
+ ## Layout
5585
+
5586
+ \`\`\`
5587
+ src/
5588
+ \u251C\u2500 index.ts boot: load env \u2192 connect Mongo \u2192 listen
5589
+ \u251C\u2500 load-env.ts loads the root .env (imported first)
5590
+ \u251C\u2500 env.ts typed, validated env (@lacspace/env)
5591
+ \u251C\u2500 app.ts the Express app (CORS, routes, error handler)
5592
+ \u251C\u2500 db.ts Mongoose connection
5593
+ \u251C\u2500 cache.ts Redis, or an in-memory fallback (@lacspace/cache)
5594
+ \u251C\u2500 http.ts HttpError + asyncHandler
5595
+ \u251C\u2500 validation.ts request schemas (@lacspace/validate)
5596
+ \u251C\u2500 middleware/ auth (@lacspace/jwt) + error handling
5597
+ \u251C\u2500 models/ Mongoose models (User, Note)
5598
+ \u2514\u2500 routes/ auth + notes (the example CRUD resource)
5599
+ \`\`\`
5600
+ `;
5601
+ var backendLoadEnv = () => `import { config } from "dotenv";
5602
+ import { resolve } from "node:path";
5603
+
5604
+ // how this works: the whole monorepo shares ONE .env at the repo root. When this
5605
+ // API runs via \`npm run dev\` its working directory is backend/, so the root .env
5606
+ // is one level up. This module is imported FIRST (before env.ts) so the variables
5607
+ // exist by the time anything reads them.
5608
+ config({ path: resolve(process.cwd(), "../.env") });
5609
+ config(); // also load backend/.env if you keep one (root values already set win)
5610
+ `;
5611
+ var backendEnv = (ctx) => `import { createEnv, str, port, oneOf } from "@lacspace/env";
5612
+
5613
+ // how this works: fail-fast, TYPED environment variables (@lacspace/env). Bad or
5614
+ // missing values throw at boot with a clear message. Sensible dev defaults mean it
5615
+ // runs with zero config against a local MongoDB; set real values in the root .env.
5616
+ export const env = createEnv({
5617
+ NODE_ENV: oneOf(["development", "production", "test"], { default: "development" }),
5618
+ PORT: port({ default: 4000 }),
5619
+ MONGODB_URI: str({ default: "mongodb://localhost:27017/${ctx.name}" }),
5620
+ JWT_SECRET: str({ default: "dev-secret-change-me" }),
5621
+ REDIS_URL: str({ optional: true }),
5622
+ CORS_ORIGIN: str({ default: "http://localhost:3000" }),
5623
+ });
5624
+
5625
+ if (env.NODE_ENV === "production" && env.JWT_SECRET === "dev-secret-change-me") {
5626
+ throw new Error("Set a strong JWT_SECRET in production (see .env.example).");
5627
+ }
5628
+ `;
5629
+ var backendIndex = (ctx) => `import "./load-env.js"; // MUST be first: fills process.env before anything reads it
5630
+ import { env } from "./env.js";
5631
+ import { connectDb } from "./db.js";
5632
+ import { createApp } from "./app.js";
5633
+
5634
+ // how this works: connect to MongoDB, build the Express app, then listen.
5635
+ async function main(): Promise<void> {
5636
+ await connectDb(env.MONGODB_URI);
5637
+ const app = createApp();
5638
+ app.listen(env.PORT, () => {
5639
+ console.log(\`\u{1F680} ${ctx.name} API ready on http://localhost:\${env.PORT}\`);
5640
+ });
5641
+ }
5642
+
5643
+ main().catch((err) => {
5644
+ console.error("Failed to start the API:", err);
5645
+ process.exit(1);
5646
+ });
5647
+ `;
5648
+ var backendDb = () => `import mongoose from "mongoose";
5649
+
5650
+ // how this works: opens the Mongoose connection. Call once at boot.
5651
+ export async function connectDb(uri: string): Promise<void> {
5652
+ mongoose.set("strictQuery", true);
5653
+ await mongoose.connect(uri);
5654
+ console.log("\u2714 MongoDB connected");
5655
+ }
5656
+ `;
5657
+ var backendCache = () => `import { createCache } from "@lacspace/cache";
5658
+ import { Redis } from "ioredis";
5659
+ import { env } from "./env.js";
5660
+
5661
+ // how this works: one cache interface, TWO backends. If REDIS_URL is set we use
5662
+ // Redis; otherwise we fall back to @lacspace/cache (zero-dep, in-memory) so the app
5663
+ // runs with NO Redis at all. The rest of the code doesn't care which is active.
5664
+ export interface Cache {
5665
+ get(key: string): Promise<string | null>;
5666
+ set(key: string, value: string, ttlSeconds?: number): Promise<void>;
5667
+ del(key: string): Promise<void>;
5668
+ readonly kind: "redis" | "memory";
5669
+ }
5670
+
5671
+ function redisCache(url: string): Cache {
5672
+ const client = new Redis(url, { maxRetriesPerRequest: 2 });
5673
+ client.on("error", (e: Error) => console.warn("\u26A0 Redis error:", e.message));
5674
+ return {
5675
+ kind: "redis",
5676
+ async get(key) { return client.get(key); },
5677
+ async set(key, value, ttl) { if (ttl) await client.set(key, value, "EX", ttl); else await client.set(key, value); },
5678
+ async del(key) { await client.del(key); },
5679
+ };
5680
+ }
5681
+
5682
+ function memoryCache(): Cache {
5683
+ const mem = createCache<string>({ max: 5000 });
5684
+ return {
5685
+ kind: "memory",
5686
+ async get(key) { return mem.get(key) ?? null; },
5687
+ async set(key, value, ttl) { mem.set(key, value, ttl ? ttl * 1000 : undefined); },
5688
+ async del(key) { mem.delete(key); },
5689
+ };
5690
+ }
5691
+
5692
+ export const cache: Cache = env.REDIS_URL ? redisCache(env.REDIS_URL) : memoryCache();
5693
+ console.log(\`\u2714 Cache: \${cache.kind}\${cache.kind === "memory" ? " (no REDIS_URL \u2014 in-memory fallback)" : ""}\`);
5694
+ `;
5695
+ var backendHttp = () => `import type { Request, Response, NextFunction, RequestHandler } from "express";
5696
+
5697
+ /** A simple HTTP error with a status code \u2014 throw it from any handler. */
5698
+ export class HttpError extends Error {
5699
+ status: number;
5700
+ constructor(status: number, message: string) {
5701
+ super(message);
5702
+ this.status = status;
5703
+ this.name = "HttpError";
5704
+ }
5705
+ }
5706
+
5707
+ // how this works: Express v4 doesn't catch rejected Promises from async handlers,
5708
+ // so wrap them \u2014 any thrown error is forwarded to the error middleware.
5709
+ export const asyncHandler =
5710
+ (fn: (req: Request, res: Response, next: NextFunction) => Promise<unknown>): RequestHandler =>
5711
+ (req, res, next) => { fn(req, res, next).catch(next); };
5712
+ `;
5713
+ var backendExpressTypes = () => `// Adds req.user (populated by requireAuth) to Express's Request type.
5714
+ import "express";
5715
+
5716
+ declare global {
5717
+ namespace Express {
5718
+ interface Request {
5719
+ user?: { sub: string; email: string; iat?: number; exp?: number; iss?: string };
5720
+ }
5721
+ }
5722
+ }
5723
+
5724
+ export {};
5725
+ `;
5726
+ var backendErrorMw = () => `import type { Request, Response, NextFunction } from "express";
5727
+ import { ValidationError } from "@lacspace/validate";
5728
+ import { HttpError } from "../http.js";
5729
+
5730
+ // how this works: ONE place that turns thrown errors into clean JSON responses.
5731
+ // Register it LAST (after all routes). Express identifies it by its 4 arguments.
5732
+ export function errorHandler(err: unknown, _req: Request, res: Response, _next: NextFunction): void {
5733
+ if (err instanceof ValidationError) {
5734
+ res.status(400).json({ error: "Validation failed", fields: err.flatten() });
5735
+ return;
5736
+ }
5737
+ if (err instanceof HttpError) {
5738
+ res.status(err.status).json({ error: err.message });
5739
+ return;
5740
+ }
5741
+ console.error(err);
5742
+ res.status(500).json({ error: "Internal server error" });
5743
+ }
5744
+ `;
5745
+ var backendAuthMw = (ctx) => `import type { RequestHandler } from "express";
5746
+ import { expressJwt } from "@lacspace/jwt";
5747
+ import { env } from "../env.js";
5748
+
5749
+ // how this works: verifies the "Authorization: Bearer <token>" header with
5750
+ // @lacspace/jwt and attaches the decoded payload to req.user (see express.d.ts).
5751
+ // Missing/invalid token \u2192 it responds 401 automatically. Put it on any route you
5752
+ // want protected: router.get("/secret", requireAuth, handler)
5753
+ // (@lacspace/jwt's middleware is framework-agnostic, so we cast it to Express's
5754
+ // RequestHandler \u2014 it's a standard (req, res, next) function underneath.)
5755
+ export const requireAuth = expressJwt(env.JWT_SECRET, { issuer: "${ctx.name}-api" }) as unknown as RequestHandler;
5756
+ `;
5757
+ var backendUserModel = () => `import mongoose from "mongoose";
5758
+ import { uuidv7 } from "@lacspace/id";
5759
+
5760
+ // how this works: the User fields. _id is a time-sortable UUID (@lacspace/id)
5761
+ // instead of an ObjectId, so ids are readable and orderable. We store only a
5762
+ // password HASH, never the raw password. (We DON'T extend mongoose.Document \u2014 that
5763
+ // would force _id to be an ObjectId; a plain interface lets _id be our string.)
5764
+ export interface UserDoc {
5765
+ _id: string;
5766
+ email: string;
5767
+ name: string;
5768
+ passwordHash: string;
5769
+ createdAt: Date;
5770
+ updatedAt: Date;
5771
+ }
5772
+
5773
+ const userSchema = new mongoose.Schema<UserDoc>(
5774
+ {
5775
+ _id: { type: String, default: () => uuidv7() },
5776
+ email: { type: String, required: true, unique: true, lowercase: true, trim: true },
5777
+ name: { type: String, required: true, trim: true },
5778
+ passwordHash: { type: String, required: true },
5779
+ },
5780
+ { timestamps: true },
5781
+ );
5782
+
5783
+ export const User =
5784
+ (mongoose.models.User as mongoose.Model<UserDoc>) ?? mongoose.model<UserDoc>("User", userSchema);
5785
+ `;
5786
+ var backendNoteModel = () => `import mongoose from "mongoose";
5787
+ import { uuidv7 } from "@lacspace/id";
5788
+
5789
+ // how this works: the example CRUD resource. Rename "Note" to your real domain
5790
+ // object (Task, Post, Product\u2026) and add fields \u2014 the routes follow the same shape.
5791
+ // (Plain interface, not mongoose.Document, so _id can be our string UUID.)
5792
+ export interface NoteDoc {
5793
+ _id: string;
5794
+ title: string;
5795
+ body: string;
5796
+ userId: string;
5797
+ createdAt: Date;
5798
+ updatedAt: Date;
5799
+ }
5800
+
5801
+ const noteSchema = new mongoose.Schema<NoteDoc>(
5802
+ {
5803
+ _id: { type: String, default: () => uuidv7() },
5804
+ title: { type: String, required: true, trim: true },
5805
+ body: { type: String, default: "" },
5806
+ userId: { type: String, required: true, index: true },
5807
+ },
5808
+ { timestamps: true },
5809
+ );
5810
+
5811
+ export const Note =
5812
+ (mongoose.models.Note as mongoose.Model<NoteDoc>) ?? mongoose.model<NoteDoc>("Note", noteSchema);
5813
+ `;
5814
+ var backendValidation = () => `import { v, type Infer } from "@lacspace/validate";
5815
+
5816
+ // how this works: Zod-like schemas (@lacspace/validate). .parse(body) throws a
5817
+ // ValidationError on bad input, which the error middleware turns into a clean 400
5818
+ // with per-field messages.
5819
+ export const RegisterInput = v.object({
5820
+ name: v.string().min(2).max(80),
5821
+ email: v.string().email(),
5822
+ password: v.string().min(8).max(200),
5823
+ });
5824
+
5825
+ export const LoginInput = v.object({
5826
+ email: v.string().email(),
5827
+ password: v.string().min(1),
5828
+ });
5829
+
5830
+ export const NoteInput = v.object({
5831
+ title: v.string().min(1).max(200),
5832
+ body: v.string().max(10_000).default(""),
5833
+ });
5834
+
5835
+ export type RegisterBody = Infer<typeof RegisterInput>;
5836
+ export type LoginBody = Infer<typeof LoginInput>;
5837
+ export type NoteBody = Infer<typeof NoteInput>;
5838
+ `;
5839
+ var backendAuthRoutes = (ctx) => `import express from "express";
5840
+ import { hash, verify as verifyPassword } from "@lacspace/password";
5841
+ import { sign } from "@lacspace/jwt";
5842
+ import { asyncHandler, HttpError } from "../http.js";
5843
+ import { requireAuth } from "../middleware/auth.js";
5844
+ import { User, type UserDoc } from "../models/user.js";
5845
+ import { env } from "../env.js";
5846
+ import { RegisterInput, LoginInput } from "../validation.js";
5847
+ import type { AuthResponse, User as UserDTO } from "${scope(ctx)}/types";
5848
+
5849
+ const ISSUER = "${ctx.name}-api";
5850
+ const WEEK = 60 * 60 * 24 * 7; // token lifetime, in seconds
5851
+ const router = express.Router();
5852
+
5853
+ function toDTO(u: UserDoc): UserDTO {
5854
+ return { id: String(u._id), email: u.email, name: u.name, createdAt: u.createdAt.toISOString() };
5855
+ }
5856
+ function tokenFor(u: UserDoc): Promise<string> {
5857
+ return sign({ sub: String(u._id), email: u.email }, env.JWT_SECRET, { expiresIn: WEEK, issuer: ISSUER });
5858
+ }
5859
+
5860
+ // POST /auth/register \u2014 create an account, return a JWT + the user.
5861
+ router.post("/register", asyncHandler(async (req, res) => {
5862
+ const { name, email, password } = RegisterInput.parse(req.body);
5863
+ if (await User.findOne({ email })) throw new HttpError(409, "That email is already registered");
5864
+ const passwordHash = await hash(password); // PBKDF2 via @lacspace/password
5865
+ const user = await User.create({ name, email, passwordHash });
5866
+ const out: AuthResponse = { token: await tokenFor(user), user: toDTO(user) };
5867
+ res.status(201).json(out);
5868
+ }));
5869
+
5870
+ // POST /auth/login \u2014 verify credentials, return a JWT + the user.
5871
+ router.post("/login", asyncHandler(async (req, res) => {
5872
+ const { email, password } = LoginInput.parse(req.body);
5873
+ const user = await User.findOne({ email });
5874
+ if (!user || !(await verifyPassword(password, user.passwordHash))) {
5875
+ throw new HttpError(401, "Invalid email or password");
5876
+ }
5877
+ const out: AuthResponse = { token: await tokenFor(user), user: toDTO(user) };
5878
+ res.json(out);
5879
+ }));
5880
+
5881
+ // GET /auth/me \u2014 the current user (requires a valid token).
5882
+ router.get("/me", requireAuth, asyncHandler(async (req, res) => {
5883
+ const user = await User.findById(req.user!.sub);
5884
+ if (!user) throw new HttpError(404, "User not found");
5885
+ res.json(toDTO(user));
5886
+ }));
5887
+
5888
+ export default router;
5889
+ `;
5890
+ var backendNoteRoutes = (ctx) => `import express from "express";
5891
+ import { asyncHandler, HttpError } from "../http.js";
5892
+ import { requireAuth } from "../middleware/auth.js";
5893
+ import { Note, type NoteDoc } from "../models/note.js";
5894
+ import { cache } from "../cache.js";
5895
+ import { NoteInput } from "../validation.js";
5896
+ import type { Note as NoteDTO } from "${scope(ctx)}/types";
5897
+
5898
+ const router = express.Router();
5899
+ router.use(requireAuth); // every /notes route requires a valid token
5900
+
5901
+ function toDTO(n: NoteDoc): NoteDTO {
5902
+ return {
5903
+ id: String(n._id),
5904
+ title: n.title,
5905
+ body: n.body,
5906
+ userId: String(n.userId),
5907
+ createdAt: n.createdAt.toISOString(),
5908
+ updatedAt: n.updatedAt.toISOString(),
5909
+ };
5910
+ }
5911
+ const listKey = (userId: string): string => \`notes:\${userId}\`;
5912
+
5913
+ // GET /notes \u2014 this user's notes. Cached for 30s (Redis or in-memory); every write
5914
+ // below busts the cache, so reads are fast but never stale after a change.
5915
+ router.get("/", asyncHandler(async (req, res) => {
5916
+ const userId = req.user!.sub;
5917
+ const cached = await cache.get(listKey(userId));
5918
+ if (cached) { res.json(JSON.parse(cached) as NoteDTO[]); return; }
5919
+ const notes = await Note.find({ userId }).sort({ createdAt: -1 });
5920
+ const dto = notes.map(toDTO);
5921
+ await cache.set(listKey(userId), JSON.stringify(dto), 30);
5922
+ res.json(dto);
5923
+ }));
5924
+
5925
+ // POST /notes \u2014 create a note.
5926
+ router.post("/", asyncHandler(async (req, res) => {
5927
+ const userId = req.user!.sub;
5928
+ const { title, body } = NoteInput.parse(req.body);
5929
+ const note = await Note.create({ title, body, userId });
5930
+ await cache.del(listKey(userId));
5931
+ res.status(201).json(toDTO(note));
5932
+ }));
5933
+
5934
+ // GET /notes/:id \u2014 one note (only if it's yours).
5935
+ router.get("/:id", asyncHandler(async (req, res) => {
5936
+ const note = await Note.findOne({ _id: req.params.id, userId: req.user!.sub });
5937
+ if (!note) throw new HttpError(404, "Note not found");
5938
+ res.json(toDTO(note));
5939
+ }));
5940
+
5941
+ // PATCH /notes/:id \u2014 update a note.
5942
+ router.patch("/:id", asyncHandler(async (req, res) => {
5943
+ const patch = NoteInput.partial().parse(req.body);
5944
+ const note = await Note.findOneAndUpdate({ _id: req.params.id, userId: req.user!.sub }, { $set: patch }, { new: true });
5945
+ if (!note) throw new HttpError(404, "Note not found");
5946
+ await cache.del(listKey(req.user!.sub));
5947
+ res.json(toDTO(note));
5948
+ }));
5949
+
5950
+ // DELETE /notes/:id \u2014 delete a note.
5951
+ router.delete("/:id", asyncHandler(async (req, res) => {
5952
+ const note = await Note.findOneAndDelete({ _id: req.params.id, userId: req.user!.sub });
5953
+ if (!note) throw new HttpError(404, "Note not found");
5954
+ await cache.del(listKey(req.user!.sub));
5955
+ res.status(204).end();
5956
+ }));
5957
+
5958
+ export default router;
5959
+ `;
5960
+ var backendApp = (ctx) => `import express from "express";
5961
+ import type { RequestHandler } from "express";
5962
+ import cors from "cors";
5963
+ import { rateLimit, expressRateLimit } from "@lacspace/rate-limit";
5964
+ import { env } from "./env.js";
5965
+ import { errorHandler } from "./middleware/error.js";
5966
+ import authRoutes from "./routes/auth.js";
5967
+ import noteRoutes from "./routes/notes.js";
5968
+
5969
+ // 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.
5971
+ export function createApp(): express.Express {
5972
+ const app = express();
5973
+
5974
+ app.use(cors({ origin: env.CORS_ORIGIN.split(",").map((o) => o.trim()), credentials: true }));
5975
+ app.use(express.json());
5976
+
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
+ app.get("/health", (_req, res) => { res.json({ ok: true, service: "${ctx.name}-api" }); });
5981
+ app.use("/auth", authLimiter, authRoutes);
5982
+ app.use("/notes", noteRoutes);
5983
+
5984
+ app.use(errorHandler);
5985
+ return app;
5986
+ }
5987
+ `;
5988
+ function backendFiles(ctx) {
5989
+ return {
5990
+ "backend/package.json": backendPkgJson(ctx),
5991
+ "backend/tsconfig.json": backendTsconfig(ctx),
5992
+ "backend/.gitignore": backendGitignore(),
5993
+ "backend/README.md": backendReadme(ctx),
5994
+ "backend/src/index.ts": backendIndex(ctx),
5995
+ "backend/src/load-env.ts": backendLoadEnv(),
5996
+ "backend/src/env.ts": backendEnv(ctx),
5997
+ "backend/src/db.ts": backendDb(),
5998
+ "backend/src/cache.ts": backendCache(),
5999
+ "backend/src/app.ts": backendApp(ctx),
6000
+ "backend/src/http.ts": backendHttp(),
6001
+ "backend/src/express.d.ts": backendExpressTypes(),
6002
+ "backend/src/validation.ts": backendValidation(),
6003
+ "backend/src/middleware/auth.ts": backendAuthMw(ctx),
6004
+ "backend/src/middleware/error.ts": backendErrorMw(),
6005
+ "backend/src/models/user.ts": backendUserModel(),
6006
+ "backend/src/models/note.ts": backendNoteModel(),
6007
+ "backend/src/routes/auth.ts": backendAuthRoutes(ctx),
6008
+ "backend/src/routes/notes.ts": backendNoteRoutes(ctx)
6009
+ };
6010
+ }
6011
+ var splitList = (s) => s.split(",").map((x) => x.trim()).filter(Boolean);
4556
6012
  function parseArgs(list) {
4557
- const a = { yes: false, install: true, git: true, pm: "npm", help: false };
6013
+ const a = { features: [], yes: false, install: true, git: true, pm: "npm", help: false };
4558
6014
  for (let i = 0; i < list.length; i++) {
4559
6015
  const arg = list[i];
4560
6016
  const next = () => list[++i] ?? "";
@@ -4564,10 +6020,21 @@ function parseArgs(list) {
4564
6020
  else if (arg === "--no-git") a.git = false;
4565
6021
  else if (arg === "--pm") a.pm = next();
4566
6022
  else if (arg === "--theme" || arg === "--accent") a.theme = next();
4567
- else if (arg === "-h" || arg === "--help") a.help = true;
6023
+ else if (arg === "--with" || arg === "--features") a.features.push(...splitList(next()));
6024
+ else if (arg === "--fullstack" || arg === "--full-stack" || arg === "--dynamic") a.mode = "dynamic";
6025
+ else if (arg === "--static") a.mode = "static";
6026
+ else if (arg === "--mode") {
6027
+ const m = next().toLowerCase();
6028
+ a.mode = m === "dynamic" ? "dynamic" : "static";
6029
+ } else if (arg.startsWith("--mode=")) {
6030
+ const m = arg.slice(7).toLowerCase();
6031
+ a.mode = m === "dynamic" ? "dynamic" : "static";
6032
+ } else if (arg === "-h" || arg === "--help") a.help = true;
4568
6033
  else if (arg.startsWith("--template=")) a.template = arg.slice(11);
4569
6034
  else if (arg.startsWith("--theme=")) a.theme = arg.slice(8);
4570
6035
  else if (arg.startsWith("--accent=")) a.theme = arg.slice(9);
6036
+ else if (arg.startsWith("--with=")) a.features.push(...splitList(arg.slice(7)));
6037
+ else if (arg.startsWith("--features=")) a.features.push(...splitList(arg.slice(11)));
4571
6038
  else if (!arg.startsWith("-") && !a.name) a.name = arg;
4572
6039
  }
4573
6040
  return a;
@@ -4662,6 +6129,10 @@ ${TEMPLATES.map((t) => ` ${t.key.padEnd(10)} ${t.description}`).join("\n")}
4662
6129
 
4663
6130
  ${c("bold", "Options")}
4664
6131
  -t, --template <key> Template (${TEMPLATES.map((t) => t.key).join(" | ")})
6132
+ --fullstack Full-stack monorepo: Next.js frontend + Node/Express/
6133
+ MongoDB/Redis backend (JWT auth + CRUD) + shared types
6134
+ ${c("dim", "(alias --dynamic; default is --static, a single Next.js app)")}
6135
+ --with <a,b> Feature add-ons, comma-separated (alias --features)
4665
6136
  --theme <name|hex> Accent: a preset, a "#hex", or "from,to" (e.g. --theme lacspace)
4666
6137
  --pm <npm|pnpm|yarn|bun> Package manager (default npm)
4667
6138
  --no-install Skip installing dependencies
@@ -4669,13 +6140,18 @@ ${c("bold", "Options")}
4669
6140
  -y, --yes Accept defaults (needs <name>)
4670
6141
  -h, --help Show this help
4671
6142
 
6143
+ ${c("bold", "Feature add-ons")} ${c("dim", "(--with) \u2014 free & keyless, local by default")}
6144
+ ${FEATURES.map((f) => ` ${f.key.padEnd(10)} ${f.description}`).join("\n")}
6145
+ ${c("dim", "e.g. npx create-lacspace-app my-app --template saas --with ai-chat,rag")}
6146
+
4672
6147
  ${c("bold", "Themes")} ${c("dim", "(--theme)")}
4673
6148
  ${Object.keys(THEMES).join(" \xB7 ")}
4674
6149
  ${c("dim", 'or a custom colour: --theme "#ff6a00" \xB7 --theme "#0bb9d9,#7c3aed"')}
4675
6150
 
4676
- ${c("bold", "Add sections to an existing app")}
4677
- npx create-lacspace-app add pricing faq testimonials
4678
- ${c("dim", "Drops prebuilt, themed sections into components/sections/ (and the UI kit if missing).")}
6151
+ ${c("bold", "Grow an existing app")}
6152
+ npx create-lacspace-app add pricing faq testimonials ${c("dim", "# prebuilt sections")}
6153
+ npx create-lacspace-app add ai-chat ${c("dim", "# a feature add-on")}
6154
+ ${c("dim", "Drops themed sections / feature files into your project (and the UI kit if missing).")}
4679
6155
  `;
4680
6156
  var SECTIONS = {
4681
6157
  hero: `import Link from "next/link";
@@ -4915,7 +6391,7 @@ function ensureUiKit(root) {
4915
6391
  var pascal = (s) => s.split(/[-_]/).map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join("");
4916
6392
  function runAdd(rawNames) {
4917
6393
  stdout.write(`
4918
- ${c("bold", c("magenta", "\u25C6 create-lacspace-app add"))} ${c("dim", "\u2014 drop prebuilt sections into your app")}
6394
+ ${c("bold", c("magenta", "\u25C6 create-lacspace-app add"))} ${c("dim", "\u2014 drop prebuilt sections or a feature into your app")}
4919
6395
 
4920
6396
  `);
4921
6397
  const root = cwd();
@@ -4926,56 +6402,108 @@ ${c("bold", c("magenta", "\u25C6 create-lacspace-app add"))} ${c("dim", "\u2014
4926
6402
  }
4927
6403
  const wanted = rawNames.filter((n) => !n.startsWith("-")).map((n) => n.toLowerCase());
4928
6404
  if (wanted.length === 0 || rawNames.includes("--help") || rawNames.includes("-h")) {
4929
- stdout.write(`Usage: ${c("cyan", "npx create-lacspace-app add <section...>")}
6405
+ stdout.write(`Usage: ${c("cyan", "npx create-lacspace-app add <section|feature...>")}
4930
6406
 
4931
6407
  ${c("bold", "Available sections")}
4932
6408
  `);
4933
6409
  stdout.write(" " + Object.keys(SECTIONS).map((k) => c("cyan", k)).join(" ") + "\n");
4934
6410
  stdout.write(`
4935
- Example: ${c("cyan", "npx create-lacspace-app add pricing faq testimonials")}
6411
+ ${c("bold", "Available features")}
6412
+ `);
6413
+ stdout.write(" " + FEATURES.map((f) => c("cyan", f.key)).join(" ") + "\n");
6414
+ stdout.write(`
6415
+ Example: ${c("cyan", "npx create-lacspace-app add pricing faq")} ${c("dim", "or")} ${c("cyan", "add ai-chat")}
4936
6416
 
4937
6417
  `);
4938
6418
  return;
4939
6419
  }
4940
- const unknown = wanted.filter((n) => !(n in SECTIONS));
6420
+ const featKeys = wanted.filter((n) => FEATURES.some((f) => f.key === n));
6421
+ const sectionNames = wanted.filter((n) => n in SECTIONS);
6422
+ const unknown = wanted.filter((n) => !featKeys.includes(n) && !(n in SECTIONS));
4941
6423
  if (unknown.length) stdout.write(c("yellow", `! Unknown: ${unknown.join(", ")} ${c("dim", "(run with no args to list)")}
4942
6424
  `));
4943
- const toAdd = wanted.filter((n) => n in SECTIONS);
4944
- if (toAdd.length === 0) {
4945
- exit(1);
4946
- return;
4947
- }
4948
- const kitAdded = ensureUiKit(root);
4949
- if (kitAdded.length) stdout.write(` ${c("green", "\u2714")} Added the UI kit ${c("dim", "(" + kitAdded.length + " components)")}
6425
+ const addedFeatures = featKeys.map((k) => FEATURES.find((f) => f.key === k));
6426
+ if (addedFeatures.length) {
6427
+ const ctx = resolveContext({ name: basename(root), features: featKeys });
6428
+ for (const feat of addedFeatures) {
6429
+ stdout.write(`
6430
+ ${c("bold", `+ ${feat.label}`)} ${c("dim", `(${feat.key})`)}
4950
6431
  `);
4951
- const created = [];
4952
- for (const name of toAdd) {
4953
- const rel = `components/sections/${name}.tsx`;
4954
- const full = join(root, rel);
4955
- if (existsSync(full)) {
4956
- stdout.write(c("yellow", ` ~ ${rel} exists \u2014 skipped
6432
+ for (const [rel, content] of Object.entries(feat.files(ctx))) {
6433
+ const full = join(root, rel);
6434
+ if (existsSync(full)) {
6435
+ stdout.write(c("yellow", ` ~ ${rel} exists \u2014 skipped
4957
6436
  `));
4958
- continue;
4959
- }
4960
- mkdirSync(dirname(full), { recursive: true });
4961
- writeFileSync(full, SECTIONS[name]);
4962
- created.push(name);
4963
- stdout.write(` ${c("green", "\u2714")} ${c("dim", "+ " + rel)}
6437
+ continue;
6438
+ }
6439
+ mkdirSync(dirname(full), { recursive: true });
6440
+ writeFileSync(full, content);
6441
+ stdout.write(` ${c("green", "\u2714")} ${c("dim", "+ " + rel)}
6442
+ `);
6443
+ }
6444
+ stdout.write(`
6445
+ ${c("bold", "Add these dependencies")}:
6446
+ ${c("cyan", "npm i " + Object.entries(feat.deps).map(([n, v]) => `${n}@${v}`).join(" "))}
6447
+ `);
6448
+ if (feat.scripts && Object.keys(feat.scripts).length) {
6449
+ stdout.write(`
6450
+ ${c("bold", "Add to package.json scripts")}:
6451
+ `);
6452
+ for (const [n, v] of Object.entries(feat.scripts)) stdout.write(` ${c("cyan", `"${n}": "${v}"`)}
4964
6453
  `);
6454
+ }
6455
+ if (feat.env && Object.keys(feat.env).length) {
6456
+ stdout.write(`
6457
+ ${c("bold", "Add to .env")}:
6458
+ `);
6459
+ for (const [n, comment] of Object.entries(feat.env)) stdout.write(` ${c("cyan", n + "=")} ${c("dim", "# " + comment)}
6460
+ `);
6461
+ }
6462
+ stdout.write(`
6463
+ ${c("bold", "Next steps")}:
6464
+ `);
6465
+ for (const s of feat.nextSteps) stdout.write(` ${c("dim", "\u2022")} ${s}
6466
+ `);
6467
+ }
6468
+ stdout.write("\n");
4965
6469
  }
4966
- if (created.length) {
4967
- stdout.write(`
6470
+ if (sectionNames.length) {
6471
+ const kitAdded = ensureUiKit(root);
6472
+ if (kitAdded.length) stdout.write(` ${c("green", "\u2714")} Added the UI kit ${c("dim", "(" + kitAdded.length + " components)")}
6473
+ `);
6474
+ const created = [];
6475
+ for (const name of sectionNames) {
6476
+ const rel = `components/sections/${name}.tsx`;
6477
+ const full = join(root, rel);
6478
+ if (existsSync(full)) {
6479
+ stdout.write(c("yellow", ` ~ ${rel} exists \u2014 skipped
6480
+ `));
6481
+ continue;
6482
+ }
6483
+ mkdirSync(dirname(full), { recursive: true });
6484
+ writeFileSync(full, SECTIONS[name]);
6485
+ created.push(name);
6486
+ stdout.write(` ${c("green", "\u2714")} ${c("dim", "+ " + rel)}
6487
+ `);
6488
+ }
6489
+ if (created.length) {
6490
+ stdout.write(`
4968
6491
  ${c("bold", "Use them")} \u2014 import into any page:
4969
6492
  `);
4970
- for (const n of created) stdout.write(` ${c("cyan", `import { ${pascal(n)}Section } from "@/components/sections/${n}";`)}
6493
+ for (const n of created) stdout.write(` ${c("cyan", `import { ${pascal(n)}Section } from "@/components/sections/${n}";`)}
4971
6494
  `);
4972
- stdout.write(`
6495
+ stdout.write(`
4973
6496
  Then drop ${c("cyan", "<" + pascal(created[0]) + "Section />")} into your JSX.
4974
6497
  `);
4975
- stdout.write(`
6498
+ stdout.write(`
4976
6499
  ${c("dim", "Sections use the @lacspace UI kit + design tokens \u2014 best inside a create-lacspace-app project.")}
4977
6500
 
4978
6501
  `);
6502
+ }
6503
+ }
6504
+ if (!addedFeatures.length && !sectionNames.length) {
6505
+ exit(1);
6506
+ return;
4979
6507
  }
4980
6508
  }
4981
6509
  async function main() {
@@ -4995,7 +6523,9 @@ ${c("bold", c("magenta", "\u25C6 create-lacspace-app"))} ${c("dim", "\u2014 a go
4995
6523
  `);
4996
6524
  let name = args.name;
4997
6525
  let templateKey = args.template;
4998
- if (!args.yes) {
6526
+ let mode = args.mode ?? "static";
6527
+ const featureKeys = [...args.features];
6528
+ if (!args.yes && stdin.isTTY) {
4999
6529
  const rl = createInterface({ input: stdin, output: stdout });
5000
6530
  try {
5001
6531
  if (!name) name = (await rl.question(`${c("green", "?")} Project name ${c("dim", "(my-app)")}: `)).trim() || "my-app";
@@ -5010,6 +6540,34 @@ ${c("green", "?")} Template ${c("dim", "(1)")}: `)).trim() || "1";
5010
6540
  const idx = /^\d+$/.test(ans) ? parseInt(ans, 10) - 1 : TEMPLATES.findIndex((t) => t.key === ans);
5011
6541
  templateKey = TEMPLATES[idx]?.key ?? "personal";
5012
6542
  }
6543
+ if (args.mode === void 0) {
6544
+ stdout.write(`
6545
+ What kind of app?
6546
+ `);
6547
+ stdout.write(` ${c("cyan", "1")}. ${c("bold", "Static / frontend only")} ${c("dim", "\u2014 a single Next.js app (SEO site, marketing, blog, docs). Fast, deploy anywhere.")}
6548
+ `);
6549
+ stdout.write(` ${c("cyan", "2")}. ${c("bold", "Dynamic / full-stack")} ${c("dim", "\u2014 frontend + a Node\xB7Express\xB7MongoDB\xB7Redis API with working auth & CRUD, wired together.")}
6550
+ `);
6551
+ const ans = (await rl.question(`
6552
+ ${c("green", "?")} Type ${c("dim", "(1)")}: `)).trim() || "1";
6553
+ mode = ans === "2" || ans.toLowerCase().startsWith("dyn") || ans.toLowerCase().startsWith("full") ? "dynamic" : "static";
6554
+ }
6555
+ if (featureKeys.length === 0) {
6556
+ stdout.write(`
6557
+ Add feature add-ons? ${c("dim", "(free & keyless \u2014 local AI by default)")}
6558
+ `);
6559
+ FEATURES.forEach((f, i) => stdout.write(` ${c("cyan", String(i + 1))}. ${c("bold", f.label)} ${c("dim", "\u2014 " + f.description)}
6560
+ `));
6561
+ const ans = (await rl.question(`
6562
+ ${c("green", "?")} Add features? ${c("dim", "(comma-separated numbers, or Enter for none)")}: `)).trim();
6563
+ if (ans) {
6564
+ for (const tok of splitList(ans)) {
6565
+ const idx = /^\d+$/.test(tok) ? parseInt(tok, 10) - 1 : FEATURES.findIndex((f) => f.key === tok);
6566
+ const feat = FEATURES[idx];
6567
+ if (feat && !featureKeys.includes(feat.key)) featureKeys.push(feat.key);
6568
+ }
6569
+ }
6570
+ }
5013
6571
  } finally {
5014
6572
  rl.close();
5015
6573
  }
@@ -5034,14 +6592,18 @@ ${c("green", "?")} Template ${c("dim", "(1)")}: `)).trim() || "1";
5034
6592
  exit(1);
5035
6593
  return;
5036
6594
  }
5037
- const files = buildFiles({ name: projectName, template });
6595
+ const features = normalizeFeatures(featureKeys);
6596
+ const files = buildFiles({ name: projectName, template, features, mode });
5038
6597
  for (const [rel, content] of Object.entries(files)) {
5039
6598
  const full = join(dir, rel);
5040
6599
  mkdirSync(dirname(full), { recursive: true });
5041
6600
  writeFileSync(full, content);
5042
6601
  }
6602
+ const shape = mode === "dynamic" ? " \xB7 full-stack" : "";
5043
6603
  stdout.write(`
5044
- ${c("green", "\u2714")} Created ${c("bold", name)} ${c("dim", `(${template.label})`)}
6604
+ ${c("green", "\u2714")} Created ${c("bold", name)} ${c("dim", `(${template.label}${shape})`)}
6605
+ `);
6606
+ if (features.length) stdout.write(` ${c("green", "\u2714")} Feature add-ons: ${features.map((f) => c("cyan", f.key)).join(", ")}
5045
6607
  `);
5046
6608
  for (const rel of Object.keys(files)) stdout.write(` ${c("dim", "+ " + rel)}
5047
6609
  `);
@@ -5069,11 +6631,40 @@ ${c("bold", "Done! Next steps")}
5069
6631
  `);
5070
6632
  if (!args.install) stdout.write(` ${c("cyan", `${args.pm} install`)}
5071
6633
  `);
5072
- stdout.write(` ${c("cyan", run)}
6634
+ if (mode === "dynamic") {
6635
+ stdout.write(` ${c("cyan", "cp .env.example .env")} ${c("dim", "\u2014 then, optionally:")} ${c("cyan", "docker compose up -d")} ${c("dim", "(Mongo + Redis)")}
5073
6636
  `);
5074
- stdout.write(`
6637
+ stdout.write(` ${c("cyan", run)} ${c("dim", "\u2014 runs the API (:4000) and the frontend (:3000) together")}
6638
+ `);
6639
+ stdout.write(`
6640
+ ${c("dim", "backend \u2192")} ${c("cyan", "backend/src/")} ${c("dim", "(Express \xB7 MongoDB \xB7 Redis \xB7 JWT auth \xB7 example CRUD)")}
6641
+ `);
6642
+ stdout.write(` ${c("dim", "frontend \u2192")} ${c("cyan", "frontend/app/")} ${c("dim", "\xB7 shared API types \u2192")} ${c("cyan", "types/src/")}
6643
+ `);
6644
+ stdout.write(` ${c("dim", "No Docker? Point")} ${c("cyan", "MONGODB_URI")} ${c("dim", "at any MongoDB (e.g. free Atlas); Redis is optional.")}
6645
+ `);
6646
+ } else {
6647
+ stdout.write(` ${c("cyan", run)}
6648
+ `);
6649
+ stdout.write(`
5075
6650
  Edit ${c("cyan", "lib/site.ts")} (your SEO config) and ${c("cyan", "app/page.tsx")}.
5076
6651
  `);
6652
+ }
6653
+ if (features.length) {
6654
+ const hasAi = features.some((f) => f.key === "ai-chat" || f.key === "rag");
6655
+ stdout.write(`
6656
+ ${c("bold", "Your feature add-ons")} ${c("dim", "\u2014 details in LEARN.md")}
6657
+ `);
6658
+ if (hasAi) stdout.write(` ${c("green", "\u{1F193} Free & local AI")} ${c("dim", "\u2014 install Ollama (https://ollama.com); no API key required.")}
6659
+ `);
6660
+ for (const f of features) {
6661
+ stdout.write(`
6662
+ ${c("bold", f.label)} ${c("dim", `(${f.key})`)}
6663
+ `);
6664
+ for (const s of f.nextSteps) stdout.write(` ${c("dim", "\u2022")} ${s}
6665
+ `);
6666
+ }
6667
+ }
5077
6668
  stdout.write(`
5078
6669
  ${c("green", "Happy building!")} ${c("dim", "https://lacspace.com/packages")}
5079
6670
 
@@ -5106,6 +6697,13 @@ function listSections() {
5106
6697
  function getSection(name) {
5107
6698
  return SECTIONS[name];
5108
6699
  }
6700
+ function listFeatures() {
6701
+ return FEATURES.map((f) => ({ ...f }));
6702
+ }
6703
+ function getFeature(key) {
6704
+ const f = FEATURES.find((x) => x.key === key);
6705
+ return f ? { ...f } : void 0;
6706
+ }
5109
6707
  function generateProject(options = {}) {
5110
6708
  return buildFiles(resolveContext(options));
5111
6709
  }
@@ -5121,4 +6719,4 @@ async function scaffold(options = {}) {
5121
6719
  return { dir: target, files: Object.keys(files) };
5122
6720
  }
5123
6721
 
5124
- export { generateProject, getSection, getTemplate, listSections, listTemplates, scaffold, templateKeys, templates };
6722
+ export { generateProject, getFeature, getSection, getTemplate, listFeatures, listSections, listTemplates, scaffold, templateKeys, templates };