cronus-ui 0.6.1 → 0.6.3

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.
@@ -0,0 +1,1057 @@
1
+ /**
2
+ * Authenticated gold path for saas/admin compose: SQLite + Drizzle + Better-Auth.
3
+ * Always sqlite — postgres/mysql live in create-cronus-stack.
4
+ */
5
+ import { existsSync } from "node:fs";
6
+ import { readFile } from "node:fs/promises";
7
+ import { join } from "node:path";
8
+ import { resolveSafeDest, writeFileEnsured } from "../utils.js";
9
+ import { baseSnapshotDir } from "./reload.js";
10
+ export const GOLD_PATH_TEMPLATES = new Set(["saas", "admin"]);
11
+ export function isGoldPathTemplate(name) {
12
+ return GOLD_PATH_TEMPLATES.has(name);
13
+ }
14
+ /** Production npm specs installed with the gold path (devDeps are merged into package.json). */
15
+ export const GOLD_PATH_DEPENDENCIES = [
16
+ "drizzle-orm@^0.45.2",
17
+ "better-sqlite3@^12.0.0",
18
+ "better-auth@^1.7.2",
19
+ ];
20
+ const GOLD_PATH_PROD_DEPS = {
21
+ "drizzle-orm": "^0.45.2",
22
+ "better-sqlite3": "^12.0.0",
23
+ "better-auth": "^1.7.2",
24
+ };
25
+ const GOLD_PATH_DEV_DEPS = {
26
+ "drizzle-kit": "^0.31.10",
27
+ "@types/better-sqlite3": "^9.6.0",
28
+ };
29
+ const GOLD_PATH_SCRIPTS = {
30
+ "db:push": "drizzle-kit push",
31
+ "db:generate": "drizzle-kit generate",
32
+ "db:studio": "drizzle-kit studio",
33
+ };
34
+ const ENV_VARS = {
35
+ DATABASE_URL: "file:./data/app.db",
36
+ BETTER_AUTH_SECRET: "change-me-to-a-32-character-secret",
37
+ BETTER_AUTH_URL: "http://localhost:3000",
38
+ };
39
+ const GITIGNORE_ENTRIES = ["*.db", "data/", "drizzle/"];
40
+ const DATABASE_URL_FALLBACK = "file:./data/app.db";
41
+ const TITLE_MAX = 200;
42
+ export function goldPathLayout(config) {
43
+ const libDir = posix(config.paths.lib);
44
+ const uiDir = posix(config.paths.ui);
45
+ const src = libDir === "src" || libDir.startsWith("src/");
46
+ const prefix = src ? "src/" : "";
47
+ const componentsDir = uiDir.endsWith("/ui")
48
+ ? uiDir.slice(0, -"/ui".length)
49
+ : `${prefix}components`;
50
+ return {
51
+ libDir,
52
+ dbDir: `${prefix}db`,
53
+ appDir: `${prefix}app`,
54
+ componentsDir,
55
+ middlewareRel: `${prefix}middleware.ts`,
56
+ };
57
+ }
58
+ function posix(p) {
59
+ return p.replaceAll("\\", "/");
60
+ }
61
+ function resolveAppDir(targetDir, layout, generatedFiles) {
62
+ const fromGenerated = generatedFiles.find((f) => /(^|\/)\(shell\)\/page\.tsx$/.test(posix(f)));
63
+ if (fromGenerated !== undefined) {
64
+ return posix(fromGenerated).replace(/\/\(shell\)\/page\.tsx$/, "");
65
+ }
66
+ if (existsSync(join(targetDir, "app", "(shell)", "page.tsx")))
67
+ return "app";
68
+ if (existsSync(join(targetDir, "src", "app", "(shell)", "page.tsx")))
69
+ return "src/app";
70
+ if (existsSync(join(targetDir, layout.appDir)))
71
+ return layout.appDir;
72
+ if (existsSync(join(targetDir, "app")))
73
+ return "app";
74
+ if (existsSync(join(targetDir, "src", "app")))
75
+ return "src/app";
76
+ return layout.appDir;
77
+ }
78
+ function homePageRel(appDir, generatedFiles) {
79
+ const match = generatedFiles.find((f) => posix(f) === `${appDir}/(shell)/page.tsx`);
80
+ if (match !== undefined)
81
+ return posix(match);
82
+ const any = generatedFiles.find((f) => /(^|\/)\(shell\)\/page\.tsx$/.test(posix(f)));
83
+ return any !== undefined ? posix(any) : undefined;
84
+ }
85
+ function drizzleConfigSource(dbDir) {
86
+ return `import { mkdirSync } from "node:fs";
87
+ import { dirname } from "node:path";
88
+ import { defineConfig } from "drizzle-kit";
89
+
90
+ const url = process.env.DATABASE_URL ?? "${DATABASE_URL_FALLBACK}";
91
+ const fileFromUrl = url.startsWith("file:") ? url.slice("file:".length) : url;
92
+ mkdirSync(dirname(fileFromUrl) || ".", { recursive: true });
93
+
94
+ export default defineConfig({
95
+ dialect: "sqlite",
96
+ schema: "./${dbDir}/schema.ts",
97
+ out: "./drizzle",
98
+ dbCredentials: { url },
99
+ });
100
+ `;
101
+ }
102
+ function dbSchemaSource() {
103
+ return `import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
104
+
105
+ export const user = sqliteTable("user", {
106
+ id: text("id").primaryKey(),
107
+ name: text("name").notNull(),
108
+ email: text("email").notNull().unique(),
109
+ emailVerified: integer("email_verified", { mode: "boolean" }).notNull(),
110
+ image: text("image"),
111
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
112
+ updatedAt: integer("updated_at", { mode: "timestamp" }).notNull(),
113
+ });
114
+
115
+ export const session = sqliteTable("session", {
116
+ id: text("id").primaryKey(),
117
+ expiresAt: integer("expires_at", { mode: "timestamp" }).notNull(),
118
+ token: text("token").notNull().unique(),
119
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
120
+ updatedAt: integer("updated_at", { mode: "timestamp" }).notNull(),
121
+ ipAddress: text("ip_address"),
122
+ userAgent: text("user_agent"),
123
+ activeOrganizationId: text("active_organization_id"),
124
+ userId: text("user_id")
125
+ .notNull()
126
+ .references(() => user.id, { onDelete: "cascade" }),
127
+ });
128
+
129
+ export const account = sqliteTable("account", {
130
+ id: text("id").primaryKey(),
131
+ issuer: text("issuer").notNull(),
132
+ accountId: text("account_id").notNull(),
133
+ providerId: text("provider_id").notNull(),
134
+ userId: text("user_id")
135
+ .notNull()
136
+ .references(() => user.id, { onDelete: "cascade" }),
137
+ accessToken: text("access_token"),
138
+ refreshToken: text("refresh_token"),
139
+ idToken: text("id_token"),
140
+ accessTokenExpiresAt: integer("access_token_expires_at", { mode: "timestamp" }),
141
+ refreshTokenExpiresAt: integer("refresh_token_expires_at", { mode: "timestamp" }),
142
+ scope: text("scope"),
143
+ password: text("password"),
144
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
145
+ updatedAt: integer("updated_at", { mode: "timestamp" }).notNull(),
146
+ });
147
+
148
+ export const verification = sqliteTable("verification", {
149
+ id: text("id").primaryKey(),
150
+ identifier: text("identifier").notNull(),
151
+ value: text("value").notNull(),
152
+ expiresAt: integer("expires_at", { mode: "timestamp" }).notNull(),
153
+ createdAt: integer("created_at", { mode: "timestamp" }),
154
+ updatedAt: integer("updated_at", { mode: "timestamp" }),
155
+ });
156
+
157
+ export const organization = sqliteTable("organization", {
158
+ id: text("id").primaryKey(),
159
+ name: text("name").notNull(),
160
+ slug: text("slug").notNull().unique(),
161
+ logo: text("logo"),
162
+ metadata: text("metadata"),
163
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
164
+ });
165
+
166
+ export const member = sqliteTable("member", {
167
+ id: text("id").primaryKey(),
168
+ organizationId: text("organization_id")
169
+ .notNull()
170
+ .references(() => organization.id, { onDelete: "cascade" }),
171
+ userId: text("user_id")
172
+ .notNull()
173
+ .references(() => user.id, { onDelete: "cascade" }),
174
+ role: text("role").notNull(),
175
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
176
+ });
177
+
178
+ export const invitation = sqliteTable("invitation", {
179
+ id: text("id").primaryKey(),
180
+ organizationId: text("organization_id")
181
+ .notNull()
182
+ .references(() => organization.id, { onDelete: "cascade" }),
183
+ email: text("email").notNull(),
184
+ role: text("role"),
185
+ status: text("status").notNull(),
186
+ expiresAt: integer("expires_at", { mode: "timestamp" }).notNull(),
187
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
188
+ inviterId: text("inviter_id")
189
+ .notNull()
190
+ .references(() => user.id, { onDelete: "cascade" }),
191
+ });
192
+
193
+ export const items = sqliteTable("items", {
194
+ id: integer("id").primaryKey({ autoIncrement: true }),
195
+ title: text("title").notNull(),
196
+ workspaceId: text("workspace_id").references(() => organization.id, { onDelete: "cascade" }),
197
+ });
198
+ `;
199
+ }
200
+ function dbClientSource() {
201
+ return `import { mkdirSync } from "node:fs";
202
+ import { dirname } from "node:path";
203
+ import Database from "better-sqlite3";
204
+ import { drizzle } from "drizzle-orm/better-sqlite3";
205
+ import * as schema from "./schema";
206
+
207
+ const url = process.env.DATABASE_URL ?? "${DATABASE_URL_FALLBACK}";
208
+ const fileFromUrl = url.startsWith("file:") ? url.slice("file:".length) : url;
209
+ mkdirSync(dirname(fileFromUrl) || ".", { recursive: true });
210
+ const sqlite = new Database(fileFromUrl);
211
+
212
+ export const db = drizzle(sqlite, { schema });
213
+ `;
214
+ }
215
+ function authServerSource() {
216
+ return `import { betterAuth } from "better-auth";
217
+ import { drizzleAdapter } from "better-auth/adapters/drizzle";
218
+ import { nextCookies } from "better-auth/next-js";
219
+ import { organization } from "better-auth/plugins";
220
+ import { and, eq } from "drizzle-orm";
221
+ import { db } from "@/db";
222
+ import * as schema from "@/db/schema";
223
+ import {
224
+ invitation as invitationTable,
225
+ member,
226
+ organization as organizationTable,
227
+ user as userTable,
228
+ } from "@/db/schema";
229
+
230
+ function newId(): string {
231
+ return crypto.randomUUID().replaceAll("-", "");
232
+ }
233
+
234
+ export const auth = betterAuth({
235
+ database: drizzleAdapter(db, { provider: "sqlite", schema }),
236
+ emailAndPassword: {
237
+ enabled: true,
238
+ sendResetPassword: async ({ url }) => {
239
+ console.info(url);
240
+ },
241
+ },
242
+ databaseHooks: {
243
+ session: {
244
+ create: {
245
+ before: async (session) => {
246
+ const [existing] = await db
247
+ .select({ organizationId: member.organizationId })
248
+ .from(member)
249
+ .where(eq(member.userId, session.userId))
250
+ .limit(1);
251
+ if (existing?.organizationId) {
252
+ return { data: { ...session, activeOrganizationId: existing.organizationId } };
253
+ }
254
+ const [owner] = await db
255
+ .select({ name: userTable.name, email: userTable.email })
256
+ .from(userTable)
257
+ .where(eq(userTable.id, session.userId))
258
+ .limit(1);
259
+ if (owner?.email) {
260
+ const [pending] = await db
261
+ .select({ id: invitationTable.id })
262
+ .from(invitationTable)
263
+ .where(
264
+ and(eq(invitationTable.email, owner.email), eq(invitationTable.status, "pending")),
265
+ )
266
+ .limit(1);
267
+ if (pending) return;
268
+ }
269
+ const orgId = newId();
270
+ const now = new Date();
271
+ await db.insert(organizationTable).values({
272
+ id: orgId,
273
+ name: owner?.name.trim() || "Workspace",
274
+ slug: \`ws-\${session.userId.slice(0, 16)}\`,
275
+ createdAt: now,
276
+ });
277
+ await db.insert(member).values({
278
+ id: newId(),
279
+ organizationId: orgId,
280
+ userId: session.userId,
281
+ role: "owner",
282
+ createdAt: now,
283
+ });
284
+ return { data: { ...session, activeOrganizationId: orgId } };
285
+ },
286
+ },
287
+ },
288
+ },
289
+ secret: process.env.BETTER_AUTH_SECRET,
290
+ baseURL: process.env.BETTER_AUTH_URL,
291
+ plugins: [
292
+ organization({
293
+ sendInvitationEmail: async (data) => {
294
+ const base = process.env.BETTER_AUTH_URL ?? "http://localhost:3000";
295
+ console.info(\`Invite \${data.email}: \${base}/accept-invitation?id=\${data.id}\`);
296
+ },
297
+ }),
298
+ nextCookies(),
299
+ ],
300
+ });
301
+ `;
302
+ }
303
+ function authClientSource() {
304
+ return `import { organizationClient } from "better-auth/client/plugins";
305
+ import { createAuthClient } from "better-auth/react";
306
+
307
+ export const authClient = createAuthClient({
308
+ plugins: [organizationClient()],
309
+ });
310
+ `;
311
+ }
312
+ function authAdapterSource() {
313
+ return `import { authClient } from "./auth-client";
314
+
315
+ const INVITE_KEY = "cronus-invitation";
316
+
317
+ function readInvitation(): string | null {
318
+ if (typeof window === "undefined") return null;
319
+ const fromUrl = new URLSearchParams(window.location.search).get("invitation");
320
+ if (fromUrl) {
321
+ sessionStorage.setItem(INVITE_KEY, fromUrl);
322
+ return fromUrl;
323
+ }
324
+ return sessionStorage.getItem(INVITE_KEY);
325
+ }
326
+
327
+ function afterAuthPath(): string {
328
+ const invitation = readInvitation();
329
+ if (invitation) {
330
+ return \`/accept-invitation?id=\${encodeURIComponent(invitation)}\`;
331
+ }
332
+ return "/";
333
+ }
334
+
335
+ if (typeof window !== "undefined") {
336
+ readInvitation();
337
+ }
338
+
339
+ export async function signInEmail({ email, password }: { email: string; password: string }) {
340
+ const callbackURL = afterAuthPath();
341
+ const { error } = await authClient.signIn.email({ email, password, callbackURL });
342
+ if (error) throw new Error(error.message || "Sign in failed");
343
+ window.location.assign(callbackURL);
344
+ }
345
+
346
+ export async function signUpEmail({
347
+ email,
348
+ password,
349
+ name,
350
+ }: {
351
+ email: string;
352
+ password: string;
353
+ name?: string;
354
+ }) {
355
+ const callbackURL = afterAuthPath();
356
+ const { error } = await authClient.signUp.email({
357
+ email,
358
+ password,
359
+ name: name ?? email,
360
+ callbackURL,
361
+ });
362
+ if (error) throw new Error(error.message || "Sign up failed");
363
+ window.location.assign(callbackURL);
364
+ }
365
+
366
+ export async function requestPasswordReset({ email }: { email: string }) {
367
+ const { error } = await authClient.requestPasswordReset({ email, redirectTo: "/login" });
368
+ if (error) throw new Error(error.message || "Reset failed");
369
+ }
370
+ `;
371
+ }
372
+ function authRouteSource(authImport) {
373
+ return `import { toNextJsHandler } from "better-auth/next-js";
374
+ import { auth } from ${JSON.stringify(authImport)};
375
+
376
+ export const { GET, POST } = toNextJsHandler(auth);
377
+ `;
378
+ }
379
+ function middlewareSource() {
380
+ return `import type { NextRequest } from "next/server";
381
+ import { NextResponse } from "next/server";
382
+ import { getSessionCookie } from "better-auth/cookies";
383
+
384
+ const AUTH_PAGES = ["/login", "/signup", "/forgot-password"];
385
+
386
+ function invitationOf(request: NextRequest): string | null {
387
+ const { pathname, searchParams } = request.nextUrl;
388
+ return (
389
+ searchParams.get("invitation") ??
390
+ (pathname === "/accept-invitation" ? searchParams.get("id") : null)
391
+ );
392
+ }
393
+
394
+ export function middleware(request: NextRequest) {
395
+ const { pathname } = request.nextUrl;
396
+ if (
397
+ pathname.startsWith("/api/auth") ||
398
+ pathname.startsWith("/_next") ||
399
+ pathname === "/favicon.ico"
400
+ ) {
401
+ return NextResponse.next();
402
+ }
403
+
404
+ const sessionCookie = getSessionCookie(request);
405
+ const isAuthPage = AUTH_PAGES.includes(pathname);
406
+ const invitation = invitationOf(request);
407
+
408
+ if (!sessionCookie && pathname === "/accept-invitation") {
409
+ const url = new URL("/signup", request.url);
410
+ if (invitation) url.searchParams.set("invitation", invitation);
411
+ return NextResponse.redirect(url);
412
+ }
413
+ if (!sessionCookie && !isAuthPage) {
414
+ const url = new URL("/login", request.url);
415
+ if (invitation) url.searchParams.set("invitation", invitation);
416
+ return NextResponse.redirect(url);
417
+ }
418
+ if (sessionCookie && isAuthPage) {
419
+ if (invitation) {
420
+ return NextResponse.redirect(
421
+ new URL(\`/accept-invitation?id=\${encodeURIComponent(invitation)}\`, request.url),
422
+ );
423
+ }
424
+ return NextResponse.redirect(new URL("/", request.url));
425
+ }
426
+ return NextResponse.next();
427
+ }
428
+
429
+ export const config = {
430
+ matcher: [
431
+ "/((?!_next/static|_next/image|favicon.ico|.*\\\\.(?:svg|png|jpg|jpeg|gif|webp|ico)$).*)",
432
+ ],
433
+ };
434
+ `;
435
+ }
436
+ function itemsActionsSource(authImport) {
437
+ return `"use server";
438
+
439
+ import { and, desc, eq } from "drizzle-orm";
440
+ import { revalidatePath } from "next/cache";
441
+ import { headers } from "next/headers";
442
+ import { db } from "@/db";
443
+ import { items, member, organization } from "@/db/schema";
444
+ import { auth } from ${JSON.stringify(authImport)};
445
+
446
+ const TITLE_MAX = ${TITLE_MAX};
447
+
448
+ async function activeWorkspaceId(): Promise<string | null> {
449
+ const session = await auth.api.getSession({ headers: await headers() });
450
+ const userId = session?.user?.id;
451
+ if (!userId) return null;
452
+ const hinted = session.session?.activeOrganizationId ?? null;
453
+ if (hinted) {
454
+ const [membership] = await db
455
+ .select({ organizationId: member.organizationId })
456
+ .from(member)
457
+ .where(and(eq(member.userId, userId), eq(member.organizationId, hinted)))
458
+ .limit(1);
459
+ if (membership?.organizationId) return membership.organizationId;
460
+ }
461
+ const [row] = await db
462
+ .select({ organizationId: member.organizationId })
463
+ .from(member)
464
+ .where(eq(member.userId, userId))
465
+ .limit(1);
466
+ return row?.organizationId ?? null;
467
+ }
468
+
469
+ export async function loadItems(): Promise<{
470
+ email: string;
471
+ workspace: string;
472
+ rows: { id: number; title: string }[];
473
+ }> {
474
+ const session = await auth.api.getSession({ headers: await headers() });
475
+ const email = session?.user?.email ?? "signed out";
476
+ const orgId = await activeWorkspaceId();
477
+ if (!orgId) return { email, workspace: "no workspace", rows: [] };
478
+ const [org] = await db.select().from(organization).where(eq(organization.id, orgId)).limit(1);
479
+ const rows = await db
480
+ .select({ id: items.id, title: items.title })
481
+ .from(items)
482
+ .where(eq(items.workspaceId, orgId))
483
+ .orderBy(desc(items.id));
484
+ return { email, workspace: org?.name ?? "no workspace", rows };
485
+ }
486
+
487
+ export async function createItem(formData: FormData) {
488
+ const orgId = await activeWorkspaceId();
489
+ if (!orgId) return;
490
+ const title = String(formData.get("title") ?? "")
491
+ .trim()
492
+ .slice(0, TITLE_MAX);
493
+ if (!title) return;
494
+ await db.insert(items).values({ title, workspaceId: orgId });
495
+ revalidatePath("/");
496
+ }
497
+
498
+ export async function deleteItem(formData: FormData) {
499
+ const orgId = await activeWorkspaceId();
500
+ if (!orgId) return;
501
+ const id = Number(formData.get("id"));
502
+ if (!Number.isInteger(id) || id < 1) return;
503
+ await db.delete(items).where(and(eq(items.id, id), eq(items.workspaceId, orgId)));
504
+ revalidatePath("/");
505
+ }
506
+ `;
507
+ }
508
+ function itemsPanelSource(actionsImport, viewImport) {
509
+ return `import { loadItems } from ${JSON.stringify(actionsImport)};
510
+ import { ItemsView } from ${JSON.stringify(viewImport)};
511
+
512
+ export async function ItemsPanel() {
513
+ const data = await loadItems();
514
+ return <ItemsView email={data.email} workspace={data.workspace} rows={data.rows} />;
515
+ }
516
+ `;
517
+ }
518
+ function itemsViewSource(actionsImport) {
519
+ return `"use client";
520
+
521
+ import { Button, Input } from "@cronus-ui/ui";
522
+ import { createItem, deleteItem } from ${JSON.stringify(actionsImport)};
523
+
524
+ export function ItemsView({
525
+ email,
526
+ workspace,
527
+ rows,
528
+ }: {
529
+ email: string;
530
+ workspace: string;
531
+ rows: { id: number; title: string }[];
532
+ }) {
533
+ const count = String(rows.length);
534
+ return (
535
+ <section
536
+ data-slot="items-panel"
537
+ aria-labelledby="items-heading"
538
+ className="border-b border-border px-6 py-6"
539
+ >
540
+ <h2 id="items-heading" className="text-sm font-semibold text-fg">
541
+ Items
542
+ </h2>
543
+ <p className="mt-1 text-sm text-fg-tertiary">
544
+ {email} · {workspace} · {count} items
545
+ </p>
546
+ <form action={createItem} className="mt-4 flex flex-col gap-3 sm:flex-row sm:items-end">
547
+ <div className="flex min-w-0 flex-1 flex-col gap-2">
548
+ <label htmlFor="item-title" className="text-sm font-medium text-fg">
549
+ Title
550
+ </label>
551
+ <Input
552
+ id="item-title"
553
+ name="title"
554
+ required
555
+ maxLength={${TITLE_MAX}}
556
+ autoComplete="off"
557
+ placeholder="New item"
558
+ />
559
+ </div>
560
+ <Button type="submit">Add</Button>
561
+ </form>
562
+ {rows.length === 0 ? (
563
+ <p className="mt-4 text-sm text-fg-tertiary">No items yet.</p>
564
+ ) : (
565
+ <ul className="mt-4">
566
+ {rows.map((row) => (
567
+ <li
568
+ key={row.id}
569
+ data-slot="item"
570
+ className="flex items-center justify-between gap-3 border-t border-border py-3"
571
+ >
572
+ <span className="min-w-0 truncate text-sm text-fg">{row.title}</span>
573
+ <form action={deleteItem}>
574
+ <input type="hidden" name="id" value={row.id} />
575
+ <Button type="submit" variant="ghost" size="sm" aria-label={"Delete " + row.title}>
576
+ Delete
577
+ </Button>
578
+ </form>
579
+ </li>
580
+ ))}
581
+ </ul>
582
+ )}
583
+ </section>
584
+ );
585
+ }
586
+ `;
587
+ }
588
+ function workspaceMenuSource(authClientImport) {
589
+ return `"use client";
590
+
591
+ import { WorkspaceSwitcher } from "@cronus-ui/ui";
592
+ import { useRouter } from "next/navigation";
593
+ import { useEffect } from "react";
594
+ import { authClient } from ${JSON.stringify(authClientImport)};
595
+
596
+ export function WorkspaceMenu() {
597
+ const router = useRouter();
598
+ const { data: orgs } = authClient.useListOrganizations();
599
+ const { data: active } = authClient.useActiveOrganization();
600
+ const workspaces = (orgs ?? []).map((org) => ({ id: org.id, name: org.name }));
601
+ const firstId = workspaces[0]?.id;
602
+ useEffect(() => {
603
+ if (active || !firstId) return;
604
+ void authClient.organization.setActive({ organizationId: firstId }).then(() => {
605
+ router.refresh();
606
+ });
607
+ }, [active, firstId, router]);
608
+ return (
609
+ <WorkspaceSwitcher
610
+ workspaces={workspaces}
611
+ value={active?.id}
612
+ onValueChange={(id) => {
613
+ void authClient.organization.setActive({ organizationId: id }).then(() => {
614
+ router.refresh();
615
+ });
616
+ }}
617
+ />
618
+ );
619
+ }
620
+ `;
621
+ }
622
+ function inviteMemberSource(authClientImport) {
623
+ return `"use client";
624
+
625
+ import { InviteDialog } from "@cronus-ui/ui";
626
+ import type { ReactNode } from "react";
627
+ import { authClient } from ${JSON.stringify(authClientImport)};
628
+
629
+ export function InviteMember({ trigger }: { trigger: ReactNode }) {
630
+ return (
631
+ <InviteDialog
632
+ trigger={trigger}
633
+ onInvite={async ({ email, role }) => {
634
+ const assigned = role === "admin" || role === "owner" ? role : "member";
635
+ const { error } = await authClient.organization.inviteMember({
636
+ email,
637
+ role: assigned,
638
+ });
639
+ if (error) throw new Error(error.message || "Invite failed");
640
+ }}
641
+ />
642
+ );
643
+ }
644
+ `;
645
+ }
646
+ function sessionUserSource(authClientImport) {
647
+ return `"use client";
648
+
649
+ import { Avatar, AvatarFallback, AvatarImage } from "@cronus-ui/ui";
650
+ import { authClient } from ${JSON.stringify(authClientImport)};
651
+
652
+ function initialsOf(name: string, email: string): string {
653
+ const parts = name.trim().split(/\\s+/).filter(Boolean);
654
+ if (parts.length >= 2) {
655
+ return \`\${parts[0]?.[0] ?? ""}\${parts[1]?.[0] ?? ""}\`.toUpperCase();
656
+ }
657
+ if (parts[0]?.[0]) return parts[0][0].toUpperCase();
658
+ return email.slice(0, 2).toUpperCase();
659
+ }
660
+
661
+ export function SessionUser({ compact = false }: { compact?: boolean }) {
662
+ const { data } = authClient.useSession();
663
+ const user = data?.user;
664
+ if (!user) return null;
665
+ const name = user.name || user.email || "Account";
666
+ const email = user.email || "";
667
+ const initials = initialsOf(name, email);
668
+ const avatar = (
669
+ <Avatar className="size-8">
670
+ {user.image ? <AvatarImage src={user.image} alt={name} /> : null}
671
+ <AvatarFallback>{initials}</AvatarFallback>
672
+ </Avatar>
673
+ );
674
+ if (compact) return avatar;
675
+ return (
676
+ <div className="flex items-center gap-2 rounded-lg px-2 py-1.5">
677
+ {avatar}
678
+ <div className="flex min-w-0 flex-col">
679
+ <span className="truncate text-sm font-medium text-fg">{name}</span>
680
+ <span className="truncate text-xs text-fg-tertiary">{email}</span>
681
+ </div>
682
+ </div>
683
+ );
684
+ }
685
+ `;
686
+ }
687
+ function acceptInvitationPageSource(authClientImport) {
688
+ return `"use client";
689
+
690
+ import { Suspense, useEffect, useState } from "react";
691
+ import { useRouter, useSearchParams } from "next/navigation";
692
+ import { authClient } from ${JSON.stringify(authClientImport)};
693
+
694
+ function AcceptInvitation() {
695
+ const router = useRouter();
696
+ const params = useSearchParams();
697
+ const id = params.get("id") ?? params.get("invitation");
698
+ const { data: session, isPending } = authClient.useSession();
699
+ const [error, setError] = useState<string | null>(null);
700
+
701
+ useEffect(() => {
702
+ if (isPending) return;
703
+ if (!id) {
704
+ setError("Invitation is missing.");
705
+ return;
706
+ }
707
+ if (!session) {
708
+ router.replace(\`/signup?invitation=\${encodeURIComponent(id)}\`);
709
+ return;
710
+ }
711
+ let cancelled = false;
712
+ void (async () => {
713
+ const { data, error: acceptError } = await authClient.organization.acceptInvitation({
714
+ invitationId: id,
715
+ });
716
+ if (cancelled) return;
717
+ if (acceptError) {
718
+ setError(acceptError.message || "Could not accept invitation.");
719
+ return;
720
+ }
721
+ const orgId = data?.invitation?.organizationId ?? data?.member?.organizationId;
722
+ if (orgId) {
723
+ await authClient.organization.setActive({ organizationId: orgId });
724
+ }
725
+ try {
726
+ sessionStorage.removeItem("cronus-invitation");
727
+ } catch {
728
+ // ignore
729
+ }
730
+ window.location.assign("/");
731
+ })();
732
+ return () => {
733
+ cancelled = true;
734
+ };
735
+ }, [id, isPending, router, session]);
736
+
737
+ return (
738
+ <main className="flex min-h-svh flex-col items-center justify-center px-6">
739
+ {error ? (
740
+ <p role="alert" className="text-sm text-error-strong">
741
+ {error}
742
+ </p>
743
+ ) : (
744
+ <p className="text-sm text-fg-tertiary">Accepting invitation…</p>
745
+ )}
746
+ </main>
747
+ );
748
+ }
749
+
750
+ export default function AcceptInvitationPage() {
751
+ return (
752
+ <Suspense
753
+ fallback={
754
+ <main className="flex min-h-svh flex-col items-center justify-center px-6">
755
+ <p className="text-sm text-fg-tertiary">Accepting invitation…</p>
756
+ </main>
757
+ }
758
+ >
759
+ <AcceptInvitation />
760
+ </Suspense>
761
+ );
762
+ }
763
+ `;
764
+ }
765
+ function insertImport(source, line) {
766
+ if (source.includes(line))
767
+ return source;
768
+ const firstImport = source.match(/^import .+$/m);
769
+ if (firstImport?.index !== undefined) {
770
+ return `${source.slice(0, firstImport.index)}${line}\n${source.slice(firstImport.index)}`;
771
+ }
772
+ return `${line}\n${source}`;
773
+ }
774
+ /**
775
+ * Wire the installed app-shell-chrome copy to live Better-Auth orgs + session.
776
+ * Idempotent: a chrome that already has WorkspaceMenu and SessionUser is left
777
+ * untouched. Returns undefined when the WorkspaceSwitcher / InviteDialog
778
+ * anchors are missing and nothing else can be patched.
779
+ */
780
+ export function patchChromeSource(source, workspaceImport, inviteImport, sessionImport) {
781
+ const hasMenu = source.includes("WorkspaceMenu");
782
+ const hasSession = source.includes("SessionUser");
783
+ if (hasMenu && hasSession)
784
+ return source;
785
+ const canPatchMenu = !hasMenu &&
786
+ /<WorkspaceSwitcher[\s\S]*?\/>/.test(source) &&
787
+ /<InviteDialog[\s\S]*?\/>/.test(source);
788
+ const canPatchSession = sessionImport !== undefined &&
789
+ !hasSession &&
790
+ source.includes("{USER.email}") &&
791
+ source.includes("<SidebarFooter>");
792
+ if (!canPatchMenu && !canPatchSession) {
793
+ return hasMenu ? source : undefined;
794
+ }
795
+ let out = source;
796
+ if (canPatchMenu) {
797
+ out = insertImport(out, `import { WorkspaceMenu } from ${JSON.stringify(workspaceImport)};`);
798
+ out = insertImport(out, `import { InviteMember } from ${JSON.stringify(inviteImport)};`);
799
+ out = out.replace(/<WorkspaceSwitcher[\s\S]*?\/>/, "<WorkspaceMenu />");
800
+ out = out.replace(/<InviteDialog([\s\S]*?)\/>/, "<InviteMember$1/>");
801
+ out = out.replace(/\nconst WORKSPACES = \[[\s\S]*?\];\n/, "\n");
802
+ out = out.replace(/\s*const \[workspaceId, setWorkspaceId\] = useState\("[^"]*"\);\n/, "\n");
803
+ out = out.replace(/,\s*useState/, "");
804
+ out = out.replace(/\s*InviteDialog,\n/, "\n");
805
+ out = out.replace(/\s*WorkspaceSwitcher,\n/, "\n");
806
+ }
807
+ if (canPatchSession && sessionImport !== undefined) {
808
+ out = insertImport(out, `import { SessionUser } from ${JSON.stringify(sessionImport)};`);
809
+ out = out.replace(/<SidebarFooter>\s*<div className="flex items-center gap-2 rounded-lg px-2 py-1\.5">[\s\S]*?<\/SidebarFooter>/, "<SidebarFooter>\n <SessionUser />\n </SidebarFooter>");
810
+ out = out.replace(/<Avatar className="size-8">\s*\{OWNER\?\.avatar \? <AvatarImage src=\{OWNER\.avatar\} alt=\{USER\.name\} \/> : null\}\s*<AvatarFallback>\{USER\.initials\}<\/AvatarFallback>\s*<\/Avatar>/, "<SessionUser compact />");
811
+ out = out.replace(/\nimport \{ TEAM, USER \} from "[^"]+";\n/, "\n");
812
+ out = out.replace(/\nconst OWNER = TEAM\.find\(\(m\) => m\.email === USER\.email\);\n/, "\n");
813
+ out = out.replace(/\s*Avatar,\n/, "\n");
814
+ out = out.replace(/\s*AvatarFallback,\n/, "\n");
815
+ out = out.replace(/\s*AvatarImage,\n/, "\n");
816
+ }
817
+ return out;
818
+ }
819
+ function nextConfigSource() {
820
+ return `/** @type {import('next').NextConfig} */
821
+ const nextConfig = {
822
+ serverExternalPackages: ["better-sqlite3"],
823
+ };
824
+
825
+ export default nextConfig;
826
+ `;
827
+ }
828
+ /** Insert ItemsPanel into a generated home page. Returns undefined when there is no main. */
829
+ export function patchHomePageSource(source, itemsImport) {
830
+ if (!/<main\b/.test(source))
831
+ return undefined;
832
+ let out = source;
833
+ const importLine = `import { ItemsPanel } from ${JSON.stringify(itemsImport)};`;
834
+ if (!out.includes(importLine)) {
835
+ const match = out.match(/^import .+$/m);
836
+ if (match?.index !== undefined) {
837
+ out = `${out.slice(0, match.index)}${importLine}\n${out.slice(match.index)}`;
838
+ }
839
+ else {
840
+ out = `${importLine}\n${out}`;
841
+ }
842
+ }
843
+ out = out.replace(/export default(?! async) function/, "export default async function");
844
+ if (!/<ItemsPanel\s*\/>/.test(out)) {
845
+ out = out.replace(/(<main\b[^>]*>)/, "$1\n <ItemsPanel />");
846
+ }
847
+ return out;
848
+ }
849
+ function mergePackageJson(raw) {
850
+ const pkg = JSON.parse(raw);
851
+ const dependencies = { ...(pkg.dependencies ?? {}) };
852
+ const devDependencies = { ...(pkg.devDependencies ?? {}) };
853
+ const scripts = { ...(pkg.scripts ?? {}) };
854
+ for (const [name, range] of Object.entries(GOLD_PATH_PROD_DEPS)) {
855
+ dependencies[name] ??= range;
856
+ }
857
+ for (const [name, range] of Object.entries(GOLD_PATH_DEV_DEPS)) {
858
+ devDependencies[name] ??= range;
859
+ }
860
+ for (const [name, cmd] of Object.entries(GOLD_PATH_SCRIPTS)) {
861
+ scripts[name] ??= cmd;
862
+ }
863
+ pkg.dependencies = dependencies;
864
+ pkg.devDependencies = devDependencies;
865
+ pkg.scripts = scripts;
866
+ return `${JSON.stringify(pkg, null, 2)}\n`;
867
+ }
868
+ function mergeNextConfig(raw) {
869
+ if (raw.includes("better-sqlite3"))
870
+ return raw;
871
+ if (/serverExternalPackages:\s*\[/.test(raw)) {
872
+ return raw.replace(/serverExternalPackages:\s*\[/, 'serverExternalPackages: ["better-sqlite3", ');
873
+ }
874
+ const empty = raw.replace(/const nextConfig = \{\s*\}/, 'const nextConfig = {\n serverExternalPackages: ["better-sqlite3"],\n}');
875
+ if (empty !== raw)
876
+ return empty;
877
+ if (raw.includes("const nextConfig = {")) {
878
+ return raw.replace(/const nextConfig = \{/, 'const nextConfig = {\n serverExternalPackages: ["better-sqlite3"],');
879
+ }
880
+ return `${raw.trimEnd()}\n`;
881
+ }
882
+ function mergeEnvExample(raw) {
883
+ const lines = raw.split(/\r?\n/);
884
+ const keys = new Set(lines.map((line) => {
885
+ const eq = line.indexOf("=");
886
+ return eq === -1 ? line.trim() : line.slice(0, eq).trim();
887
+ }));
888
+ const extra = [];
889
+ for (const [key, value] of Object.entries(ENV_VARS)) {
890
+ if (!keys.has(key))
891
+ extra.push(`${key}=${value}`);
892
+ }
893
+ if (extra.length === 0)
894
+ return raw.endsWith("\n") ? raw : `${raw}\n`;
895
+ const base = raw.endsWith("\n") || raw.length === 0 ? raw : `${raw}\n`;
896
+ return `${base}${extra.join("\n")}\n`;
897
+ }
898
+ function mergeGitignore(raw) {
899
+ const lines = raw.split(/\r?\n/);
900
+ const have = new Set(lines.map((l) => l.trim()));
901
+ const extra = GITIGNORE_ENTRIES.filter((entry) => !have.has(entry));
902
+ if (extra.length === 0)
903
+ return raw.endsWith("\n") ? raw : `${raw}\n`;
904
+ const base = raw.endsWith("\n") || raw.length === 0 ? raw : `${raw}\n`;
905
+ return `${base}${extra.join("\n")}\n`;
906
+ }
907
+ async function writeRel(targetDir, rel, content, overwrite, always, written, skipped) {
908
+ const dest = resolveSafeDest(targetDir, ".", rel);
909
+ if (!always && existsSync(dest) && !overwrite) {
910
+ skipped.push(rel);
911
+ return;
912
+ }
913
+ await writeFileEnsured(dest, content);
914
+ written.push(rel);
915
+ }
916
+ /**
917
+ * Write sqlite + Drizzle + Better-Auth files into a composed saas/admin app.
918
+ * Overwrites lib/auth-adapter.ts and lib/items.ts always. Patches the shell
919
+ * home page only when compose wrote it this run.
920
+ */
921
+ export async function applyGoldPath(options) {
922
+ const { targetDir, config, generatedFiles, overwrite } = options;
923
+ const layout = goldPathLayout(config);
924
+ const appDir = resolveAppDir(targetDir, layout, generatedFiles);
925
+ const middlewareRel = appDir === "src/app"
926
+ ? "src/middleware.ts"
927
+ : appDir === "app"
928
+ ? "middleware.ts"
929
+ : layout.middlewareRel;
930
+ const authImport = `${config.aliases.lib}/auth`;
931
+ const authClientImport = `${config.aliases.lib}/auth-client`;
932
+ const itemsActionsImport = `${config.aliases.lib}/items`;
933
+ const itemsViewImport = "@/components/items-view";
934
+ const itemsImport = "@/components/items-panel";
935
+ const workspaceImport = "@/components/workspace-menu";
936
+ const inviteImport = "@/components/invite-member";
937
+ const sessionImport = "@/components/session-user";
938
+ const chromeRel = `${posix(config.paths.blocks)}/app-shell-chrome.tsx`;
939
+ const written = [];
940
+ const skipped = [];
941
+ const files = [
942
+ { rel: "drizzle.config.ts", content: drizzleConfigSource(layout.dbDir) },
943
+ { rel: `${layout.dbDir}/schema.ts`, content: dbSchemaSource() },
944
+ { rel: `${layout.dbDir}/index.ts`, content: dbClientSource() },
945
+ { rel: `${layout.libDir}/auth.ts`, content: authServerSource() },
946
+ { rel: `${layout.libDir}/auth-client.ts`, content: authClientSource() },
947
+ { rel: `${layout.libDir}/auth-adapter.ts`, content: authAdapterSource(), always: true },
948
+ {
949
+ rel: `${layout.libDir}/items.ts`,
950
+ content: itemsActionsSource(authImport),
951
+ always: true,
952
+ },
953
+ {
954
+ rel: `${appDir}/api/auth/[...all]/route.ts`,
955
+ content: authRouteSource(authImport),
956
+ },
957
+ { rel: middlewareRel, content: middlewareSource() },
958
+ {
959
+ rel: `${layout.componentsDir}/items-panel.tsx`,
960
+ content: itemsPanelSource(itemsActionsImport, itemsViewImport),
961
+ always: true,
962
+ },
963
+ {
964
+ rel: `${layout.componentsDir}/items-view.tsx`,
965
+ content: itemsViewSource(itemsActionsImport),
966
+ always: true,
967
+ },
968
+ {
969
+ rel: `${layout.componentsDir}/workspace-menu.tsx`,
970
+ content: workspaceMenuSource(authClientImport),
971
+ always: true,
972
+ },
973
+ {
974
+ rel: `${layout.componentsDir}/invite-member.tsx`,
975
+ content: inviteMemberSource(authClientImport),
976
+ always: true,
977
+ },
978
+ {
979
+ rel: `${layout.componentsDir}/session-user.tsx`,
980
+ content: sessionUserSource(authClientImport),
981
+ always: true,
982
+ },
983
+ {
984
+ rel: `${appDir}/(bare)/accept-invitation/page.tsx`,
985
+ content: acceptInvitationPageSource(authClientImport),
986
+ always: true,
987
+ },
988
+ ];
989
+ for (const file of files) {
990
+ await writeRel(targetDir, file.rel, file.content, overwrite, file.always === true, written, skipped);
991
+ }
992
+ const chromeDest = resolveSafeDest(targetDir, ".", chromeRel);
993
+ if (existsSync(chromeDest)) {
994
+ const current = await readFile(chromeDest, "utf8");
995
+ const patched = patchChromeSource(current, workspaceImport, inviteImport, sessionImport);
996
+ if (patched !== undefined && patched !== current) {
997
+ await writeFileEnsured(chromeDest, patched);
998
+ if (!written.includes(chromeRel))
999
+ written.push(chromeRel);
1000
+ const templateName = options.templateName;
1001
+ if (templateName !== undefined) {
1002
+ const snapDest = resolveSafeDest(targetDir, baseSnapshotDir(templateName), chromeRel);
1003
+ await writeFileEnsured(snapDest, patched);
1004
+ }
1005
+ }
1006
+ }
1007
+ const homeRel = homePageRel(appDir, generatedFiles);
1008
+ if (homeRel !== undefined) {
1009
+ const dest = resolveSafeDest(targetDir, ".", homeRel);
1010
+ if (existsSync(dest)) {
1011
+ const current = await readFile(dest, "utf8");
1012
+ const patched = patchHomePageSource(current, itemsImport);
1013
+ if (patched !== undefined && patched !== current) {
1014
+ await writeFileEnsured(dest, patched);
1015
+ const templateName = options.templateName;
1016
+ if (templateName !== undefined) {
1017
+ const snapDest = resolveSafeDest(targetDir, baseSnapshotDir(templateName), homeRel);
1018
+ await writeFileEnsured(snapDest, patched);
1019
+ }
1020
+ }
1021
+ }
1022
+ }
1023
+ await mergeTextFile(targetDir, "package.json", mergePackageJson);
1024
+ await mergeOrCreate(targetDir, "next.config.mjs", nextConfigSource(), mergeNextConfig);
1025
+ await mergeOrCreate(targetDir, ".env.example", `${Object.entries(ENV_VARS)
1026
+ .map(([k, v]) => `${k}=${v}`)
1027
+ .join("\n")}\n`, mergeEnvExample);
1028
+ await mergeOrCreate(targetDir, ".gitignore", `${GITIGNORE_ENTRIES.join("\n")}\n`, mergeGitignore);
1029
+ return { written, skipped };
1030
+ }
1031
+ async function mergeOrCreate(targetDir, rel, created, merge) {
1032
+ const dest = resolveSafeDest(targetDir, ".", rel);
1033
+ if (!existsSync(dest)) {
1034
+ await writeFileEnsured(dest, created);
1035
+ return;
1036
+ }
1037
+ const raw = await readFile(dest, "utf8");
1038
+ const next = merge(raw);
1039
+ if (next !== raw)
1040
+ await writeFileEnsured(dest, next);
1041
+ }
1042
+ async function mergeTextFile(targetDir, rel, merge) {
1043
+ const dest = resolveSafeDest(targetDir, ".", rel);
1044
+ if (!existsSync(dest))
1045
+ return;
1046
+ const raw = await readFile(dest, "utf8");
1047
+ let next;
1048
+ try {
1049
+ next = merge(raw);
1050
+ }
1051
+ catch {
1052
+ return;
1053
+ }
1054
+ if (next !== raw)
1055
+ await writeFileEnsured(dest, next);
1056
+ }
1057
+ //# sourceMappingURL=gold-path.js.map