@murumets-ee/create 0.1.13 → 0.1.15

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/index.mjs ADDED
@@ -0,0 +1,3480 @@
1
+ import{i as e,n as t,o as n,r,t as i}from"./utils-Bmw75lEa.mjs";import{join as a}from"node:path";import{mkdir as o}from"node:fs/promises";async function s(e,t){await n(a(e,`lib/admin-config.ts`),`import { Media } from '@murumets-ee/media'
2
+ import {
3
+ Ticket,
4
+ TicketMessage,
5
+ TicketAttachment,
6
+ Department,
7
+ TicketTag,
8
+ } from '@murumets-ee/ticketing'
9
+ import { Article, Category } from '@/entities'
10
+
11
+ /** All entities available in the admin (drives sidebar nav + CRUD) */
12
+ export const allEntities = [
13
+ Article, Media, Category,
14
+ Ticket, TicketMessage, TicketAttachment, Department, TicketTag,
15
+ ]
16
+
17
+ /** Taxonomy entities keyed by name */
18
+ export const taxonomyVocabularies = {
19
+ category: Category,
20
+ department: Department,
21
+ ticket_tag: TicketTag,
22
+ }
23
+
24
+ /** Entities exposed via generic CRUD API handler */
25
+ export const crudEntities = [Article, Media, Ticket, TicketMessage, TicketAttachment]
26
+
27
+ /** Plugin resources for the permission catalog */
28
+ export const pluginResources = [
29
+ { resource: 'storage', actions: ['view', 'create', 'update', 'delete'] },
30
+ { resource: 'settings', actions: ['view', 'update'] },
31
+ { resource: 'audit-logs', actions: ['view'] },
32
+ { resource: 'permissions', actions: ['view', 'create', 'update', 'delete'] },
33
+ { resource: 'ticketing', actions: ['view', 'create', 'update', 'delete'] },
34
+ ]
35
+ `),await n(a(e,`lib/content-locale.ts`),`import { cookies } from 'next/headers'
36
+ import { hasLocale } from 'next-intl'
37
+ import { routing } from '@/i18n/routing'
38
+
39
+ /**
40
+ * Get the content editing locale from the cookie, falling back to the interface locale.
41
+ */
42
+ export async function getContentLocale(interfaceLocale: string): Promise<string> {
43
+ const jar = await cookies()
44
+ const raw = jar.get('content-locale')?.value
45
+ if (raw && hasLocale(routing.locales, raw)) return raw
46
+ return interfaceLocale
47
+ }
48
+ `),await n(a(e,`lib/with-admin-context.ts`),`import { getContentConfig } from '@murumets-ee/content/plugin'
49
+ import type { RequestContext } from '@murumets-ee/core'
50
+ import { runWithContextAsync } from '@murumets-ee/core'
51
+ import { getToolkitApp } from './app'
52
+ import { getContentLocale } from './content-locale'
53
+
54
+ export async function withAdminContext<T>(
55
+ interfaceLocale: string,
56
+ fn: (ctx: { locale: string; defaultLocale: string }) => Promise<T>,
57
+ ): Promise<T> {
58
+ const app = await getToolkitApp()
59
+ const contentLocale = await getContentLocale(interfaceLocale)
60
+ const { defaultLocale } = getContentConfig()
61
+
62
+ const context: RequestContext = {
63
+ locale: contentLocale,
64
+ defaultLocale,
65
+ app,
66
+ }
67
+
68
+ return runWithContextAsync(context, () => fn({ locale: contentLocale, defaultLocale }))
69
+ }
70
+ `),await n(a(e,`lib/load-roles.ts`),`import { buildInitialRoleDefinitions } from '@murumets-ee/auth'
71
+ import type { ToolkitApp } from '@murumets-ee/core'
72
+ import { createSettingsClient } from '@murumets-ee/settings'
73
+ import { permissionSettings } from '@/settings/permissions'
74
+
75
+ export async function loadRoles(
76
+ app: ToolkitApp,
77
+ ): Promise<Record<string, Record<string, string[]>>> {
78
+ const client = createSettingsClient(permissionSettings, { app })
79
+ const saved = await client.get('roles')
80
+
81
+ if (saved) return saved
82
+
83
+ // First run — seed built-in roles with zero permissions
84
+ const initial = buildInitialRoleDefinitions()
85
+ await client.set('roles', initial)
86
+ return initial
87
+ }
88
+ `),await n(a(e,`settings/permissions.ts`),`import { defineSettings, setting } from '@murumets-ee/settings'
89
+
90
+ export const permissionSettings = defineSettings({
91
+ namespace: 'permissions',
92
+ scope: 'global',
93
+ label: 'Permissions',
94
+ schema: {
95
+ roles: setting.json<Record<string, Record<string, string[]>>>(),
96
+ },
97
+ })
98
+ `),await n(a(e,`settings/site.ts`),`import { defineSettings, setting } from '@murumets-ee/settings'
99
+
100
+ export const siteSettings = defineSettings({
101
+ namespace: 'site',
102
+ scope: 'global',
103
+ label: 'Site Settings',
104
+ schema: {
105
+ siteName: setting.text({ default: 'My Site', label: 'Site Name', translatable: true }),
106
+ siteDescription: setting.text({ label: 'Site Description', translatable: true }),
107
+ maintenanceMode: setting.boolean({ default: false, label: 'Maintenance Mode' }),
108
+ postsPerPage: setting.number({
109
+ default: 10,
110
+ min: 1,
111
+ max: 100,
112
+ integer: true,
113
+ label: 'Posts Per Page',
114
+ }),
115
+ },
116
+ })
117
+ `),await n(a(e,`app/admin-layout.tsx`),`'use client'
118
+
119
+ import type { LinkComponent, SidebarNavGroup } from '@murumets-ee/admin-ui'
120
+ import { AdminShell } from '@murumets-ee/admin-ui'
121
+ import type { AdminNavGroup } from '@murumets-ee/admin-ui/server'
122
+ import {
123
+ Activity,
124
+ Building2,
125
+ FileText,
126
+ FolderTree,
127
+ Home,
128
+ Image,
129
+ ImageDown,
130
+ Inbox,
131
+ Kanban,
132
+ Lock,
133
+ PenTool,
134
+ ShieldCheck,
135
+ Tag,
136
+ Tags,
137
+ Ticket,
138
+ Users,
139
+ type LucideIcon,
140
+ } from 'lucide-react'
141
+ import type { ReactNode } from 'react'
142
+ import { Link, usePathname } from '@/i18n/navigation'
143
+
144
+ /** Map from icon name strings (from entity admin config) to Lucide components */
145
+ const ICON_MAP: Record<string, LucideIcon> = {
146
+ 'file-text': FileText,
147
+ 'folder-tree': FolderTree,
148
+ tags: Tags,
149
+ ticket: Ticket,
150
+ }
151
+
152
+ interface AdminLayoutProps {
153
+ children: ReactNode
154
+ defaultOpen?: boolean
155
+ headerActions?: ReactNode
156
+ sidebarFooter?: ReactNode
157
+ entityNavGroups?: AdminNavGroup[]
158
+ }
159
+
160
+ export function AdminLayout({
161
+ children,
162
+ defaultOpen,
163
+ headerActions,
164
+ sidebarFooter,
165
+ entityNavGroups,
166
+ }: AdminLayoutProps) {
167
+ const pathname = usePathname()
168
+
169
+ const dynamicGroups: SidebarNavGroup[] = (entityNavGroups ?? []).map((group) => ({
170
+ label: group.label,
171
+ items: group.items.map((item) => ({
172
+ label: item.label,
173
+ href: item.href,
174
+ icon: item.iconName ? ICON_MAP[item.iconName] : undefined,
175
+ })),
176
+ }))
177
+
178
+ const staticBefore: SidebarNavGroup = {
179
+ items: [
180
+ { label: 'Home', href: '/', icon: Home },
181
+ { label: 'Admin', href: '/admin', icon: PenTool },
182
+ ],
183
+ }
184
+
185
+ const supportGroup: SidebarNavGroup = {
186
+ label: 'Support',
187
+ items: [
188
+ { label: 'Tickets', href: '/admin/tickets', icon: Inbox },
189
+ { label: 'Board', href: '/admin/tickets/board', icon: Kanban },
190
+ { label: 'Departments', href: '/admin/departments', icon: Building2 },
191
+ { label: 'Ticket Tags', href: '/admin/ticket-tags', icon: Tag },
192
+ ],
193
+ }
194
+
195
+ const systemGroup: SidebarNavGroup = {
196
+ label: 'System',
197
+ items: [
198
+ { label: 'Users', href: '/admin/users', icon: Users },
199
+ { label: 'Roles', href: '/admin/roles', icon: ShieldCheck },
200
+ { label: 'Permissions', href: '/admin/permissions', icon: Lock },
201
+ { label: 'Media', href: '/admin/media', icon: Image },
202
+ { label: 'Image Styles', href: '/admin/media/image-styles', icon: ImageDown },
203
+ { label: 'Activity', href: '/admin/activity', icon: Activity },
204
+ ],
205
+ }
206
+
207
+ const navGroups: SidebarNavGroup[] = [
208
+ staticBefore,
209
+ ...dynamicGroups,
210
+ supportGroup,
211
+ systemGroup,
212
+ ]
213
+
214
+ return (
215
+ <AdminShell
216
+ defaultOpen={defaultOpen}
217
+ sidebar={{
218
+ navGroups,
219
+ pathname,
220
+ Link: Link as unknown as LinkComponent,
221
+ logo: (
222
+ <div className="flex h-8 items-center gap-2 px-2">
223
+ <span className="font-semibold text-sm text-zinc-700 dark:text-zinc-300 truncate">
224
+ Admin
225
+ </span>
226
+ </div>
227
+ ),
228
+ footer: sidebarFooter,
229
+ }}
230
+ header={{
231
+ actions: headerActions,
232
+ }}
233
+ >
234
+ {children}
235
+ </AdminShell>
236
+ )
237
+ }
238
+ `),await n(a(e,`app/[locale]/(shell)/layout.tsx`),`import { buildAdminNav } from '@murumets-ee/admin-ui/server'
239
+ import { cookies, headers } from 'next/headers'
240
+ import { redirect } from 'next/navigation'
241
+ import { Suspense } from 'react'
242
+ import { allEntities } from '@/lib/admin-config'
243
+ import { auth } from '@/lib/auth'
244
+ import { AdminLayout } from '../../admin-layout'
245
+ import { ThemeToggle } from '../../theme-toggle'
246
+
247
+ async function DynamicShell({
248
+ children,
249
+ interfaceLocale,
250
+ }: {
251
+ children: React.ReactNode
252
+ interfaceLocale: string
253
+ }) {
254
+ const h = await headers()
255
+ const session = await auth.api.getSession({ headers: h })
256
+ if (!session?.user) {
257
+ redirect(\`/\${interfaceLocale}/auth/sign-in\`)
258
+ }
259
+
260
+ const jar = await cookies()
261
+ const sidebarOpen = jar.get('sidebar:state')?.value !== 'false'
262
+ const entityNavGroups = buildAdminNav(allEntities, { basePath: '/admin' })
263
+
264
+ return (
265
+ <AdminLayout
266
+ defaultOpen={sidebarOpen}
267
+ entityNavGroups={entityNavGroups}
268
+ sidebarFooter={
269
+ <div className="flex justify-center gap-2">
270
+ <ThemeToggle />
271
+ </div>
272
+ }
273
+ >
274
+ {children}
275
+ </AdminLayout>
276
+ )
277
+ }
278
+
279
+ export default async function ShellLayout({
280
+ children,
281
+ params,
282
+ }: {
283
+ children: React.ReactNode
284
+ params: Promise<{ locale: string }>
285
+ }) {
286
+ const { locale } = await params
287
+
288
+ return (
289
+ <Suspense>
290
+ <DynamicShell interfaceLocale={locale}>{children}</DynamicShell>
291
+ </Suspense>
292
+ )
293
+ }
294
+ `),await n(a(e,`app/[locale]/(shell)/admin/layout.tsx`),`import { headers } from 'next/headers'
295
+ import { redirect } from 'next/navigation'
296
+ import { auth } from '@/lib/auth'
297
+
298
+ const ALLOWED_ROLES = new Set(['admin', 'editor'])
299
+
300
+ export default async function AdminGuardLayout({
301
+ children,
302
+ params,
303
+ }: {
304
+ children: React.ReactNode
305
+ params: Promise<{ locale: string }>
306
+ }) {
307
+ const { locale } = await params
308
+ const h = await headers()
309
+ const session = await auth.api.getSession({ headers: h })
310
+
311
+ if (!session?.user) {
312
+ redirect(\`/\${locale}/auth/sign-in\`)
313
+ }
314
+
315
+ const role = (session.user as Record<string, unknown>).role as string | undefined
316
+ if (!role || !ALLOWED_ROLES.has(role)) {
317
+ redirect(\`/\${locale}\`)
318
+ }
319
+
320
+ return <>{children}</>
321
+ }
322
+ `),await n(a(e,`app/[locale]/(shell)/admin/page.tsx`),`import { setRequestLocale } from 'next-intl/server'
323
+
324
+ export default async function AdminDashboard({ params }: { params: Promise<{ locale: string }> }) {
325
+ const { locale } = await params
326
+ setRequestLocale(locale)
327
+
328
+ return (
329
+ <div className="p-6">
330
+ <h1 className="text-2xl font-bold mb-4">Dashboard</h1>
331
+ <p className="text-muted-foreground">
332
+ Welcome to the admin panel. Use the sidebar to manage your content.
333
+ </p>
334
+ </div>
335
+ )
336
+ }
337
+ `),await n(a(e,`app/[locale]/(shell)/admin/[entity]/page.tsx`),`import { EntityList } from '@murumets-ee/admin-ui/entity-list'
338
+ import {
339
+ entityNameToSlug,
340
+ fetchEntityList,
341
+ getEntityLabel,
342
+ resolveEntityFromSlug,
343
+ toEntityMeta,
344
+ } from '@murumets-ee/admin-ui/server'
345
+ import { getContentConfig } from '@murumets-ee/content/plugin'
346
+ import { notFound } from 'next/navigation'
347
+ import { setRequestLocale } from 'next-intl/server'
348
+ import { allEntities, taxonomyVocabularies } from '@/lib/admin-config'
349
+ import { withAdminContext } from '@/lib/with-admin-context'
350
+
351
+ interface EntityListPageProps {
352
+ params: Promise<{ locale: string; entity: string }>
353
+ }
354
+
355
+ export default async function EntityListPage({ params }: EntityListPageProps) {
356
+ const { locale, entity: entitySlug } = await params
357
+ setRequestLocale(locale)
358
+
359
+ const entity = resolveEntityFromSlug(entitySlug, allEntities)
360
+ if (!entity) notFound()
361
+
362
+ const admin = entity.admin
363
+ const meta = toEntityMeta(entity)
364
+ const urlSlug = entityNameToSlug(entity.name)
365
+ const hasTranslatable = Object.values(entity.allFields).some((f) => f.translatable)
366
+ const isPublishable = entity.behaviors?.some((b) => b.name === 'publishable')
367
+ const isTaxonomy = entity.name in taxonomyVocabularies
368
+
369
+ return withAdminContext(locale, async ({ locale: contentLocale, defaultLocale }) => {
370
+ let locales: Array<{ code: string; label: string }> | undefined
371
+ if (hasTranslatable) {
372
+ try {
373
+ const config = getContentConfig()
374
+ locales = config.locales
375
+ } catch {
376
+ // content plugin not available
377
+ }
378
+ }
379
+
380
+ const initialData = await fetchEntityList(entity, {
381
+ sortField: admin?.defaultSort ?? 'createdAt',
382
+ sortDirection: admin?.defaultSortDirection ?? 'desc',
383
+ limit: admin?.pageSize ?? 20,
384
+ locale: contentLocale,
385
+ includeTranslationStatus: hasTranslatable,
386
+ })
387
+
388
+ return (
389
+ <div className="p-6">
390
+ <div className="mb-6">
391
+ <h1 className="text-2xl font-bold">{getEntityLabel(entity)}</h1>
392
+ {admin?.description && (
393
+ <p className="text-sm text-muted-foreground">{admin.description}</p>
394
+ )}
395
+ </div>
396
+ <EntityList
397
+ entity={meta}
398
+ allowDelete
399
+ allowStatusToggle={isPublishable}
400
+ {...(isTaxonomy ? { apiBasePath: '/api/admin/taxonomy', entityPath: entity.name } : {})}
401
+ defaultSort={admin?.defaultSort ?? 'createdAt'}
402
+ defaultSortDirection={admin?.defaultSortDirection ?? 'desc'}
403
+ hiddenColumns={admin?.hiddenColumns}
404
+ pageSize={admin?.pageSize}
405
+ locale={contentLocale}
406
+ locales={locales}
407
+ defaultLocale={defaultLocale}
408
+ showTranslationStatus={hasTranslatable && !!locales}
409
+ searchPlaceholder={\`Search \${getEntityLabel(entity).toLowerCase()}...\`}
410
+ editHref={\`/\${locale}/admin/\${urlSlug}/:id\`}
411
+ createHref={admin?.disableCreate ? undefined : \`/\${locale}/admin/\${urlSlug}/new\`}
412
+ initialData={initialData}
413
+ />
414
+ </div>
415
+ )
416
+ })
417
+ }
418
+ `),await n(a(e,`app/[locale]/(shell)/admin/[entity]/[id]/page.tsx`),`import {
419
+ entityNameToSlug,
420
+ fetchReferenceOptions,
421
+ getBlocksFieldName,
422
+ getEntityLabelSingular,
423
+ getReferenceFields,
424
+ inferRootFields,
425
+ resolveEntityFromSlug,
426
+ toEntityMeta,
427
+ } from '@murumets-ee/admin-ui/server'
428
+ import { buildPermissionChecker } from '@murumets-ee/auth'
429
+ import { ContentClient } from '@murumets-ee/content/client'
430
+ import { LockService } from '@murumets-ee/content/lock'
431
+ import { createAdminClient } from '@murumets-ee/core/clients'
432
+ import { getApp } from '@murumets-ee/core'
433
+ import { prepareBlockEditor } from '@murumets-ee/editor/server'
434
+ import { headers } from 'next/headers'
435
+ import { notFound } from 'next/navigation'
436
+ import { setRequestLocale } from 'next-intl/server'
437
+ import { GenericBlockEditor } from '@murumets-ee/admin-ui/content-editor'
438
+ import { GenericEntityForm } from '@murumets-ee/admin-ui/entity-form'
439
+ import { allEntities } from '@/lib/admin-config'
440
+ import { auth } from '@/lib/auth'
441
+ import { loadRoles } from '@/lib/load-roles'
442
+ import { withAdminContext } from '@/lib/with-admin-context'
443
+
444
+ interface EditEntityPageProps {
445
+ params: Promise<{ locale: string; entity: string; id: string }>
446
+ }
447
+
448
+ export default async function EditEntityPage({ params }: EditEntityPageProps) {
449
+ const { locale, entity: entitySlug, id } = await params
450
+ setRequestLocale(locale)
451
+
452
+ const entity = resolveEntityFromSlug(entitySlug, allEntities)
453
+ if (!entity) notFound()
454
+
455
+ const blocksField = getBlocksFieldName(entity)
456
+ const urlSlug = entityNameToSlug(entity.name)
457
+
458
+ return withAdminContext(locale, async ({ locale: contentLocale, defaultLocale }) => {
459
+ const client = createAdminClient(entity)
460
+ const isDefaultLocale = contentLocale === defaultLocale
461
+ const isNonDefaultLocale = !isDefaultLocale
462
+
463
+ const isVersionable = entity.behaviors?.some((b) => b.name === 'versionable') ?? false
464
+ const isPublishable = entity.behaviors?.some((b) => b.name === 'publishable') ?? false
465
+
466
+ let draft: { data: Record<string, unknown>; createdBy: string; createdByName: string | null; updatedAt: Date | string } | undefined
467
+ let canPublish = false
468
+ let lockResult: { acquired: boolean; lock?: { lockedBy: string; lockedByName: string | null; lockedAt: Date | string; expiresAt: Date | string } | null } | undefined
469
+ const enableLocking = isPublishable
470
+
471
+ if (isPublishable) {
472
+ try {
473
+ const app = getApp()
474
+ const contentClient = new ContentClient({ entity, db: app.db.readWrite })
475
+ const lockLocale = isDefaultLocale ? '_' : contentLocale
476
+
477
+ const draftEntry = await contentClient.getDraft(id, lockLocale)
478
+ if (draftEntry) {
479
+ draft = {
480
+ data: draftEntry.data,
481
+ createdBy: draftEntry.createdBy,
482
+ createdByName: draftEntry.createdByName,
483
+ updatedAt: draftEntry.updatedAt,
484
+ }
485
+ }
486
+
487
+ const session = await auth.api.getSession({ headers: await headers() })
488
+ if (session?.user) {
489
+ const role = (session.user as Record<string, unknown>).role as string | undefined
490
+ if (role) {
491
+ const roles = await loadRoles(app)
492
+ const checker = buildPermissionChecker(roles)
493
+ canPublish = checker(role, entity.name, 'publish')
494
+ }
495
+
496
+ const lockService = new LockService({ db: app.db.readWrite })
497
+ const result = await lockService.acquireLock(
498
+ entity.name, id, lockLocale,
499
+ { id: session.user.id, name: session.user.name ?? undefined },
500
+ )
501
+ if (result.acquired) {
502
+ lockResult = { acquired: true }
503
+ } else {
504
+ lockResult = { acquired: false, lock: result.lock }
505
+ }
506
+ }
507
+ } catch {
508
+ // Draft/permission/lock errors — proceed without
509
+ }
510
+ }
511
+
512
+ // Block editor entity
513
+ if (blocksField) {
514
+ const record = isDefaultLocale
515
+ ? await client.findById(id, { defaultLocale })
516
+ : await client.findById(id, { locale: contentLocale, defaultLocale })
517
+ if (!record) notFound()
518
+
519
+ const rootFields = inferRootFields(entity, blocksField)
520
+ const { blocks, initialData, mediaUrls, rootData, rootFieldDefs } =
521
+ await prepareBlockEditor(
522
+ entity as Parameters<typeof prepareBlockEditor>[0],
523
+ blocksField,
524
+ record,
525
+ { rootFields },
526
+ )
527
+
528
+ return (
529
+ <div className="flex h-[calc(100vh-3.5rem)] flex-col">
530
+ <div className="flex items-center gap-3 border-b px-6 py-3">
531
+ <h1 className="text-lg font-semibold">
532
+ {(record.title as string) ?? \`Untitled \${getEntityLabelSingular(entity)}\`}
533
+ </h1>
534
+ <span className="rounded bg-muted px-2 py-0.5 text-xs text-muted-foreground uppercase">
535
+ {contentLocale}
536
+ </span>
537
+ </div>
538
+ <div className="flex-1 overflow-hidden">
539
+ <GenericBlockEditor
540
+ key={contentLocale}
541
+ entityId={id}
542
+ entityName={entity.name}
543
+ blocksField={blocksField}
544
+ blocks={blocks}
545
+ initialData={initialData}
546
+ mediaUrls={mediaUrls}
547
+ rootData={rootData}
548
+ rootFieldDefs={rootFieldDefs}
549
+ saveLabel="Save"
550
+ locale={contentLocale}
551
+ defaultLocale={defaultLocale}
552
+ versionable={isVersionable}
553
+ isPublishable={isPublishable}
554
+ draft={draft}
555
+ canPublish={canPublish}
556
+ enableLocking={enableLocking}
557
+ lockResult={lockResult}
558
+ />
559
+ </div>
560
+ </div>
561
+ )
562
+ }
563
+
564
+ // Form entity
565
+ const [record, defaultLocaleData] = await Promise.all([
566
+ client.findById(id, { locale: contentLocale }),
567
+ isNonDefaultLocale ? client.findById(id) : Promise.resolve(null),
568
+ ])
569
+ if (!record) notFound()
570
+
571
+ const refFields = getReferenceFields(entity)
572
+ const referenceOptions: Record<string, Array<{ id: string; label: string }>> = {}
573
+
574
+ if (refFields.length > 0) {
575
+ const optionPromises = refFields.map(async ({ fieldName, entityName }) => {
576
+ const refEntity = allEntities.find((e) => e.name === entityName)
577
+ if (!refEntity) return { fieldName, options: [] }
578
+ const options = await fetchReferenceOptions(refEntity, { locale: contentLocale })
579
+ return { fieldName, options }
580
+ })
581
+ const results = await Promise.all(optionPromises)
582
+ for (const { fieldName, options } of results) {
583
+ referenceOptions[fieldName] = options
584
+ }
585
+ }
586
+
587
+ return (
588
+ <div className="p-6">
589
+ <div className="mb-6">
590
+ <h1 className="text-2xl font-bold">Edit {getEntityLabelSingular(entity)}</h1>
591
+ </div>
592
+ <GenericEntityForm
593
+ entity={toEntityMeta(entity)}
594
+ id={id}
595
+ locale={contentLocale}
596
+ defaultLocale={defaultLocale}
597
+ defaultLocaleData={
598
+ isNonDefaultLocale && defaultLocaleData
599
+ ? (defaultLocaleData as Record<string, unknown>)
600
+ : undefined
601
+ }
602
+ initialData={record as Record<string, unknown>}
603
+ referenceOptions={referenceOptions}
604
+ listUrl={\`/\${locale}/admin/\${urlSlug}\`}
605
+ versionable={isVersionable}
606
+ draft={draft}
607
+ canPublish={canPublish}
608
+ enableLocking={enableLocking}
609
+ lockResult={lockResult}
610
+ />
611
+ </div>
612
+ )
613
+ })
614
+ }
615
+ `),await n(a(e,`app/[locale]/(shell)/admin/[entity]/new/page.tsx`),`import {
616
+ entityNameToSlug,
617
+ fetchReferenceOptions,
618
+ getBlocksFieldName,
619
+ getEntityLabelSingular,
620
+ getReferenceFields,
621
+ resolveEntityFromSlug,
622
+ toEntityMeta,
623
+ } from '@murumets-ee/admin-ui/server'
624
+ import { createAdminClient } from '@murumets-ee/core/clients'
625
+ import { notFound, redirect } from 'next/navigation'
626
+ import { setRequestLocale } from 'next-intl/server'
627
+ import { GenericEntityForm } from '@murumets-ee/admin-ui/entity-form'
628
+ import { allEntities } from '@/lib/admin-config'
629
+ import { withAdminContext } from '@/lib/with-admin-context'
630
+
631
+ interface NewEntityPageProps {
632
+ params: Promise<{ locale: string; entity: string }>
633
+ }
634
+
635
+ export default async function NewEntityPage({ params }: NewEntityPageProps) {
636
+ const { locale, entity: entitySlug } = await params
637
+ setRequestLocale(locale)
638
+
639
+ const entity = resolveEntityFromSlug(entitySlug, allEntities)
640
+ if (!entity) notFound()
641
+ if (entity.admin?.disableCreate) notFound()
642
+
643
+ const blocksField = getBlocksFieldName(entity)
644
+ const urlSlug = entityNameToSlug(entity.name)
645
+
646
+ return withAdminContext(locale, async ({ locale: contentLocale }) => {
647
+ // Block editor entities: create a draft and redirect to the edit page
648
+ if (blocksField) {
649
+ const client = createAdminClient(entity)
650
+ const draft = await client.create({ title: 'Untitled' })
651
+ const newId = (draft as Record<string, unknown>).id as string
652
+ redirect(\`/\${locale}/admin/\${urlSlug}/\${newId}\`)
653
+ }
654
+
655
+ // Form entities: render the create form
656
+ const refFields = getReferenceFields(entity)
657
+ const referenceOptions: Record<string, Array<{ id: string; label: string }>> = {}
658
+
659
+ if (refFields.length > 0) {
660
+ const optionPromises = refFields.map(async ({ fieldName, entityName }) => {
661
+ const refEntity = allEntities.find((e) => e.name === entityName)
662
+ if (!refEntity) return { fieldName, options: [] }
663
+ const options = await fetchReferenceOptions(refEntity, { locale: contentLocale })
664
+ return { fieldName, options }
665
+ })
666
+ const results = await Promise.all(optionPromises)
667
+ for (const { fieldName, options } of results) {
668
+ referenceOptions[fieldName] = options
669
+ }
670
+ }
671
+
672
+ return (
673
+ <div className="p-6">
674
+ <div className="mb-6">
675
+ <h1 className="text-2xl font-bold">New {getEntityLabelSingular(entity)}</h1>
676
+ </div>
677
+ <GenericEntityForm
678
+ entity={toEntityMeta(entity)}
679
+ locale={contentLocale}
680
+ referenceOptions={referenceOptions}
681
+ listUrl={\`/\${locale}/admin/\${urlSlug}\`}
682
+ />
683
+ </div>
684
+ )
685
+ })
686
+ }
687
+ `),await n(a(e,`app/[locale]/(shell)/admin/media/page.tsx`),`import { EntityList } from '@murumets-ee/admin-ui/entity-list'
688
+ import { fetchEntityList, toEntityMeta } from '@murumets-ee/admin-ui/server'
689
+ import { Media } from '@murumets-ee/media'
690
+ import { getMediaClient } from '@murumets-ee/media/client'
691
+ import { setRequestLocale } from 'next-intl/server'
692
+
693
+ export default async function MediaListPage({ params }: { params: Promise<{ locale: string }> }) {
694
+ const { locale } = await params
695
+ setRequestLocale(locale)
696
+ const initialData = await fetchEntityList(Media, { sortField: 'createdAt' })
697
+
698
+ const mediaClient = await getMediaClient()
699
+ const ids = initialData.items.map((i) => i.id as string)
700
+ const thumbMap = await mediaClient.getVariantUrls(ids, 'thumbnail')
701
+ for (const item of initialData.items) {
702
+ item.thumbnailUrl = thumbMap.get(item.id as string) ?? ''
703
+ }
704
+
705
+ return (
706
+ <div className="p-6">
707
+ <div className="mb-6">
708
+ <h1 className="text-2xl font-bold">Media</h1>
709
+ <p className="text-sm text-muted-foreground">
710
+ Manage uploaded media files.
711
+ </p>
712
+ </div>
713
+ <EntityList
714
+ entity={toEntityMeta(Media)}
715
+ entityPath="media"
716
+ image={{ field: 'thumbnailUrl', size: 'sm', shape: 'rounded' }}
717
+ allowDelete
718
+ defaultSort="createdAt"
719
+ searchPlaceholder="Search media..."
720
+ editHref={\`/\${locale}/admin/media/:id\`}
721
+ initialData={initialData}
722
+ />
723
+ </div>
724
+ )
725
+ }
726
+ `),await n(a(e,`app/[locale]/(shell)/admin/media/[id]/page.tsx`),`import { toEntityMeta } from '@murumets-ee/admin-ui/server'
727
+ import { getCurrentApp } from '@murumets-ee/core'
728
+ import { createAdminClient } from '@murumets-ee/core/clients'
729
+ import { Media } from '@murumets-ee/media'
730
+ import { findMediaUsages } from '@murumets-ee/media/usage'
731
+ import { notFound } from 'next/navigation'
732
+ import { setRequestLocale } from 'next-intl/server'
733
+ import { withAdminContext } from '@/lib/with-admin-context'
734
+ import { MediaForm } from './media-form'
735
+ import { MediaUsagePanel } from './media-usage-panel'
736
+
737
+ interface MediaEditPageProps {
738
+ params: Promise<{ locale: string; id: string }>
739
+ }
740
+
741
+ export default async function MediaEditPage({ params }: MediaEditPageProps) {
742
+ const { locale, id } = await params
743
+ setRequestLocale(locale)
744
+
745
+ return withAdminContext(locale, async ({ locale: contentLocale }) => {
746
+ const app = getCurrentApp()!
747
+ const client = createAdminClient(Media)
748
+ const [mediaItem, usages] = await Promise.all([
749
+ client.findById(id, { locale: contentLocale }),
750
+ findMediaUsages(id, app.db.readWrite),
751
+ ])
752
+ if (!mediaItem) notFound()
753
+
754
+ return (
755
+ <div className="p-6">
756
+ <div className="mb-6">
757
+ <h1 className="text-2xl font-bold">Edit Media</h1>
758
+ </div>
759
+ <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
760
+ <div className="lg:col-span-2">
761
+ <MediaForm
762
+ entity={toEntityMeta(Media)}
763
+ id={id}
764
+ locale={contentLocale}
765
+ initialData={mediaItem as Record<string, unknown>}
766
+ />
767
+ </div>
768
+ <div>
769
+ <MediaUsagePanel usages={usages} locale={locale} />
770
+ </div>
771
+ </div>
772
+ </div>
773
+ )
774
+ })
775
+ }
776
+ `),await n(a(e,`app/[locale]/(shell)/admin/media/[id]/media-form.tsx`),`'use client'
777
+
778
+ import { EntityForm } from '@murumets-ee/admin-ui/entity-form'
779
+ import type { EntityMeta } from '@murumets-ee/admin-ui/entity-list'
780
+ import { useRouter } from 'next/navigation'
781
+
782
+ interface MediaFormProps {
783
+ entity: EntityMeta
784
+ id: string
785
+ locale?: string
786
+ initialData?: Record<string, unknown>
787
+ }
788
+
789
+ export function MediaForm({ entity, id, locale, initialData }: MediaFormProps) {
790
+ const router = useRouter()
791
+
792
+ return (
793
+ <EntityForm
794
+ entity={entity}
795
+ id={id}
796
+ locale={locale}
797
+ initialData={initialData}
798
+ entityPath="media"
799
+ layout="two-column"
800
+ fields={['title', 'alt', 'description', 'filename', 'mimeType', 'size', 'mediaType']}
801
+ fieldOverrides={{
802
+ filename: { readOnly: true, description: 'Original upload filename (read-only)' },
803
+ mimeType: { readOnly: true, label: 'MIME Type' },
804
+ size: { readOnly: true, description: 'File size in bytes' },
805
+ mediaType: { readOnly: true, label: 'Media Type' },
806
+ alt: { label: 'Alt Text', description: 'Alternative text for accessibility' },
807
+ }}
808
+ onSuccess={() => router.push(\`/\${locale}/admin/media\`)}
809
+ onCancel={() => router.back()}
810
+ />
811
+ )
812
+ }
813
+ `),await n(a(e,`app/[locale]/(shell)/admin/media/[id]/media-usage-panel.tsx`),`import type { MediaUsage } from '@murumets-ee/media/usage'
814
+
815
+ interface MediaUsagePanelProps {
816
+ usages: MediaUsage[]
817
+ locale: string
818
+ }
819
+
820
+ export function MediaUsagePanel({ usages, locale }: MediaUsagePanelProps) {
821
+ return (
822
+ <div className="rounded-lg border bg-card p-4">
823
+ <h3 className="mb-3 text-sm font-semibold">Used by</h3>
824
+
825
+ {usages.length === 0 && (
826
+ <p className="text-sm text-muted-foreground">
827
+ This media item is not referenced by any entity.
828
+ </p>
829
+ )}
830
+
831
+ {usages.length > 0 && (
832
+ <ul className="space-y-2">
833
+ {usages.map((usage) => {
834
+ const entitySlug = \`\${usage.entityName}s\`
835
+ const href = \`/\${locale}/admin/\${entitySlug}/\${usage.entityId}\`
836
+
837
+ return (
838
+ <li key={\`\${usage.entityName}-\${usage.entityId}-\${usage.fieldName}\`}>
839
+ <a
840
+ href={href}
841
+ className="block rounded-md border px-3 py-2 text-sm hover:bg-muted transition-colors"
842
+ >
843
+ <span className="font-medium capitalize">{usage.entityName}</span>
844
+ <span className="mx-1.5 text-muted-foreground">&middot;</span>
845
+ <span className="text-muted-foreground">{usage.fieldName}</span>
846
+ {usage.context === 'block' && (
847
+ <span className="ml-1.5 rounded bg-muted px-1.5 py-0.5 text-xs text-muted-foreground">
848
+ block
849
+ </span>
850
+ )}
851
+ </a>
852
+ </li>
853
+ )
854
+ })}
855
+ </ul>
856
+ )}
857
+ </div>
858
+ )
859
+ }
860
+ `),await n(a(e,`app/[locale]/(shell)/admin/media/image-styles/page.tsx`),`import { imageStylesSettings } from '@murumets-ee/media'
861
+ import { ImageStylesManager } from '@murumets-ee/media/image-styles'
862
+ import { createSettingsClient } from '@murumets-ee/settings'
863
+ import { setRequestLocale } from 'next-intl/server'
864
+ import { getToolkitApp } from '@/lib/app'
865
+
866
+ async function loadImageStyles() {
867
+ const app = await getToolkitApp()
868
+ const client = createSettingsClient(imageStylesSettings, { app })
869
+ const styles = await client.get('imageStyles')
870
+ return styles ?? {}
871
+ }
872
+
873
+ export default async function ImageStylesPage({ params }: { params: Promise<{ locale: string }> }) {
874
+ const { locale } = await params
875
+ setRequestLocale(locale)
876
+
877
+ const initialStyles = await loadImageStyles()
878
+
879
+ return (
880
+ <div className="p-6 max-w-4xl">
881
+ <ImageStylesManager initialStyles={initialStyles} />
882
+ </div>
883
+ )
884
+ }
885
+ `),await n(a(e,`app/[locale]/(shell)/admin/users/page.tsx`),`import type { UsersInitialData } from '@murumets-ee/admin-ui/users'
886
+ import { getAuth } from '@murumets-ee/auth'
887
+ import { headers } from 'next/headers'
888
+ import { setRequestLocale } from 'next-intl/server'
889
+ import { getToolkitApp } from '@/lib/app'
890
+ import { UsersPage } from './users-page'
891
+
892
+ export default async function UsersAdminPage({ params }: { params: Promise<{ locale: string }> }) {
893
+ const { locale } = await params
894
+ setRequestLocale(locale)
895
+
896
+ await getToolkitApp()
897
+ const auth = getAuth()
898
+
899
+ const result = await auth.api.listUsers({
900
+ headers: await headers(),
901
+ query: { limit: 20, sortBy: 'createdAt', sortDirection: 'desc' },
902
+ })
903
+
904
+ const initialData: UsersInitialData = {
905
+ users: result.users.map((u) => ({
906
+ id: u.id,
907
+ name: u.name,
908
+ email: u.email,
909
+ emailVerified: u.emailVerified,
910
+ image: u.image ?? null,
911
+ createdAt: u.createdAt instanceof Date ? u.createdAt.toISOString() : String(u.createdAt),
912
+ updatedAt: u.updatedAt instanceof Date ? u.updatedAt.toISOString() : String(u.updatedAt),
913
+ role: u.role ?? null,
914
+ banned: u.banned ?? null,
915
+ banReason: u.banReason ?? null,
916
+ banExpires:
917
+ u.banExpires instanceof Date
918
+ ? u.banExpires.toISOString()
919
+ : u.banExpires
920
+ ? String(u.banExpires)
921
+ : null,
922
+ })),
923
+ total: result.total,
924
+ }
925
+
926
+ return (
927
+ <div className="p-6">
928
+ <div className="mb-6">
929
+ <h1 className="text-2xl font-bold">Users</h1>
930
+ <p className="text-sm text-muted-foreground">Manage user accounts, roles, and access.</p>
931
+ </div>
932
+ <UsersPage initialData={initialData} />
933
+ </div>
934
+ )
935
+ }
936
+ `),await n(a(e,`app/[locale]/(shell)/admin/users/users-page.tsx`),`'use client'
937
+
938
+ import type { UsersInitialData } from '@murumets-ee/admin-ui/users'
939
+ import { UsersManagement } from '@murumets-ee/admin-ui/users'
940
+ import { createUsersApi } from '@murumets-ee/auth/client'
941
+ import { authClient } from '@/lib/auth-client'
942
+
943
+ const usersApi = createUsersApi(authClient)
944
+
945
+ export function UsersPage({ initialData }: { initialData: UsersInitialData }) {
946
+ const session = authClient.useSession()
947
+
948
+ return (
949
+ <UsersManagement
950
+ api={usersApi}
951
+ currentUserId={session.data?.user?.id}
952
+ roles={['admin', 'editor', 'viewer']}
953
+ initialData={initialData}
954
+ />
955
+ )
956
+ }
957
+ `),await n(a(e,`app/[locale]/(shell)/admin/permissions/page.tsx`),`import { PermissionsEditor } from '@murumets-ee/admin-ui/permissions'
958
+ import { BUILT_IN_ROLES, buildResourceCatalog } from '@murumets-ee/auth'
959
+ import { setRequestLocale } from 'next-intl/server'
960
+ import { allEntities, pluginResources } from '@/lib/admin-config'
961
+ import { getToolkitApp } from '@/lib/app'
962
+ import { loadRoles } from '@/lib/load-roles'
963
+
964
+ export default async function PermissionsPage({ params }: { params: Promise<{ locale: string }> }) {
965
+ const { locale } = await params
966
+ setRequestLocale(locale)
967
+
968
+ const app = await getToolkitApp()
969
+ const savedRoles = await loadRoles(app)
970
+ const statements = buildResourceCatalog(allEntities, pluginResources)
971
+
972
+ return (
973
+ <div className="p-6">
974
+ <div className="mb-6">
975
+ <h1 className="text-2xl font-bold">Permissions</h1>
976
+ <p className="text-sm text-muted-foreground">
977
+ Configure what each role can do. Admin always has full access.
978
+ </p>
979
+ </div>
980
+ <PermissionsEditor
981
+ statements={statements}
982
+ roles={Object.keys(savedRoles)}
983
+ builtInRoles={[...BUILT_IN_ROLES]}
984
+ initialPermissions={savedRoles}
985
+ />
986
+ </div>
987
+ )
988
+ }
989
+ `),await n(a(e,`app/[locale]/(shell)/admin/roles/page.tsx`),`import { RolesEditor } from '@murumets-ee/admin-ui/permissions'
990
+ import { BUILT_IN_ROLES } from '@murumets-ee/auth'
991
+ import { setRequestLocale } from 'next-intl/server'
992
+ import { getToolkitApp } from '@/lib/app'
993
+ import { loadRoles } from '@/lib/load-roles'
994
+
995
+ export default async function RolesPage({ params }: { params: Promise<{ locale: string }> }) {
996
+ const { locale } = await params
997
+ setRequestLocale(locale)
998
+
999
+ const app = await getToolkitApp()
1000
+ const savedRoles = await loadRoles(app)
1001
+
1002
+ const roles = [
1003
+ { name: 'admin', builtIn: true, permissionCount: 0 },
1004
+ ...Object.entries(savedRoles).map(([name, perms]) => ({
1005
+ name,
1006
+ builtIn: (BUILT_IN_ROLES as readonly string[]).includes(name),
1007
+ permissionCount: Object.values(perms).flat().length,
1008
+ })),
1009
+ ]
1010
+
1011
+ return (
1012
+ <div className="p-6">
1013
+ <div className="mb-6">
1014
+ <h1 className="text-2xl font-bold">Roles</h1>
1015
+ <p className="text-sm text-muted-foreground">
1016
+ Manage user roles. Built-in roles cannot be deleted.
1017
+ </p>
1018
+ </div>
1019
+ <RolesEditor roles={roles} permissionsHref={\`/\${locale}/admin/permissions\`} />
1020
+ </div>
1021
+ )
1022
+ }
1023
+ `),await n(a(e,`app/[locale]/(shell)/admin/activity/page.tsx`),`import { AuditLog } from '@murumets-ee/admin-ui/audit-log'
1024
+ import { fetchAuditLogData } from '@murumets-ee/admin-ui/server'
1025
+ import { setRequestLocale } from 'next-intl/server'
1026
+ import { withAdminContext } from '@/lib/with-admin-context'
1027
+
1028
+ export default async function ActivityPage({ params }: { params: Promise<{ locale: string }> }) {
1029
+ const { locale } = await params
1030
+ setRequestLocale(locale)
1031
+
1032
+ return withAdminContext(locale, async () => {
1033
+ const initialData = await fetchAuditLogData()
1034
+
1035
+ return (
1036
+ <div className="p-6">
1037
+ <div className="mb-6">
1038
+ <h1 className="text-2xl font-bold">Activity Log</h1>
1039
+ <p className="text-sm text-muted-foreground">
1040
+ Track all content changes across your CMS.
1041
+ </p>
1042
+ </div>
1043
+ <AuditLog
1044
+ initialData={initialData}
1045
+ editHrefPattern={\`/\${locale}/admin/:entityType/:entityId\`}
1046
+ />
1047
+ </div>
1048
+ )
1049
+ })
1050
+ }
1051
+ `),await n(a(e,`app/[locale]/(shell)/admin/tickets/page.tsx`),`import { Ticket, Department, TicketTag } from '@murumets-ee/ticketing'
1052
+ import { headers } from 'next/headers'
1053
+ import { setRequestLocale } from 'next-intl/server'
1054
+ import { withAdminContext } from '@/lib/with-admin-context'
1055
+ import { auth } from '@/lib/auth'
1056
+ import { TicketsInboxClient } from './tickets-inbox-client'
1057
+ import { fetchEntityList } from '@murumets-ee/admin-ui/server'
1058
+ import type {
1059
+ TicketData,
1060
+ DepartmentData,
1061
+ TagData,
1062
+ } from '@murumets-ee/ticketing-ui'
1063
+
1064
+ interface TicketsPageProps {
1065
+ params: Promise<{ locale: string }>
1066
+ }
1067
+
1068
+ export default async function TicketsPage({ params }: TicketsPageProps) {
1069
+ const { locale } = await params
1070
+ setRequestLocale(locale)
1071
+
1072
+ const h = await headers()
1073
+ const session = await auth.api.getSession({ headers: h })
1074
+ const currentUserId = session?.user?.id ?? ''
1075
+
1076
+ return withAdminContext(locale, async () => {
1077
+ const ticketData = await fetchEntityList(Ticket, {
1078
+ sortField: 'lastReplyAt',
1079
+ sortDirection: 'desc',
1080
+ limit: 50,
1081
+ })
1082
+
1083
+ const departmentData = await fetchEntityList(Department, {
1084
+ sortField: 'name',
1085
+ sortDirection: 'asc',
1086
+ limit: 100,
1087
+ })
1088
+
1089
+ const tagData = await fetchEntityList(TicketTag, {
1090
+ sortField: 'name',
1091
+ sortDirection: 'asc',
1092
+ limit: 100,
1093
+ })
1094
+
1095
+ return (
1096
+ <TicketsInboxClient
1097
+ initialTickets={ticketData.items as unknown as TicketData[]}
1098
+ initialTotal={ticketData.total}
1099
+ initialDepartments={departmentData.items as unknown as DepartmentData[]}
1100
+ initialTags={tagData.items as unknown as TagData[]}
1101
+ currentUserId={currentUserId}
1102
+ locale={locale}
1103
+ />
1104
+ )
1105
+ })
1106
+ }
1107
+ `),await n(a(e,`app/[locale]/(shell)/admin/tickets/tickets-inbox-client.tsx`),`'use client'
1108
+
1109
+ import { QueryProvider } from '@murumets-ee/admin-ui'
1110
+ import { InboxProvider, TicketInbox } from '@murumets-ee/ticketing-ui/inbox'
1111
+ import type {
1112
+ TicketData,
1113
+ DepartmentData,
1114
+ TagData,
1115
+ } from '@murumets-ee/ticketing-ui'
1116
+
1117
+ interface TicketsInboxClientProps {
1118
+ initialTickets: TicketData[]
1119
+ initialTotal: number
1120
+ initialDepartments: DepartmentData[]
1121
+ initialTags: TagData[]
1122
+ currentUserId: string
1123
+ locale: string
1124
+ }
1125
+
1126
+ export function TicketsInboxClient({
1127
+ initialTickets,
1128
+ initialTotal,
1129
+ initialDepartments,
1130
+ initialTags,
1131
+ currentUserId,
1132
+ }: TicketsInboxClientProps) {
1133
+ return (
1134
+ <QueryProvider>
1135
+ <InboxProvider
1136
+ apiBasePath="/api/admin"
1137
+ initialTickets={initialTickets}
1138
+ initialTotal={initialTotal}
1139
+ initialDepartments={initialDepartments}
1140
+ initialTags={initialTags}
1141
+ currentUserId={currentUserId}
1142
+ >
1143
+ <div className="h-[calc(100vh-3.5rem)]">
1144
+ <TicketInbox currentUserId={currentUserId} />
1145
+ </div>
1146
+ </InboxProvider>
1147
+ </QueryProvider>
1148
+ )
1149
+ }
1150
+ `),await n(a(e,`app/[locale]/(shell)/admin/tickets/board/page.tsx`),`import { Ticket, Department } from '@murumets-ee/ticketing'
1151
+ import { setRequestLocale } from 'next-intl/server'
1152
+ import { withAdminContext } from '@/lib/with-admin-context'
1153
+ import { fetchEntityList } from '@murumets-ee/admin-ui/server'
1154
+ import { TicketBoardClient } from './ticket-board-client'
1155
+ import type { TicketData, DepartmentData } from '@murumets-ee/ticketing-ui'
1156
+
1157
+ interface TicketBoardPageProps {
1158
+ params: Promise<{ locale: string }>
1159
+ }
1160
+
1161
+ export default async function TicketBoardPage({ params }: TicketBoardPageProps) {
1162
+ const { locale } = await params
1163
+ setRequestLocale(locale)
1164
+
1165
+ return withAdminContext(locale, async () => {
1166
+ const ticketData = await fetchEntityList(Ticket, {
1167
+ sortField: 'lastReplyAt',
1168
+ sortDirection: 'desc',
1169
+ limit: 200,
1170
+ })
1171
+
1172
+ const departmentData = await fetchEntityList(Department, {
1173
+ sortField: 'name',
1174
+ sortDirection: 'asc',
1175
+ limit: 100,
1176
+ })
1177
+
1178
+ return (
1179
+ <div className="p-6 h-[calc(100vh-3.5rem)]">
1180
+ <div className="mb-4">
1181
+ <h1 className="text-2xl font-bold">Ticket Board</h1>
1182
+ <p className="text-sm text-muted-foreground">
1183
+ Kanban view of tickets by status
1184
+ </p>
1185
+ </div>
1186
+ <TicketBoardClient
1187
+ initialTickets={ticketData.items as unknown as TicketData[]}
1188
+ initialDepartments={departmentData.items as unknown as DepartmentData[]}
1189
+ locale={locale}
1190
+ />
1191
+ </div>
1192
+ )
1193
+ })
1194
+ }
1195
+ `),await n(a(e,`app/[locale]/(shell)/admin/tickets/board/ticket-board-client.tsx`),`'use client'
1196
+
1197
+ import { useMemo } from 'react'
1198
+ import { TicketBoard } from '@murumets-ee/ticketing-ui/board'
1199
+ import type { TicketData, DepartmentData } from '@murumets-ee/ticketing-ui'
1200
+ import { useRouter } from 'next/navigation'
1201
+
1202
+ interface TicketBoardClientProps {
1203
+ initialTickets: TicketData[]
1204
+ initialDepartments: DepartmentData[]
1205
+ locale: string
1206
+ }
1207
+
1208
+ export function TicketBoardClient({
1209
+ initialTickets,
1210
+ initialDepartments,
1211
+ locale,
1212
+ }: TicketBoardClientProps) {
1213
+ const router = useRouter()
1214
+ const departmentMap = useMemo(
1215
+ () => new Map(initialDepartments.map((d) => [d.id, d])),
1216
+ [initialDepartments],
1217
+ )
1218
+
1219
+ return (
1220
+ <TicketBoard
1221
+ tickets={initialTickets}
1222
+ departments={departmentMap}
1223
+ onTicketSelect={(ticket) => {
1224
+ router.push(\`/\${locale}/admin/tickets?selected=\${ticket.id}\`)
1225
+ }}
1226
+ className="h-[calc(100%-4rem)]"
1227
+ />
1228
+ )
1229
+ }
1230
+ `),await n(a(e,`app/api/ticketing/inbound/route.ts`),`/**
1231
+ * Resend inbound email webhook endpoint.
1232
+ *
1233
+ * Public endpoint (no session auth) — protected by webhook signature
1234
+ * verification (HMAC-SHA256). Lives outside the admin API handler
1235
+ * because the admin handler requires authentication.
1236
+ */
1237
+
1238
+ import { getToolkitApp } from '@/lib/app'
1239
+
1240
+ await getToolkitApp()
1241
+
1242
+ export async function POST(req: Request): Promise<Response> {
1243
+ const { handleInboundWebhook } = await import('@murumets-ee/ticketing')
1244
+ const { QueueClient } = await import('@murumets-ee/queue/client')
1245
+ const { getApp } = await import('@murumets-ee/core')
1246
+
1247
+ const db = getApp().db.readWrite
1248
+ const queueClient = new QueueClient({ db })
1249
+
1250
+ return handleInboundWebhook(req, (type, payload) => queueClient.enqueue(type, payload))
1251
+ }
1252
+ `),await n(a(e,`app/api/admin/[...path]/route.ts`),`import { createAdminApiHandler } from '@murumets-ee/admin-ui/server'
1253
+ import { buildPermissionChecker, buildResourceCatalog } from '@murumets-ee/auth'
1254
+ import { permissionRoutes } from '@murumets-ee/auth/admin'
1255
+ import { ContentClient } from '@murumets-ee/content/client'
1256
+ import { LockService } from '@murumets-ee/content/lock'
1257
+ import type { PermissionChecker } from '@murumets-ee/core'
1258
+ import { getApp } from '@murumets-ee/core'
1259
+ import {
1260
+ AuditLogClient,
1261
+ createAuditDbWriter,
1262
+ createAuditLogger,
1263
+ createLogger,
1264
+ } from '@murumets-ee/logging'
1265
+ import { logRoutes } from '@murumets-ee/logging/admin'
1266
+ import { mediaRoutes } from '@murumets-ee/media/admin'
1267
+ import { createSettingsClient } from '@murumets-ee/settings'
1268
+ import { settingsRoutes } from '@murumets-ee/settings/admin'
1269
+ import { storageRoutes } from '@murumets-ee/storage/admin'
1270
+ import { taxonomyRoutes } from '@murumets-ee/taxonomy/admin'
1271
+ import { ticketingRoutes } from '@murumets-ee/ticketing/admin'
1272
+ import {
1273
+ allEntities,
1274
+ crudEntities,
1275
+ pluginResources,
1276
+ taxonomyVocabularies,
1277
+ } from '@/lib/admin-config'
1278
+ import { getToolkitApp } from '@/lib/app'
1279
+ import { auth } from '@/lib/auth'
1280
+ import { loadRoles } from '@/lib/load-roles'
1281
+ import { permissionSettings } from '@/settings/permissions'
1282
+ import { siteSettings } from '@/settings/site'
1283
+
1284
+ await getToolkitApp()
1285
+
1286
+ let _auditLogger: ReturnType<typeof createAuditLogger> | null = null
1287
+ let _checker: PermissionChecker | null = null
1288
+
1289
+ const routes = [
1290
+ mediaRoutes(),
1291
+ storageRoutes(),
1292
+ settingsRoutes(siteSettings),
1293
+ taxonomyRoutes(taxonomyVocabularies),
1294
+ ticketingRoutes(),
1295
+ logRoutes(() => new AuditLogClient(getApp().db.readWrite)),
1296
+ permissionRoutes({
1297
+ getStatements: () => buildResourceCatalog(allEntities, pluginResources),
1298
+ loadRoles: async () => loadRoles(getApp()),
1299
+ saveRoles: async (roles) => {
1300
+ const app = getApp()
1301
+ const client = createSettingsClient(permissionSettings, { app })
1302
+ await client.set('roles', roles)
1303
+ },
1304
+ onSave: () => {
1305
+ _checker = null
1306
+ },
1307
+ }),
1308
+ ]
1309
+
1310
+ const handler = createAdminApiHandler({
1311
+ authenticate: async (req) => {
1312
+ const session = await auth.api.getSession({ headers: req.headers })
1313
+ if (!session?.user) return null
1314
+ const role = (session.user as Record<string, unknown>).role as string | undefined
1315
+ return { id: session.user.id, role, name: session.user.name, email: session.user.email }
1316
+ },
1317
+ defaultLocale: 'en',
1318
+ entities: crudEntities,
1319
+ routes,
1320
+ loadPermissions: async () => {
1321
+ if (_checker) return _checker
1322
+ const roles = await loadRoles(getApp())
1323
+ _checker = buildPermissionChecker(roles)
1324
+ return _checker
1325
+ },
1326
+ auditLogger: {
1327
+ log: async (entry) => {
1328
+ if (!_auditLogger) {
1329
+ const app = getApp()
1330
+ _auditLogger = createAuditLogger({
1331
+ logger: createLogger({ name: 'audit' }),
1332
+ dbWriter: createAuditDbWriter(app.db.readWrite),
1333
+ })
1334
+ }
1335
+ return _auditLogger.log(entry)
1336
+ },
1337
+ },
1338
+ contentClientFactory: (entity) =>
1339
+ new ContentClient({ entity, db: getApp().db.readWrite }),
1340
+ lockServiceFactory: () =>
1341
+ new LockService({ db: getApp().db.readWrite }),
1342
+ })
1343
+
1344
+ export const { GET, POST, PATCH, DELETE } = handler
1345
+ `)}async function c(e,t){await n(a(e,`lib/auth.ts`),`import { getToolkitApp } from './app'
1346
+ import { getAuth } from '@murumets-ee/auth'
1347
+
1348
+ export async function getAuthInstance() {
1349
+ await getToolkitApp()
1350
+ return getAuth()
1351
+ }
1352
+ `),await n(a(e,`lib/auth-client.ts`),`import { createClient } from '@murumets-ee/auth/client'
1353
+
1354
+ export const authClient = createClient()
1355
+ `),await n(a(e,`app/api/auth/[...all]/route.ts`),`import { toNextJsHandler } from 'better-auth/next-js'
1356
+ import { getAuthInstance } from '../../../../lib/auth'
1357
+
1358
+ let _handler: ReturnType<typeof toNextJsHandler> | null = null
1359
+
1360
+ async function handler() {
1361
+ if (!_handler) {
1362
+ const auth = await getAuthInstance()
1363
+ _handler = toNextJsHandler(auth)
1364
+ }
1365
+ return _handler
1366
+ }
1367
+
1368
+ export async function GET(req: Request) {
1369
+ const h = await handler()
1370
+ return h.GET(req)
1371
+ }
1372
+
1373
+ export async function POST(req: Request) {
1374
+ const h = await handler()
1375
+ return h.POST(req)
1376
+ }
1377
+ `),await n(a(e,`app/[locale]/auth/layout.tsx`),`import { AuthProviders } from './providers'
1378
+ import type { ReactNode } from 'react'
1379
+
1380
+ export default function AuthLayout({ children }: { children: ReactNode }) {
1381
+ return (
1382
+ <AuthProviders>
1383
+ <div className="flex min-h-[calc(100vh-3rem)] items-center justify-center px-4">
1384
+ {children}
1385
+ </div>
1386
+ </AuthProviders>
1387
+ )
1388
+ }
1389
+ `),await n(a(e,`app/[locale]/auth/providers.tsx`),`'use client'
1390
+
1391
+ import { AuthUIProvider } from '@murumets-ee/auth-ui'
1392
+ import { authClient } from '@/lib/auth-client'
1393
+ import Link from 'next/link'
1394
+ import { useRouter } from 'next/navigation'
1395
+ import { useLocale } from 'next-intl'
1396
+ import type { ReactNode } from 'react'
1397
+
1398
+ export function AuthProviders({ children }: { children: ReactNode }) {
1399
+ const router = useRouter()
1400
+ const locale = useLocale()
1401
+
1402
+ return (
1403
+ <AuthUIProvider
1404
+ authClient={authClient as never}
1405
+ basePath="/auth"
1406
+ redirectTo="/"
1407
+ Link={Link}
1408
+ navigate={(url) => router.push(url)}
1409
+ resetPasswordUrl={\`/\${locale}/auth/reset-password\`}
1410
+ >
1411
+ {children}
1412
+ </AuthUIProvider>
1413
+ )
1414
+ }
1415
+ `),await n(a(e,`app/[locale]/auth/sign-in/page.tsx`),`import { SignInForm } from '@murumets-ee/auth-ui'
1416
+
1417
+ export default function SignInPage() {
1418
+ return <SignInForm />
1419
+ }
1420
+ `),await n(a(e,`app/[locale]/auth/sign-up/page.tsx`),`import { SignUpForm } from '@murumets-ee/auth-ui'
1421
+
1422
+ export default function SignUpPage() {
1423
+ return <SignUpForm />
1424
+ }
1425
+ `),await n(a(e,`app/[locale]/auth/forgot-password/page.tsx`),`import { ForgotPasswordForm } from '@murumets-ee/auth-ui'
1426
+
1427
+ export default function ForgotPasswordPage() {
1428
+ return <ForgotPasswordForm />
1429
+ }
1430
+ `),await n(a(e,`app/[locale]/auth/reset-password/page.tsx`),`import { Suspense } from 'react'
1431
+ import { ResetPasswordContent } from './content'
1432
+
1433
+ export default function ResetPasswordPage() {
1434
+ return (
1435
+ <Suspense>
1436
+ <ResetPasswordContent />
1437
+ </Suspense>
1438
+ )
1439
+ }
1440
+ `),await n(a(e,`app/[locale]/auth/reset-password/content.tsx`),`'use client'
1441
+
1442
+ import { useSearchParams } from 'next/navigation'
1443
+ import { ResetPasswordForm } from '@murumets-ee/auth-ui'
1444
+
1445
+ export function ResetPasswordContent() {
1446
+ const searchParams = useSearchParams()
1447
+ const token = searchParams.get('token')
1448
+
1449
+ if (!token) {
1450
+ return (
1451
+ <div className="text-center">
1452
+ <h1 className="text-2xl font-bold text-zinc-900 dark:text-zinc-50">
1453
+ Invalid or expired link
1454
+ </h1>
1455
+ <p className="mt-2 text-zinc-500">
1456
+ Please request a new password reset.
1457
+ </p>
1458
+ </div>
1459
+ )
1460
+ }
1461
+
1462
+ return <ResetPasswordForm token={token} />
1463
+ }
1464
+ `),await n(a(e,`app/[locale]/setup/page.tsx`),`import { redirect } from 'next/navigation'
1465
+ import { sql } from 'drizzle-orm'
1466
+ import { getToolkitApp } from '@/lib/app'
1467
+ import { SetupForm } from './form'
1468
+
1469
+ export default async function SetupPage() {
1470
+ const app = await getToolkitApp()
1471
+ const result = await app.db.readOnly.execute<{ count: string }>(
1472
+ sql\`SELECT COUNT(*)::text as count FROM "user"\`,
1473
+ )
1474
+
1475
+ if (Number(result[0]?.count) > 0) {
1476
+ redirect('/')
1477
+ }
1478
+
1479
+ return (
1480
+ <div className="max-w-md mx-auto p-8">
1481
+ <h1 className="text-2xl font-bold mb-2">Create Admin</h1>
1482
+ <p className="text-sm text-zinc-500 dark:text-zinc-400 mb-6">
1483
+ No users found. Create the first admin account.
1484
+ </p>
1485
+ <SetupForm />
1486
+ </div>
1487
+ )
1488
+ }
1489
+ `),await n(a(e,`app/[locale]/setup/form.tsx`),`'use client'
1490
+
1491
+ import { useState } from 'react'
1492
+ import { createFirstAdmin } from './actions'
1493
+
1494
+ export function SetupForm() {
1495
+ const [result, setResult] = useState<{ ok?: boolean; error?: string; email?: string } | null>(null)
1496
+ const [loading, setLoading] = useState(false)
1497
+
1498
+ async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
1499
+ e.preventDefault()
1500
+ setLoading(true)
1501
+ setResult(null)
1502
+ const res = await createFirstAdmin(new FormData(e.currentTarget))
1503
+ setResult(res)
1504
+ setLoading(false)
1505
+ }
1506
+
1507
+ if (result?.ok) {
1508
+ return (
1509
+ <div className="space-y-2">
1510
+ <p className="text-green-600 dark:text-green-400">Admin created: {result.email}</p>
1511
+ <a href="/auth/sign-in" className="text-blue-600 dark:text-blue-400 hover:underline">
1512
+ Sign in &rarr;
1513
+ </a>
1514
+ </div>
1515
+ )
1516
+ }
1517
+
1518
+ return (
1519
+ <form onSubmit={handleSubmit} className="flex flex-col gap-4">
1520
+ <label className="text-sm font-medium">
1521
+ Name
1522
+ <input
1523
+ name="name"
1524
+ required
1525
+ className="mt-1 block w-full px-3 py-2 bg-zinc-100 dark:bg-zinc-900 border border-zinc-300 dark:border-zinc-700 rounded-md text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
1526
+ />
1527
+ </label>
1528
+ <label className="text-sm font-medium">
1529
+ Email
1530
+ <input
1531
+ name="email"
1532
+ type="email"
1533
+ required
1534
+ className="mt-1 block w-full px-3 py-2 bg-zinc-100 dark:bg-zinc-900 border border-zinc-300 dark:border-zinc-700 rounded-md text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
1535
+ />
1536
+ </label>
1537
+ <label className="text-sm font-medium">
1538
+ Password (min 8 chars)
1539
+ <input
1540
+ name="password"
1541
+ type="password"
1542
+ required
1543
+ minLength={8}
1544
+ className="mt-1 block w-full px-3 py-2 bg-zinc-100 dark:bg-zinc-900 border border-zinc-300 dark:border-zinc-700 rounded-md text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
1545
+ />
1546
+ </label>
1547
+
1548
+ {result?.error && <p className="text-red-600 dark:text-red-400 text-sm">{result.error}</p>}
1549
+
1550
+ <button
1551
+ type="submit"
1552
+ disabled={loading}
1553
+ className="px-4 py-2 text-sm rounded-md bg-blue-600 text-white hover:bg-blue-500 disabled:opacity-50 transition-colors"
1554
+ >
1555
+ {loading ? 'Creating...' : 'Create Admin'}
1556
+ </button>
1557
+ </form>
1558
+ )
1559
+ }
1560
+ `),await n(a(e,`app/[locale]/setup/actions.ts`),`'use server'
1561
+
1562
+ import { sql } from 'drizzle-orm'
1563
+ import { getToolkitApp } from '@/lib/app'
1564
+ import { getAuth } from '@murumets-ee/auth'
1565
+
1566
+ /**
1567
+ * Create the first admin user. Locked down:
1568
+ * - Advisory lock prevents race conditions (two simultaneous requests)
1569
+ * - User count check inside the lock ensures only one admin can be created
1570
+ * - Once any user exists, this action permanently refuses
1571
+ */
1572
+ export async function createFirstAdmin(formData: FormData) {
1573
+ const email = formData.get('email') as string
1574
+ const password = formData.get('password') as string
1575
+ const name = formData.get('name') as string
1576
+
1577
+ if (!email || !password || !name) {
1578
+ return { error: 'All fields are required' }
1579
+ }
1580
+
1581
+ if (password.length < 8) {
1582
+ return { error: 'Password must be at least 8 characters' }
1583
+ }
1584
+
1585
+ const app = await getToolkitApp()
1586
+
1587
+ // Acquire advisory lock + check atomically in a transaction
1588
+ const canCreate = await app.db.readWrite.transaction(async (tx) => {
1589
+ // Advisory lock 1 = "setup lock". Blocks concurrent setup attempts.
1590
+ await tx.execute(sql\`SELECT pg_advisory_xact_lock(1)\`)
1591
+
1592
+ const result = await tx.execute<{ count: string }>(
1593
+ sql\`SELECT COUNT(*)::text as count FROM "user"\`,
1594
+ )
1595
+ return Number(result[0]?.count) === 0
1596
+ })
1597
+
1598
+ if (!canCreate) {
1599
+ return { error: 'Admin user already exists. Setup is complete.' }
1600
+ }
1601
+
1602
+ const auth = getAuth()
1603
+
1604
+ const adminUser = await auth.api.signUpEmail({
1605
+ body: { email, password, name },
1606
+ })
1607
+
1608
+ await app.db.readWrite.execute(
1609
+ sql\`UPDATE "user" SET role = 'admin' WHERE id = \${adminUser.user.id}\`,
1610
+ )
1611
+
1612
+ return { ok: true, email: adminUser.user.email }
1613
+ }
1614
+ `)}async function l(e,t){let{name:r}=t;await n(a(e,`.env.example`),`DATABASE_URL=postgresql://${r}:${r}_dev_password@localhost:5432/${r}_dev
1615
+ BETTER_AUTH_SECRET=dev-secret-change-me-in-production-min-32-chars
1616
+ BETTER_AUTH_URL=http://localhost:3000
1617
+ LOG_LEVEL=debug
1618
+ NEXT_PUBLIC_APP_URL=http://localhost:3000
1619
+ # Queue worker — by default runs embedded in the web process.
1620
+ # Set to "false" in production and run "pnpm worker" as a separate process.
1621
+ # QUEUE_WORKER=false
1622
+ RESEND_API_KEY=
1623
+ RESEND_WEBHOOK_SECRET=
1624
+ MAIL_FROM=noreply@example.com
1625
+ CSAT_SECRET=
1626
+ `),await n(a(e,`.dockerignore`),`# Dependencies (installed inside Docker)
1627
+ node_modules/
1628
+ .pnpm-store/
1629
+
1630
+ # Build outputs (rebuilt inside Docker)
1631
+ .next/
1632
+ out/
1633
+ dist/
1634
+
1635
+ # Git
1636
+ .git/
1637
+ .gitignore
1638
+
1639
+ # Environment files (pass via docker run --env-file)
1640
+ .env
1641
+ .env.*
1642
+ !.env.example
1643
+
1644
+ # Docker files
1645
+ Dockerfile*
1646
+ .dockerignore
1647
+ docker-compose*.yml
1648
+
1649
+ # Tests
1650
+ coverage/
1651
+ **/*.test.*
1652
+ **/*.spec.*
1653
+ **/vitest.config.*
1654
+ docker-compose.test.yml
1655
+
1656
+ # Development tooling
1657
+ .vscode/
1658
+ .idea/
1659
+ .turbo/
1660
+ .cache/
1661
+ *.tsbuildinfo
1662
+
1663
+ # Documentation
1664
+ *.md
1665
+ docs/
1666
+
1667
+ # OS files
1668
+ .DS_Store
1669
+ Thumbs.db
1670
+ `),await n(a(e,`Dockerfile`),`# --- Base image ---
1671
+ # Node 22 LTS (Debian slim — glibc required for sharp image optimization)
1672
+ FROM node:22-slim AS base
1673
+
1674
+ # --- Stage 1: Install dependencies ---
1675
+ FROM base AS deps
1676
+ WORKDIR /app
1677
+ RUN corepack enable pnpm
1678
+ COPY package.json pnpm-lock.yaml ./
1679
+ RUN --mount=type=cache,id=pnpm,target=/root/.local/share/pnpm/store \\
1680
+ pnpm install --frozen-lockfile
1681
+
1682
+ # --- Stage 2: Build the application ---
1683
+ FROM base AS builder
1684
+ WORKDIR /app
1685
+ RUN corepack enable pnpm
1686
+ COPY --from=deps /app/node_modules ./node_modules
1687
+ COPY . .
1688
+ ENV NODE_ENV=production
1689
+ ENV NEXT_TELEMETRY_DISABLED=1
1690
+ # Dummy env vars so toolkit.config.ts doesn't throw at build time (no DB connection needed)
1691
+ ENV DATABASE_URL=postgresql://build:build@localhost:5432/build
1692
+ ENV BETTER_AUTH_SECRET=build-secret-not-used-at-runtime
1693
+ RUN pnpm build
1694
+
1695
+ # --- Stage 3: Production runner ---
1696
+ FROM base AS runner
1697
+ WORKDIR /app
1698
+ ENV NODE_ENV=production
1699
+ ENV PORT=3000
1700
+ ENV HOSTNAME=0.0.0.0
1701
+ ENV NEXT_TELEMETRY_DISABLED=1
1702
+
1703
+ # Copy standalone output (includes server.js + traced node_modules)
1704
+ COPY --from=builder --chown=node:node /app/.next/standalone ./
1705
+ # Copy static assets (JS/CSS chunks — excluded from standalone trace)
1706
+ COPY --from=builder --chown=node:node /app/.next/static ./.next/static
1707
+ # Copy public assets (favicon, robots.txt, images)
1708
+ COPY --from=builder --chown=node:node /app/public ./public
1709
+ # Copy migrations (applied at app startup by the toolkit migration runner)
1710
+ COPY --from=builder --chown=node:node /app/migrations ./migrations
1711
+
1712
+ # Run as non-root user
1713
+ USER node
1714
+ EXPOSE 3000
1715
+ CMD ["node", "server.js"]
1716
+ `),await n(a(e,`docker-compose.yml`),`services:
1717
+ postgres:
1718
+ image: postgres:17-alpine
1719
+ container_name: ${r}-postgres
1720
+ restart: unless-stopped
1721
+ environment:
1722
+ POSTGRES_USER: ${r}
1723
+ POSTGRES_PASSWORD: ${r}_dev_password
1724
+ POSTGRES_DB: ${r}_dev
1725
+ ports:
1726
+ - "5432:5432"
1727
+ volumes:
1728
+ - postgres_data:/var/lib/postgresql/data
1729
+ healthcheck:
1730
+ test: ["CMD-SHELL", "pg_isready -U ${r} -d ${r}_dev"]
1731
+ interval: 10s
1732
+ timeout: 5s
1733
+ retries: 5
1734
+
1735
+ volumes:
1736
+ postgres_data:
1737
+ name: ${r}_postgres_data
1738
+ `),await n(a(e,`docker-compose.prod.yml`),`services:
1739
+ app:
1740
+ build: .
1741
+ restart: unless-stopped
1742
+ env_file: .env
1743
+ depends_on:
1744
+ postgres:
1745
+ condition: service_healthy
1746
+ ports:
1747
+ - "3000:3000"
1748
+ networks:
1749
+ - internal
1750
+
1751
+ postgres:
1752
+ image: postgres:17-alpine
1753
+ restart: unless-stopped
1754
+ environment:
1755
+ POSTGRES_USER: ${r}
1756
+ POSTGRES_PASSWORD: \${DB_PASSWORD}
1757
+ POSTGRES_DB: ${r}
1758
+ volumes:
1759
+ - postgres_data:/var/lib/postgresql/data
1760
+ healthcheck:
1761
+ test: ["CMD-SHELL", "pg_isready -U ${r} -d ${r}"]
1762
+ interval: 10s
1763
+ timeout: 5s
1764
+ retries: 5
1765
+ networks:
1766
+ - internal
1767
+
1768
+ volumes:
1769
+ postgres_data:
1770
+
1771
+ networks:
1772
+ internal:
1773
+ `),await i(a(e,`.gitignore`),`
1774
+ # Toolkit generated files
1775
+ generated/
1776
+
1777
+ # Environment
1778
+ .env*
1779
+ !.env.example
1780
+ `)}async function u(e,t){await n(a(e,`entities/index.ts`),`export { Article } from './article'
1781
+ export { Category } from './category'
1782
+ `),await n(a(e,`entities/article.ts`),`import { behavior, defineEntity, field } from '@murumets-ee/entity'
1783
+
1784
+ export const Article = defineEntity({
1785
+ name: 'article',
1786
+ fields: {
1787
+ title: field.text({ required: true, maxLength: 200, indexed: true, translatable: true }),
1788
+ slug: field.slug({ from: 'title', unique: true }),
1789
+ excerpt: field.text({ maxLength: 500, translatable: true }),
1790
+ body: field.richtext(),
1791
+ viewCount: field.number({ default: 0, integer: true }),
1792
+ featured: field.boolean({ default: false }),
1793
+ publishDate: field.date(),
1794
+ contentType: field.select({ options: ['news', 'tutorial', 'announcement'], default: 'news' }),
1795
+ category: field.reference({ entity: 'category', required: false }),
1796
+ tags: field.reference({ entity: 'category', cardinality: 'many' }),
1797
+ coverImage: field.media({ accept: ['image/*'] }),
1798
+ },
1799
+ behaviors: [
1800
+ behavior.publishable(),
1801
+ behavior.auditable(),
1802
+ behavior.sluggable('title'),
1803
+ behavior.revisionable(),
1804
+ ],
1805
+ scope: 'global',
1806
+ access: {
1807
+ view: 'public',
1808
+ create: 'group.editor',
1809
+ update: 'group.editor',
1810
+ delete: 'group.admin',
1811
+ },
1812
+ })
1813
+ `),await n(a(e,`entities/category.ts`),`import { defineEntity, field } from '@murumets-ee/entity'
1814
+
1815
+ export const Category = defineEntity({
1816
+ name: 'category',
1817
+ fields: {
1818
+ name: field.text({ required: true, maxLength: 100, indexed: true, translatable: true }),
1819
+ slug: field.slug({ from: 'name', unique: true }),
1820
+ description: field.text({ maxLength: 500, translatable: true }),
1821
+ },
1822
+ scope: 'global',
1823
+ access: {
1824
+ view: 'public',
1825
+ create: 'group.editor',
1826
+ update: 'group.editor',
1827
+ delete: 'group.admin',
1828
+ },
1829
+ })
1830
+ `)}async function d(e,t){await n(a(e,`i18n/routing.ts`),`import { defineRouting } from 'next-intl/routing'
1831
+
1832
+ export const routing = defineRouting({
1833
+ locales: ['en'],
1834
+ defaultLocale: 'en',
1835
+ })
1836
+ `),await n(a(e,`i18n/request.ts`),`import { getRequestConfig } from 'next-intl/server'
1837
+ import { hasLocale } from 'next-intl'
1838
+ import { routing } from './routing'
1839
+ import { getAuthMessages } from '@murumets-ee/auth-ui/i18n'
1840
+
1841
+ export default getRequestConfig(async ({ requestLocale }) => {
1842
+ const requested = await requestLocale
1843
+ const locale = hasLocale(routing.locales, requested)
1844
+ ? requested
1845
+ : routing.defaultLocale
1846
+
1847
+ const authMessages = await getAuthMessages(locale)
1848
+
1849
+ return {
1850
+ locale,
1851
+ messages: {
1852
+ ...authMessages,
1853
+ },
1854
+ }
1855
+ })
1856
+ `)}const f={myorgCore:`0.1.0`,myorgDb:`0.1.0`,myorgEntity:`0.1.0`,myorgLogging:`0.1.0`,myorgAuth:`0.1.0`,myorgAuthUi:`0.1.0`,myorgAdminUi:`0.1.0`,myorgContent:`0.1.0`,myorgContentApi:`0.1.0`,myorgSettings:`0.1.0`,myorgStorage:`0.1.0`,myorgMedia:`0.1.0`,myorgTaxonomy:`0.1.0`,myorgQueue:`0.1.0`,myorgMail:`0.1.0`,myorgTicketing:`0.1.0`,myorgTicketingUi:`0.1.0`,myorgEditor:`0.1.0`,myorgBlocks:`0.1.0`,myorgTokens:`0.1.0`,myorgUi:`0.1.0`,myorgCli:`0.1.0`,betterAuth:`1.4.0`,drizzleOrm:`0.45.1`,nextIntl:`4.8.2`,nextThemes:`0.4.6`,lucideReact:`0.563.0`,postgres:`3.4.5`,reactHookForm:`7.71.1`,hookformResolvers:`5.2.2`,zod:`3.24.1`,tanstackReactQuery:`5.60.5`,tanstackReactTable:`8.21.3`,drizzleKit:`0.31.10`,tsx:`4.19.2`,babelReactCompiler:`1.0.0`};async function p(e,t,n){await m(e,t),n?.(`Workspace root created`),n?.(`Creating admin app...`),await g(e,t),n?.(`Admin app created`),n?.(`Creating web app...`),await _(e,t),n?.(`Web app created`),await h(e,t),n?.(`Shared config package created`)}async function m(e,t){let{name:r}=t;await o(e,{recursive:!0}),await n(a(e,`pnpm-workspace.yaml`),`packages:
1857
+ - 'packages/*'
1858
+ - 'apps/*'
1859
+
1860
+ ignoredBuiltDependencies:
1861
+ - sharp
1862
+ - unrs-resolver
1863
+ `),await n(a(e,`package.json`),`${JSON.stringify({name:`@${r}/monorepo`,version:`0.0.0`,private:!0,type:`module`,scripts:{dev:`turbo dev`,build:`turbo build`,"db:generate":`tsx --env-file=.env packages/config/scripts/generate-schema.ts`,"db:migrate:generate":`drizzle-kit generate --config packages/config/drizzle.config.ts`,"db:migrate":`tsx --env-file=.env packages/config/scripts/migrate.ts`,"db:reset":`tsx --env-file=.env packages/config/scripts/reset-db.ts`},devDependencies:{turbo:`^2.3.3`,typescript:`^5.7.3`,tsx:`^${f.tsx}`,"drizzle-kit":`^${f.drizzleKit}`}},null,2)}\n`),await n(a(e,`.gitignore`),`# dependencies
1864
+ node_modules/
1865
+
1866
+ # build
1867
+ dist/
1868
+ .next/
1869
+ .turbo/
1870
+
1871
+ # env
1872
+ .env*
1873
+ !.env.example
1874
+
1875
+ # toolkit generated
1876
+ generated/
1877
+
1878
+ # IDE
1879
+ .vscode/
1880
+ .idea/
1881
+
1882
+ # OS
1883
+ .DS_Store
1884
+ Thumbs.db
1885
+
1886
+ # logs
1887
+ *.log
1888
+
1889
+ # migrations meta
1890
+ migrations/
1891
+
1892
+ # turbo
1893
+ .turbo/
1894
+ `),await n(a(e,`.env.example`),`DATABASE_URL=postgresql://${r}:${r}_dev_password@localhost:5432/${r}_dev
1895
+ BETTER_AUTH_SECRET=dev-secret-change-me-in-production-min-32-chars
1896
+ BETTER_AUTH_URL=http://localhost:3000
1897
+ LOG_LEVEL=debug
1898
+ NEXT_PUBLIC_APP_URL=http://localhost:3000
1899
+ QUEUE_WORKER=true
1900
+ RESEND_API_KEY=
1901
+ RESEND_WEBHOOK_SECRET=
1902
+ MAIL_FROM=noreply@example.com
1903
+ CSAT_SECRET=
1904
+ `),await n(a(e,`docker-compose.yml`),`services:
1905
+ postgres:
1906
+ image: postgres:17-alpine
1907
+ container_name: ${r}-postgres
1908
+ restart: unless-stopped
1909
+ environment:
1910
+ POSTGRES_USER: ${r}
1911
+ POSTGRES_PASSWORD: ${r}_dev_password
1912
+ POSTGRES_DB: ${r}_dev
1913
+ ports:
1914
+ - "5432:5432"
1915
+ volumes:
1916
+ - postgres_data:/var/lib/postgresql/data
1917
+ healthcheck:
1918
+ test: ["CMD-SHELL", "pg_isready -U ${r} -d ${r}_dev"]
1919
+ interval: 10s
1920
+ timeout: 5s
1921
+ retries: 5
1922
+
1923
+ volumes:
1924
+ postgres_data:
1925
+ name: ${r}_postgres_data
1926
+ `)}async function h(e,t){let{name:r}=t,i=a(e,`packages/config`);await n(a(i,`package.json`),`${JSON.stringify({name:`@${r}/config`,version:`0.1.0`,private:!0,type:`module`,exports:{".":`./toolkit.config.ts`,"./entities":`./entities/index.ts`,"./entities/*":`./entities/*`,"./app":`./lib/app.ts`,"./auth":`./lib/auth.ts`,"./auth-client":`./lib/auth-client.ts`},dependencies:{"@murumets-ee/core":`^${f.myorgCore}`,"@murumets-ee/db":`^${f.myorgDb}`,"@murumets-ee/entity":`^${f.myorgEntity}`,"@murumets-ee/logging":`^${f.myorgLogging}`,"@murumets-ee/auth":`^${f.myorgAuth}`,"better-auth":`^${f.betterAuth}`,"drizzle-orm":`^${f.drizzleOrm}`,postgres:`^${f.postgres}`,zod:`^${f.zod}`}},null,2)}\n`),await n(a(i,`tsconfig.json`),`${JSON.stringify({compilerOptions:{target:`ES2022`,module:`ESNext`,moduleResolution:`Bundler`,strict:!0,esModuleInterop:!0,skipLibCheck:!0,resolveJsonModule:!0},include:[`**/*.ts`]},null,2)}\n`),await n(a(i,`toolkit.config.ts`),`import { auth } from '@murumets-ee/auth/plugin'
1927
+ import { content } from '@murumets-ee/content/plugin'
1928
+ import { defineConfig } from '@murumets-ee/core'
1929
+ import { logging } from '@murumets-ee/logging/plugin'
1930
+ import { mail, ResendMailProvider } from '@murumets-ee/mail'
1931
+ import { media } from '@murumets-ee/media/plugin'
1932
+ import { queue } from '@murumets-ee/queue/plugin'
1933
+ import { settings } from '@murumets-ee/settings/plugin'
1934
+ import { storage } from '@murumets-ee/storage/plugin'
1935
+ import { taxonomy } from '@murumets-ee/taxonomy/plugin'
1936
+ import { ticketing } from '@murumets-ee/ticketing/plugin'
1937
+ import { Article, Category } from './entities'
1938
+ import * as authSchema from './generated/auth-schema'
1939
+
1940
+ if (!process.env.DATABASE_URL) {
1941
+ throw new Error('DATABASE_URL environment variable is required')
1942
+ }
1943
+
1944
+ export default defineConfig({
1945
+ db: {
1946
+ url: process.env.DATABASE_URL,
1947
+ poolMin: 2,
1948
+ poolMax: 10,
1949
+ },
1950
+ logging: {
1951
+ level: (process.env.LOG_LEVEL || 'info') as 'debug' | 'info' | 'warn' | 'error',
1952
+ name: '${r}',
1953
+ },
1954
+ entities: [Category, Article],
1955
+ plugins: [
1956
+ auth({ providers: ['email'], schema: authSchema }),
1957
+ content({
1958
+ locales: [{ code: 'en', label: 'English' }],
1959
+ defaultLocale: 'en',
1960
+ }),
1961
+ logging(),
1962
+ settings(),
1963
+ storage(),
1964
+ media(),
1965
+ taxonomy(),
1966
+ queue(),
1967
+ mail({
1968
+ provider: process.env.RESEND_API_KEY
1969
+ ? new ResendMailProvider({ apiKey: process.env.RESEND_API_KEY })
1970
+ : undefined,
1971
+ defaultFrom: process.env.MAIL_FROM ?? 'noreply@example.com',
1972
+ webhookSecret: process.env.RESEND_WEBHOOK_SECRET,
1973
+ }),
1974
+ ticketing({
1975
+ csatSecret: process.env.CSAT_SECRET,
1976
+ }),
1977
+ ],
1978
+ projectRoot: import.meta.dirname,
1979
+ })
1980
+ `),await n(a(i,`auth.config.ts`),`import { betterAuth } from 'better-auth'
1981
+ import { drizzleAdapter } from 'better-auth/adapters/drizzle'
1982
+ import { admin } from 'better-auth/plugins'
1983
+ import { organization } from 'better-auth/plugins/organization'
1984
+ import { drizzle } from 'drizzle-orm/postgres-js'
1985
+ import postgres from 'postgres'
1986
+
1987
+ const sql = postgres(process.env.DATABASE_URL!)
1988
+ const db = drizzle(sql)
1989
+
1990
+ export const auth = betterAuth({
1991
+ database: drizzleAdapter(db, { provider: 'pg' }),
1992
+ emailAndPassword: { enabled: true },
1993
+ plugins: [
1994
+ admin(),
1995
+ organization(),
1996
+ ],
1997
+ })
1998
+ `),await n(a(i,`drizzle.config.ts`),`import type { Config } from 'drizzle-kit'
1999
+
2000
+ if (!process.env.DATABASE_URL) {
2001
+ throw new Error('DATABASE_URL environment variable is required')
2002
+ }
2003
+
2004
+ export default {
2005
+ schema: ['./generated/schema.ts', './generated/auth-schema.ts'],
2006
+ out: './migrations',
2007
+ dialect: 'postgresql',
2008
+ dbCredentials: {
2009
+ url: process.env.DATABASE_URL,
2010
+ },
2011
+ } satisfies Config
2012
+ `),await n(a(i,`entities/index.ts`),`export { Article } from './article'
2013
+ export { Category } from './category'
2014
+ `),await n(a(i,`entities/article.ts`),`import { behavior, defineEntity, field } from '@murumets-ee/entity'
2015
+
2016
+ export const Article = defineEntity({
2017
+ name: 'article',
2018
+ fields: {
2019
+ title: field.text({ required: true, maxLength: 200, indexed: true, translatable: true }),
2020
+ slug: field.slug({ from: 'title', unique: true }),
2021
+ excerpt: field.text({ maxLength: 500, translatable: true }),
2022
+ body: field.richtext(),
2023
+ viewCount: field.number({ default: 0, integer: true }),
2024
+ featured: field.boolean({ default: false }),
2025
+ publishDate: field.date(),
2026
+ contentType: field.select({ options: ['news', 'tutorial', 'announcement'], default: 'news' }),
2027
+ category: field.reference({ entity: 'category', required: false }),
2028
+ tags: field.reference({ entity: 'category', cardinality: 'many' }),
2029
+ coverImage: field.media({ accept: ['image/*'] }),
2030
+ },
2031
+ behaviors: [
2032
+ behavior.publishable(),
2033
+ behavior.auditable(),
2034
+ behavior.sluggable('title'),
2035
+ behavior.revisionable(),
2036
+ ],
2037
+ scope: 'global',
2038
+ access: {
2039
+ view: 'public',
2040
+ create: 'group.editor',
2041
+ update: 'group.editor',
2042
+ delete: 'group.admin',
2043
+ },
2044
+ })
2045
+ `),await n(a(i,`entities/category.ts`),`import { defineEntity, field } from '@murumets-ee/entity'
2046
+
2047
+ export const Category = defineEntity({
2048
+ name: 'category',
2049
+ fields: {
2050
+ name: field.text({ required: true, maxLength: 100, indexed: true, translatable: true }),
2051
+ slug: field.slug({ from: 'name', unique: true }),
2052
+ description: field.text({ maxLength: 500, translatable: true }),
2053
+ },
2054
+ scope: 'global',
2055
+ access: {
2056
+ view: 'public',
2057
+ create: 'group.editor',
2058
+ update: 'group.editor',
2059
+ delete: 'group.admin',
2060
+ },
2061
+ })
2062
+ `),await n(a(i,`lib/app.ts`),`import { createApp, setApp, type ToolkitApp } from '@murumets-ee/core'
2063
+ import config from '../toolkit.config'
2064
+
2065
+ let appInstance: ToolkitApp | null = null
2066
+
2067
+ export async function getToolkitApp(): Promise<ToolkitApp> {
2068
+ if (!appInstance) {
2069
+ appInstance = await createApp(config)
2070
+ setApp(appInstance)
2071
+ }
2072
+ return appInstance
2073
+ }
2074
+ `),await n(a(i,`lib/auth.ts`),`import { getToolkitApp } from './app'
2075
+ import { getAuth } from '@murumets-ee/auth'
2076
+
2077
+ export async function getAuthInstance() {
2078
+ await getToolkitApp()
2079
+ return getAuth()
2080
+ }
2081
+ `),await n(a(i,`lib/auth-client.ts`),`import { createClient } from '@murumets-ee/auth/client'
2082
+
2083
+ export const authClient = createClient()
2084
+ `),await n(a(i,`generated/auth-schema.ts`),`// This file is generated by better-auth CLI.
2085
+ // Run: npx @better-auth/cli generate --config auth.config.ts -y
2086
+ export {}
2087
+ `),await n(a(i,`scripts/generate-schema.ts`),`/**
2088
+ * Generate Drizzle schemas from entity definitions
2089
+ */
2090
+
2091
+ import { mkdir, writeFile } from 'node:fs/promises'
2092
+ import { join } from 'node:path'
2093
+ import { generateSchemaCode, generateTranslationSchemaCode } from '@murumets-ee/entity'
2094
+ import config from '../toolkit.config'
2095
+
2096
+ async function generateSchemas() {
2097
+ console.log('Generating Drizzle schemas from entity definitions...')
2098
+
2099
+ const schemaDir = join(import.meta.dirname, '..', 'generated')
2100
+ await mkdir(schemaDir, { recursive: true })
2101
+
2102
+ const imports: string[] = []
2103
+ const schemas: string[] = []
2104
+ let hasTranslations = false
2105
+
2106
+ for (const entity of config.entities) {
2107
+ console.log(\` - Generating schema for \${entity.name}\`)
2108
+
2109
+ const schemaCode = generateSchemaCode(entity)
2110
+ schemas.push(\`\\n// \${entity.name} table\`)
2111
+ schemas.push(schemaCode)
2112
+
2113
+ const translationCode = generateTranslationSchemaCode(entity)
2114
+ if (translationCode) {
2115
+ hasTranslations = true
2116
+ schemas.push(\`\\n// \${entity.name} translations\`)
2117
+ schemas.push(translationCode)
2118
+ }
2119
+ }
2120
+
2121
+ const pgCoreTypes = ['pgTable', 'varchar', 'text', 'boolean', 'timestamp', 'integer', 'doublePrecision', 'jsonb', 'uuid', 'index']
2122
+ if (hasTranslations) pgCoreTypes.push('unique')
2123
+ const pgCoreImports = \`import { \${pgCoreTypes.join(', ')} } from 'drizzle-orm/pg-core'\\n\`
2124
+ imports.push(pgCoreImports)
2125
+
2126
+ const schemaFile = join(schemaDir, 'schema.ts')
2127
+ await writeFile(schemaFile, [...imports, ...schemas].join('\\n'))
2128
+
2129
+ console.log(\`\\nSchemas written to: \${schemaFile}\`)
2130
+ console.log('Run \\\`pnpm db:migrate:generate\\\` to create migrations')
2131
+ }
2132
+
2133
+ generateSchemas().catch(console.error)
2134
+ `),await n(a(i,`scripts/migrate.ts`),`/**
2135
+ * Run pending migrations
2136
+ */
2137
+
2138
+ import { createDbClient, runMigrations } from '@murumets-ee/db'
2139
+
2140
+ async function migrate() {
2141
+ console.log('Running migrations...')
2142
+
2143
+ try {
2144
+ if (!process.env.DATABASE_URL) {
2145
+ throw new Error('DATABASE_URL environment variable is required')
2146
+ }
2147
+
2148
+ const db = createDbClient({ url: process.env.DATABASE_URL })
2149
+ await runMigrations(db, import.meta.dirname + '/..')
2150
+
2151
+ console.log('Migrations completed successfully')
2152
+ process.exit(0)
2153
+ } catch (error) {
2154
+ console.error('Migration failed:', error)
2155
+ process.exit(1)
2156
+ }
2157
+ }
2158
+
2159
+ migrate()
2160
+ `),await n(a(i,`scripts/reset-db.ts`),`/**
2161
+ * Reset database (DROP all tables)
2162
+ * WARNING: Only for development
2163
+ */
2164
+
2165
+ import postgres from 'postgres'
2166
+
2167
+ async function resetDb() {
2168
+ const DATABASE_URL = process.env.DATABASE_URL
2169
+
2170
+ if (!DATABASE_URL) {
2171
+ throw new Error('DATABASE_URL not set')
2172
+ }
2173
+
2174
+ console.warn('WARNING: This will DROP ALL TABLES')
2175
+ console.log('Database:', DATABASE_URL.split('@')[1])
2176
+
2177
+ const sql = postgres(DATABASE_URL)
2178
+
2179
+ try {
2180
+ await sql\`
2181
+ DROP SCHEMA public CASCADE;
2182
+ CREATE SCHEMA public;
2183
+ GRANT ALL ON SCHEMA public TO PUBLIC;
2184
+ \`
2185
+
2186
+ console.log('Database reset complete')
2187
+ } finally {
2188
+ await sql.end()
2189
+ }
2190
+ }
2191
+
2192
+ resetDb().catch(console.error)
2193
+ `)}async function g(i,s){let{name:c}=s,l=a(i,`apps/admin`);await o(a(i,`apps`),{recursive:!0}),e(`pnpm create next-app@16 ${l} --typescript --tailwind --no-eslint --app --no-src-dir --turbopack --react-compiler --skip-install --import-alias "@/*"`),await t(l,[`app/page.tsx`,`app/page.module.css`,`app/fonts`,`README.md`,`pnpm-workspace.yaml`]),await r(a(l,`package.json`),{dependencies:{[`@${c}/config`]:`workspace:*`,"@murumets-ee/auth-ui":`^${f.myorgAuthUi}`,"better-auth":`^${f.betterAuth}`,"next-intl":`^${f.nextIntl}`,"next-themes":`^${f.nextThemes}`,"lucide-react":`^${f.lucideReact}`,"react-hook-form":`^${f.reactHookForm}`,"@hookform/resolvers":`^${f.hookformResolvers}`,zod:`^${f.zod}`},devDependencies:{"babel-plugin-react-compiler":f.babelReactCompiler}});let{appendToFile:u}=await import(`./utils-Bmw75lEa.mjs`).then(e=>e.a);await u(a(l,`.gitignore`),`
2194
+ # Environment
2195
+ .env*
2196
+ !.env.example
2197
+ `),await n(a(l,`next.config.ts`),`import type { NextConfig } from 'next'
2198
+ import createNextIntlPlugin from 'next-intl/plugin'
2199
+
2200
+ const withNextIntl = createNextIntlPlugin('./i18n/request.ts')
2201
+
2202
+ const nextConfig: NextConfig = {
2203
+ reactCompiler: true,
2204
+ transpilePackages: [
2205
+ '@${c}/config',
2206
+ '@murumets-ee/core',
2207
+ '@murumets-ee/entity',
2208
+ '@murumets-ee/db',
2209
+ '@murumets-ee/logging',
2210
+ '@murumets-ee/auth-ui',
2211
+ ],
2212
+ serverExternalPackages: ['drizzle-orm', 'postgres'],
2213
+ experimental: {
2214
+ serverActions: {
2215
+ bodySizeLimit: '2mb',
2216
+ },
2217
+ },
2218
+ }
2219
+
2220
+ export default withNextIntl(nextConfig)
2221
+ `),await n(a(l,`proxy.ts`),`import { NextRequest, NextResponse } from 'next/server'
2222
+ import { getSessionCookie } from 'better-auth/cookies'
2223
+ import createMiddleware from 'next-intl/middleware'
2224
+ import { routing } from './i18n/routing'
2225
+
2226
+ const intlMiddleware = createMiddleware(routing)
2227
+
2228
+ const protectedPaths = ['/setup']
2229
+
2230
+ export function proxy(request: NextRequest) {
2231
+ const { pathname } = request.nextUrl
2232
+
2233
+ const localePattern = new RegExp(\`^/(\${routing.locales.join('|')})\`)
2234
+ const pathWithoutLocale = pathname.replace(localePattern, '') || '/'
2235
+
2236
+ if (protectedPaths.some((p) => pathWithoutLocale.startsWith(p))) {
2237
+ const session = getSessionCookie(request)
2238
+ if (!session) {
2239
+ const locale = pathname.match(localePattern)?.[1] || routing.defaultLocale
2240
+ return NextResponse.redirect(new URL(\`/\${locale}/auth/sign-in\`, request.url))
2241
+ }
2242
+ }
2243
+
2244
+ return intlMiddleware(request)
2245
+ }
2246
+
2247
+ export const config = {
2248
+ matcher: '/((?!api|_next|_vercel|.*\\\\..*).*)',
2249
+ }
2250
+ `),await n(a(l,`i18n/routing.ts`),`import { defineRouting } from 'next-intl/routing'
2251
+
2252
+ export const routing = defineRouting({
2253
+ locales: ['en'],
2254
+ defaultLocale: 'en',
2255
+ })
2256
+ `),await n(a(l,`i18n/request.ts`),`import { getRequestConfig } from 'next-intl/server'
2257
+ import { hasLocale } from 'next-intl'
2258
+ import { routing } from './routing'
2259
+ import { getAuthMessages } from '@murumets-ee/auth-ui/i18n'
2260
+
2261
+ export default getRequestConfig(async ({ requestLocale }) => {
2262
+ const requested = await requestLocale
2263
+ const locale = hasLocale(routing.locales, requested)
2264
+ ? requested
2265
+ : routing.defaultLocale
2266
+
2267
+ const authMessages = await getAuthMessages(locale)
2268
+
2269
+ return {
2270
+ locale,
2271
+ messages: {
2272
+ ...authMessages,
2273
+ },
2274
+ }
2275
+ })
2276
+ `),await n(a(l,`app/globals.css`),`@import "tailwindcss";
2277
+ @source "../node_modules/@murumets-ee/auth-ui/dist";
2278
+
2279
+ @custom-variant dark (&:where(.dark, .dark *));
2280
+
2281
+ :root {
2282
+ --background: #ffffff;
2283
+ --foreground: #171717;
2284
+ }
2285
+
2286
+ @theme inline {
2287
+ --color-background: var(--background);
2288
+ --color-foreground: var(--foreground);
2289
+ --font-sans: var(--font-geist-sans);
2290
+ --font-mono: var(--font-geist-mono);
2291
+ }
2292
+
2293
+ .dark {
2294
+ --background: #0a0a0a;
2295
+ --foreground: #ededed;
2296
+ }
2297
+
2298
+ body {
2299
+ background: var(--background);
2300
+ color: var(--foreground);
2301
+ font-family: Arial, Helvetica, sans-serif;
2302
+ }
2303
+ `),await n(a(l,`app/theme-provider.tsx`),`'use client'
2304
+
2305
+ import { ThemeProvider as NextThemesProvider } from 'next-themes'
2306
+ import type { ReactNode } from 'react'
2307
+
2308
+ export function ThemeProvider({ children }: { children: ReactNode }) {
2309
+ return (
2310
+ <NextThemesProvider
2311
+ attribute="class"
2312
+ defaultTheme="system"
2313
+ enableSystem
2314
+ disableTransitionOnChange
2315
+ >
2316
+ {children}
2317
+ </NextThemesProvider>
2318
+ )
2319
+ }
2320
+ `),await n(a(l,`app/theme-toggle.tsx`),`'use client'
2321
+
2322
+ import { useTheme } from 'next-themes'
2323
+ import { useState, useEffect } from 'react'
2324
+ import { Sun, Moon } from 'lucide-react'
2325
+
2326
+ export function ThemeToggle() {
2327
+ const [mounted, setMounted] = useState(false)
2328
+ const { resolvedTheme, setTheme } = useTheme()
2329
+
2330
+ useEffect(() => { setMounted(true) }, [])
2331
+
2332
+ if (!mounted) {
2333
+ return <div className="h-8 w-8" />
2334
+ }
2335
+
2336
+ return (
2337
+ <button
2338
+ type="button"
2339
+ onClick={() => setTheme(resolvedTheme === 'dark' ? 'light' : 'dark')}
2340
+ className="rounded-md p-1.5 text-zinc-400 transition-colors hover:bg-zinc-100 hover:text-zinc-600 dark:hover:bg-zinc-800 dark:hover:text-zinc-200 cursor-pointer"
2341
+ aria-label={resolvedTheme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'}
2342
+ >
2343
+ {resolvedTheme === 'dark' ? <Sun className="h-5 w-5" /> : <Moon className="h-5 w-5" />}
2344
+ </button>
2345
+ )
2346
+ }
2347
+ `),await n(a(l,`app/nav-header.tsx`),`'use client'
2348
+
2349
+ import Link from 'next/link'
2350
+ import { usePathname } from 'next/navigation'
2351
+ import { ThemeToggle } from './theme-toggle'
2352
+
2353
+ const links = [
2354
+ { href: '/', label: 'Home' },
2355
+ { href: '/auth/sign-in', label: 'Sign In' },
2356
+ { href: '/setup', label: 'Setup' },
2357
+ ]
2358
+
2359
+ export function NavHeader() {
2360
+ const pathname = usePathname()
2361
+
2362
+ function isActive(href: string) {
2363
+ return href === '/' ? pathname === '/' : pathname.startsWith(href)
2364
+ }
2365
+
2366
+ const linkClass = (href: string) =>
2367
+ \`px-3 py-1.5 rounded-md text-sm transition-colors \${
2368
+ isActive(href)
2369
+ ? 'bg-zinc-200 text-zinc-900 dark:bg-zinc-800 dark:text-zinc-50'
2370
+ : 'text-zinc-500 hover:text-zinc-700 hover:bg-zinc-100 dark:text-zinc-400 dark:hover:text-zinc-200 dark:hover:bg-zinc-800/50'
2371
+ }\`
2372
+
2373
+ return (
2374
+ <header className="sticky top-0 z-50 backdrop-blur-md border-b bg-white/80 border-zinc-200 dark:bg-zinc-950/80 dark:border-zinc-800">
2375
+ <nav className="max-w-6xl mx-auto flex items-center gap-1 px-4 h-12">
2376
+ <span className="font-semibold text-sm text-zinc-700 dark:text-zinc-300 mr-3 select-none">
2377
+ ${c} Admin
2378
+ </span>
2379
+ {links.map(({ href, label }) => (
2380
+ <Link key={href} href={href} className={linkClass(href)}>
2381
+ {label}
2382
+ </Link>
2383
+ ))}
2384
+ <div className="ml-auto">
2385
+ <ThemeToggle />
2386
+ </div>
2387
+ </nav>
2388
+ </header>
2389
+ )
2390
+ }
2391
+ `),await n(a(l,`app/layout.tsx`),`import './globals.css'
2392
+
2393
+ export default function RootLayout({ children }: { children: React.ReactNode }) {
2394
+ return children
2395
+ }
2396
+ `),await n(a(l,`app/[locale]/layout.tsx`),`import type { Metadata } from 'next'
2397
+ import { Geist, Geist_Mono } from 'next/font/google'
2398
+ import { NextIntlClientProvider } from 'next-intl'
2399
+ import { getMessages } from 'next-intl/server'
2400
+ import { notFound } from 'next/navigation'
2401
+ import { routing } from '@/i18n/routing'
2402
+ import { ThemeProvider } from '../theme-provider'
2403
+ import { NavHeader } from '../nav-header'
2404
+
2405
+ const geistSans = Geist({
2406
+ variable: '--font-geist-sans',
2407
+ subsets: ['latin'],
2408
+ })
2409
+
2410
+ const geistMono = Geist_Mono({
2411
+ variable: '--font-geist-mono',
2412
+ subsets: ['latin'],
2413
+ })
2414
+
2415
+ export const metadata: Metadata = {
2416
+ title: '${c} Admin',
2417
+ description: 'Built with Lumi CMS Toolkit',
2418
+ }
2419
+
2420
+ export default async function LocaleLayout({
2421
+ children,
2422
+ params,
2423
+ }: {
2424
+ children: React.ReactNode
2425
+ params: Promise<{ locale: string }>
2426
+ }) {
2427
+ const { locale } = await params
2428
+ if (!routing.locales.includes(locale as any)) notFound()
2429
+
2430
+ const messages = await getMessages()
2431
+
2432
+ return (
2433
+ <html lang={locale} suppressHydrationWarning>
2434
+ <body className={\`\${geistSans.variable} \${geistMono.variable} antialiased\`}>
2435
+ <ThemeProvider>
2436
+ <NextIntlClientProvider locale={locale} messages={messages}>
2437
+ <NavHeader />
2438
+ {children}
2439
+ </NextIntlClientProvider>
2440
+ </ThemeProvider>
2441
+ </body>
2442
+ </html>
2443
+ )
2444
+ }
2445
+ `),await n(a(l,`app/[locale]/page.tsx`),`import { createQueryClient } from '@murumets-ee/core/clients'
2446
+ import { Article, Category } from '@${c}/config/entities'
2447
+ import { getToolkitApp } from '@${c}/config/app'
2448
+
2449
+ export default async function HomePage() {
2450
+ await getToolkitApp()
2451
+ const articles = createQueryClient(Article)
2452
+ const categories = createQueryClient(Category)
2453
+
2454
+ const [articleList, categoryList] = await Promise.all([
2455
+ articles.findMany({ limit: 10 }),
2456
+ categories.findMany({}),
2457
+ ])
2458
+
2459
+ return (
2460
+ <div className="min-h-screen p-8">
2461
+ <div className="max-w-4xl mx-auto">
2462
+ <h1 className="text-4xl font-bold mb-8">Welcome to ${c}</h1>
2463
+
2464
+ <section className="mb-12">
2465
+ <h2 className="text-2xl font-semibold mb-4">
2466
+ Categories ({categoryList.length})
2467
+ </h2>
2468
+ <div className="grid gap-4 md:grid-cols-2">
2469
+ {categoryList.map((cat) => (
2470
+ <div
2471
+ key={cat.id}
2472
+ className="border border-zinc-200 dark:border-zinc-800 rounded-lg p-4"
2473
+ >
2474
+ <h3 className="font-semibold text-lg">{cat.name}</h3>
2475
+ <p className="text-sm text-zinc-600 dark:text-zinc-400">
2476
+ {cat.description}
2477
+ </p>
2478
+ </div>
2479
+ ))}
2480
+ </div>
2481
+ </section>
2482
+
2483
+ <section>
2484
+ <h2 className="text-2xl font-semibold mb-4">
2485
+ Articles ({articleList.length})
2486
+ </h2>
2487
+ {articleList.length === 0 ? (
2488
+ <p className="text-zinc-500">No published articles yet.</p>
2489
+ ) : (
2490
+ <div className="space-y-4">
2491
+ {articleList.map((article) => (
2492
+ <div
2493
+ key={article.id}
2494
+ className="border border-zinc-200 dark:border-zinc-800 rounded-lg p-6"
2495
+ >
2496
+ <h3 className="text-xl font-bold">{article.title}</h3>
2497
+ <p className="text-zinc-600 dark:text-zinc-400 mt-2">
2498
+ {article.excerpt}
2499
+ </p>
2500
+ </div>
2501
+ ))}
2502
+ </div>
2503
+ )}
2504
+ </section>
2505
+ </div>
2506
+ </div>
2507
+ )
2508
+ }
2509
+ `),await n(a(l,`app/api/auth/[...all]/route.ts`),`import { toNextJsHandler } from 'better-auth/next-js'
2510
+ import { getAuthInstance } from '@${c}/config/auth'
2511
+
2512
+ let _handler: ReturnType<typeof toNextJsHandler> | null = null
2513
+
2514
+ async function handler() {
2515
+ if (!_handler) {
2516
+ const auth = await getAuthInstance()
2517
+ _handler = toNextJsHandler(auth)
2518
+ }
2519
+ return _handler
2520
+ }
2521
+
2522
+ export async function GET(req: Request) {
2523
+ return (await handler()).GET(req)
2524
+ }
2525
+
2526
+ export async function POST(req: Request) {
2527
+ return (await handler()).POST(req)
2528
+ }
2529
+ `),await n(a(l,`app/[locale]/auth/layout.tsx`),`import { AuthProviders } from './providers'
2530
+ import type { ReactNode } from 'react'
2531
+
2532
+ export default function AuthLayout({ children }: { children: ReactNode }) {
2533
+ return (
2534
+ <AuthProviders>
2535
+ <div className="flex min-h-[calc(100vh-3rem)] items-center justify-center px-4">
2536
+ {children}
2537
+ </div>
2538
+ </AuthProviders>
2539
+ )
2540
+ }
2541
+ `),await n(a(l,`app/[locale]/auth/providers.tsx`),`'use client'
2542
+
2543
+ import { AuthUIProvider } from '@murumets-ee/auth-ui'
2544
+ import { authClient } from '@${c}/config/auth-client'
2545
+ import Link from 'next/link'
2546
+ import { useRouter } from 'next/navigation'
2547
+ import { useLocale } from 'next-intl'
2548
+ import type { ReactNode } from 'react'
2549
+
2550
+ export function AuthProviders({ children }: { children: ReactNode }) {
2551
+ const router = useRouter()
2552
+ const locale = useLocale()
2553
+
2554
+ return (
2555
+ <AuthUIProvider
2556
+ authClient={authClient as never}
2557
+ basePath="/auth"
2558
+ redirectTo="/"
2559
+ Link={Link}
2560
+ navigate={(url) => router.push(url)}
2561
+ resetPasswordUrl={\`/\${locale}/auth/reset-password\`}
2562
+ >
2563
+ {children}
2564
+ </AuthUIProvider>
2565
+ )
2566
+ }
2567
+ `),await n(a(l,`app/[locale]/auth/sign-in/page.tsx`),`import { SignInForm } from '@murumets-ee/auth-ui'
2568
+
2569
+ export default function SignInPage() {
2570
+ return <SignInForm />
2571
+ }
2572
+ `),await n(a(l,`app/[locale]/auth/sign-up/page.tsx`),`import { SignUpForm } from '@murumets-ee/auth-ui'
2573
+
2574
+ export default function SignUpPage() {
2575
+ return <SignUpForm />
2576
+ }
2577
+ `),await n(a(l,`app/[locale]/auth/forgot-password/page.tsx`),`import { ForgotPasswordForm } from '@murumets-ee/auth-ui'
2578
+
2579
+ export default function ForgotPasswordPage() {
2580
+ return <ForgotPasswordForm />
2581
+ }
2582
+ `),await n(a(l,`app/[locale]/auth/reset-password/page.tsx`),`import { Suspense } from 'react'
2583
+ import { ResetPasswordContent } from './content'
2584
+
2585
+ export default function ResetPasswordPage() {
2586
+ return (
2587
+ <Suspense>
2588
+ <ResetPasswordContent />
2589
+ </Suspense>
2590
+ )
2591
+ }
2592
+ `),await n(a(l,`app/[locale]/auth/reset-password/content.tsx`),`'use client'
2593
+
2594
+ import { useSearchParams } from 'next/navigation'
2595
+ import { ResetPasswordForm } from '@murumets-ee/auth-ui'
2596
+
2597
+ export function ResetPasswordContent() {
2598
+ const searchParams = useSearchParams()
2599
+ const token = searchParams.get('token')
2600
+
2601
+ if (!token) {
2602
+ return (
2603
+ <div className="text-center">
2604
+ <h1 className="text-2xl font-bold text-zinc-900 dark:text-zinc-50">
2605
+ Invalid or expired link
2606
+ </h1>
2607
+ <p className="mt-2 text-zinc-500">
2608
+ Please request a new password reset.
2609
+ </p>
2610
+ </div>
2611
+ )
2612
+ }
2613
+
2614
+ return <ResetPasswordForm token={token} />
2615
+ }
2616
+ `),await n(a(l,`app/[locale]/setup/page.tsx`),`import { redirect } from 'next/navigation'
2617
+ import { sql } from 'drizzle-orm'
2618
+ import { getToolkitApp } from '@${c}/config/app'
2619
+ import { SetupForm } from './form'
2620
+
2621
+ export default async function SetupPage() {
2622
+ const app = await getToolkitApp()
2623
+ const result = await app.db.readOnly.execute<{ count: string }>(
2624
+ sql\`SELECT COUNT(*)::text as count FROM "user"\`,
2625
+ )
2626
+
2627
+ if (Number(result[0]?.count) > 0) {
2628
+ redirect('/')
2629
+ }
2630
+
2631
+ return (
2632
+ <div className="max-w-md mx-auto p-8">
2633
+ <h1 className="text-2xl font-bold mb-2">Create Admin</h1>
2634
+ <p className="text-sm text-zinc-500 dark:text-zinc-400 mb-6">
2635
+ No users found. Create the first admin account.
2636
+ </p>
2637
+ <SetupForm />
2638
+ </div>
2639
+ )
2640
+ }
2641
+ `),await n(a(l,`app/[locale]/setup/form.tsx`),`'use client'
2642
+
2643
+ import { useState } from 'react'
2644
+ import { createFirstAdmin } from './actions'
2645
+
2646
+ export function SetupForm() {
2647
+ const [result, setResult] = useState<{ ok?: boolean; error?: string; email?: string } | null>(null)
2648
+ const [loading, setLoading] = useState(false)
2649
+
2650
+ async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
2651
+ e.preventDefault()
2652
+ setLoading(true)
2653
+ setResult(null)
2654
+ const res = await createFirstAdmin(new FormData(e.currentTarget))
2655
+ setResult(res)
2656
+ setLoading(false)
2657
+ }
2658
+
2659
+ if (result?.ok) {
2660
+ return (
2661
+ <div className="space-y-2">
2662
+ <p className="text-green-600 dark:text-green-400">Admin created: {result.email}</p>
2663
+ <a href="/auth/sign-in" className="text-blue-600 dark:text-blue-400 hover:underline">
2664
+ Sign in &rarr;
2665
+ </a>
2666
+ </div>
2667
+ )
2668
+ }
2669
+
2670
+ return (
2671
+ <form onSubmit={handleSubmit} className="flex flex-col gap-4">
2672
+ <label className="text-sm font-medium">
2673
+ Name
2674
+ <input
2675
+ name="name"
2676
+ required
2677
+ className="mt-1 block w-full px-3 py-2 bg-zinc-100 dark:bg-zinc-900 border border-zinc-300 dark:border-zinc-700 rounded-md text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
2678
+ />
2679
+ </label>
2680
+ <label className="text-sm font-medium">
2681
+ Email
2682
+ <input
2683
+ name="email"
2684
+ type="email"
2685
+ required
2686
+ className="mt-1 block w-full px-3 py-2 bg-zinc-100 dark:bg-zinc-900 border border-zinc-300 dark:border-zinc-700 rounded-md text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
2687
+ />
2688
+ </label>
2689
+ <label className="text-sm font-medium">
2690
+ Password (min 8 chars)
2691
+ <input
2692
+ name="password"
2693
+ type="password"
2694
+ required
2695
+ minLength={8}
2696
+ className="mt-1 block w-full px-3 py-2 bg-zinc-100 dark:bg-zinc-900 border border-zinc-300 dark:border-zinc-700 rounded-md text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
2697
+ />
2698
+ </label>
2699
+
2700
+ {result?.error && <p className="text-red-600 dark:text-red-400 text-sm">{result.error}</p>}
2701
+
2702
+ <button
2703
+ type="submit"
2704
+ disabled={loading}
2705
+ className="px-4 py-2 text-sm rounded-md bg-blue-600 text-white hover:bg-blue-500 disabled:opacity-50 transition-colors"
2706
+ >
2707
+ {loading ? 'Creating...' : 'Create Admin'}
2708
+ </button>
2709
+ </form>
2710
+ )
2711
+ }
2712
+ `),await n(a(l,`app/[locale]/setup/actions.ts`),`'use server'
2713
+
2714
+ import { sql } from 'drizzle-orm'
2715
+ import { getToolkitApp } from '@${c}/config/app'
2716
+ import { getAuth } from '@murumets-ee/auth'
2717
+
2718
+ export async function createFirstAdmin(formData: FormData) {
2719
+ const email = formData.get('email') as string
2720
+ const password = formData.get('password') as string
2721
+ const name = formData.get('name') as string
2722
+
2723
+ if (!email || !password || !name) {
2724
+ return { error: 'All fields are required' }
2725
+ }
2726
+
2727
+ if (password.length < 8) {
2728
+ return { error: 'Password must be at least 8 characters' }
2729
+ }
2730
+
2731
+ const app = await getToolkitApp()
2732
+
2733
+ const canCreate = await app.db.readWrite.transaction(async (tx) => {
2734
+ await tx.execute(sql\`SELECT pg_advisory_xact_lock(1)\`)
2735
+
2736
+ const result = await tx.execute<{ count: string }>(
2737
+ sql\`SELECT COUNT(*)::text as count FROM "user"\`,
2738
+ )
2739
+ return Number(result[0]?.count) === 0
2740
+ })
2741
+
2742
+ if (!canCreate) {
2743
+ return { error: 'Admin user already exists. Setup is complete.' }
2744
+ }
2745
+
2746
+ const auth = getAuth()
2747
+
2748
+ const adminUser = await auth.api.signUpEmail({
2749
+ body: { email, password, name },
2750
+ })
2751
+
2752
+ await app.db.readWrite.execute(
2753
+ sql\`UPDATE "user" SET role = 'admin' WHERE id = \${adminUser.user.id}\`,
2754
+ )
2755
+
2756
+ return { ok: true, email: adminUser.user.email }
2757
+ }
2758
+ `)}async function _(i,o){let{name:s}=o,c=a(i,`apps/web`);e(`pnpm create next-app@16 ${c} --typescript --tailwind --no-eslint --app --no-src-dir --turbopack --react-compiler --skip-install --import-alias "@/*"`),await t(c,[`app/page.tsx`,`app/page.module.css`,`app/fonts`,`README.md`,`pnpm-workspace.yaml`]),await r(a(c,`package.json`),{dependencies:{[`@${s}/config`]:`workspace:*`,"@murumets-ee/core":`^${f.myorgCore}`,"@murumets-ee/auth-ui":`^${f.myorgAuthUi}`,"next-intl":`^${f.nextIntl}`,"next-themes":`^${f.nextThemes}`,"lucide-react":`^${f.lucideReact}`},devDependencies:{"babel-plugin-react-compiler":f.babelReactCompiler}});let{appendToFile:l}=await import(`./utils-Bmw75lEa.mjs`).then(e=>e.a);await l(a(c,`.gitignore`),`
2759
+ # Environment
2760
+ .env*
2761
+ !.env.example
2762
+ `),await n(a(c,`next.config.ts`),`import type { NextConfig } from 'next'
2763
+ import createNextIntlPlugin from 'next-intl/plugin'
2764
+
2765
+ const withNextIntl = createNextIntlPlugin('./i18n/request.ts')
2766
+
2767
+ const nextConfig: NextConfig = {
2768
+ reactCompiler: true,
2769
+ transpilePackages: [
2770
+ '@${s}/config',
2771
+ '@murumets-ee/core',
2772
+ '@murumets-ee/entity',
2773
+ '@murumets-ee/db',
2774
+ '@murumets-ee/logging',
2775
+ '@murumets-ee/auth-ui',
2776
+ ],
2777
+ serverExternalPackages: ['drizzle-orm', 'postgres'],
2778
+ }
2779
+
2780
+ export default withNextIntl(nextConfig)
2781
+ `),await n(a(c,`proxy.ts`),`import createMiddleware from 'next-intl/middleware'
2782
+ import { routing } from './i18n/routing'
2783
+
2784
+ export default createMiddleware(routing)
2785
+
2786
+ export const config = {
2787
+ matcher: '/((?!api|_next|_vercel|.*\\\\..*).*)',
2788
+ }
2789
+ `),await n(a(c,`i18n/routing.ts`),`import { defineRouting } from 'next-intl/routing'
2790
+
2791
+ export const routing = defineRouting({
2792
+ locales: ['en'],
2793
+ defaultLocale: 'en',
2794
+ })
2795
+ `),await n(a(c,`i18n/request.ts`),`import { getRequestConfig } from 'next-intl/server'
2796
+ import { hasLocale } from 'next-intl'
2797
+ import { routing } from './routing'
2798
+ import { getAuthMessages } from '@murumets-ee/auth-ui/i18n'
2799
+
2800
+ export default getRequestConfig(async ({ requestLocale }) => {
2801
+ const requested = await requestLocale
2802
+ const locale = hasLocale(routing.locales, requested)
2803
+ ? requested
2804
+ : routing.defaultLocale
2805
+
2806
+ const authMessages = await getAuthMessages(locale)
2807
+
2808
+ return {
2809
+ locale,
2810
+ messages: {
2811
+ ...authMessages,
2812
+ },
2813
+ }
2814
+ })
2815
+ `),await n(a(c,`app/globals.css`),`@import "tailwindcss";
2816
+ @source "../node_modules/@murumets-ee/auth-ui/dist";
2817
+
2818
+ @custom-variant dark (&:where(.dark, .dark *));
2819
+
2820
+ :root {
2821
+ --background: #ffffff;
2822
+ --foreground: #171717;
2823
+ }
2824
+
2825
+ @theme inline {
2826
+ --color-background: var(--background);
2827
+ --color-foreground: var(--foreground);
2828
+ --font-sans: var(--font-geist-sans);
2829
+ --font-mono: var(--font-geist-mono);
2830
+ }
2831
+
2832
+ .dark {
2833
+ --background: #0a0a0a;
2834
+ --foreground: #ededed;
2835
+ }
2836
+
2837
+ body {
2838
+ background: var(--background);
2839
+ color: var(--foreground);
2840
+ font-family: Arial, Helvetica, sans-serif;
2841
+ }
2842
+ `),await n(a(c,`app/theme-provider.tsx`),`'use client'
2843
+
2844
+ import { ThemeProvider as NextThemesProvider } from 'next-themes'
2845
+ import type { ReactNode } from 'react'
2846
+
2847
+ export function ThemeProvider({ children }: { children: ReactNode }) {
2848
+ return (
2849
+ <NextThemesProvider
2850
+ attribute="class"
2851
+ defaultTheme="system"
2852
+ enableSystem
2853
+ disableTransitionOnChange
2854
+ >
2855
+ {children}
2856
+ </NextThemesProvider>
2857
+ )
2858
+ }
2859
+ `),await n(a(c,`app/theme-toggle.tsx`),`'use client'
2860
+
2861
+ import { useTheme } from 'next-themes'
2862
+ import { useState, useEffect } from 'react'
2863
+ import { Sun, Moon } from 'lucide-react'
2864
+
2865
+ export function ThemeToggle() {
2866
+ const [mounted, setMounted] = useState(false)
2867
+ const { resolvedTheme, setTheme } = useTheme()
2868
+
2869
+ useEffect(() => { setMounted(true) }, [])
2870
+
2871
+ if (!mounted) {
2872
+ return <div className="h-8 w-8" />
2873
+ }
2874
+
2875
+ return (
2876
+ <button
2877
+ type="button"
2878
+ onClick={() => setTheme(resolvedTheme === 'dark' ? 'light' : 'dark')}
2879
+ className="rounded-md p-1.5 text-zinc-400 transition-colors hover:bg-zinc-100 hover:text-zinc-600 dark:hover:bg-zinc-800 dark:hover:text-zinc-200 cursor-pointer"
2880
+ aria-label={resolvedTheme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'}
2881
+ >
2882
+ {resolvedTheme === 'dark' ? <Sun className="h-5 w-5" /> : <Moon className="h-5 w-5" />}
2883
+ </button>
2884
+ )
2885
+ }
2886
+ `),await n(a(c,`app/nav-header.tsx`),`'use client'
2887
+
2888
+ import Link from 'next/link'
2889
+ import { usePathname } from 'next/navigation'
2890
+ import { ThemeToggle } from './theme-toggle'
2891
+
2892
+ const links = [
2893
+ { href: '/', label: 'Home' },
2894
+ ]
2895
+
2896
+ export function NavHeader() {
2897
+ const pathname = usePathname()
2898
+
2899
+ function isActive(href: string) {
2900
+ return href === '/' ? pathname === '/' : pathname.startsWith(href)
2901
+ }
2902
+
2903
+ const linkClass = (href: string) =>
2904
+ \`px-3 py-1.5 rounded-md text-sm transition-colors \${
2905
+ isActive(href)
2906
+ ? 'bg-zinc-200 text-zinc-900 dark:bg-zinc-800 dark:text-zinc-50'
2907
+ : 'text-zinc-500 hover:text-zinc-700 hover:bg-zinc-100 dark:text-zinc-400 dark:hover:text-zinc-200 dark:hover:bg-zinc-800/50'
2908
+ }\`
2909
+
2910
+ return (
2911
+ <header className="sticky top-0 z-50 backdrop-blur-md border-b bg-white/80 border-zinc-200 dark:bg-zinc-950/80 dark:border-zinc-800">
2912
+ <nav className="max-w-6xl mx-auto flex items-center gap-1 px-4 h-12">
2913
+ <span className="font-semibold text-sm text-zinc-700 dark:text-zinc-300 mr-3 select-none">
2914
+ ${s}
2915
+ </span>
2916
+ {links.map(({ href, label }) => (
2917
+ <Link key={href} href={href} className={linkClass(href)}>
2918
+ {label}
2919
+ </Link>
2920
+ ))}
2921
+ <div className="ml-auto">
2922
+ <ThemeToggle />
2923
+ </div>
2924
+ </nav>
2925
+ </header>
2926
+ )
2927
+ }
2928
+ `),await n(a(c,`app/layout.tsx`),`import './globals.css'
2929
+
2930
+ export default function RootLayout({ children }: { children: React.ReactNode }) {
2931
+ return children
2932
+ }
2933
+ `),await n(a(c,`app/[locale]/layout.tsx`),`import type { Metadata } from 'next'
2934
+ import { Geist, Geist_Mono } from 'next/font/google'
2935
+ import { NextIntlClientProvider } from 'next-intl'
2936
+ import { getMessages } from 'next-intl/server'
2937
+ import { notFound } from 'next/navigation'
2938
+ import { routing } from '@/i18n/routing'
2939
+ import { ThemeProvider } from '../theme-provider'
2940
+ import { NavHeader } from '../nav-header'
2941
+
2942
+ const geistSans = Geist({
2943
+ variable: '--font-geist-sans',
2944
+ subsets: ['latin'],
2945
+ })
2946
+
2947
+ const geistMono = Geist_Mono({
2948
+ variable: '--font-geist-mono',
2949
+ subsets: ['latin'],
2950
+ })
2951
+
2952
+ export const metadata: Metadata = {
2953
+ title: '${s}',
2954
+ description: 'Built with Lumi CMS Toolkit',
2955
+ }
2956
+
2957
+ export default async function LocaleLayout({
2958
+ children,
2959
+ params,
2960
+ }: {
2961
+ children: React.ReactNode
2962
+ params: Promise<{ locale: string }>
2963
+ }) {
2964
+ const { locale } = await params
2965
+ if (!routing.locales.includes(locale as any)) notFound()
2966
+
2967
+ const messages = await getMessages()
2968
+
2969
+ return (
2970
+ <html lang={locale} suppressHydrationWarning>
2971
+ <body className={\`\${geistSans.variable} \${geistMono.variable} antialiased\`}>
2972
+ <ThemeProvider>
2973
+ <NextIntlClientProvider locale={locale} messages={messages}>
2974
+ <NavHeader />
2975
+ {children}
2976
+ </NextIntlClientProvider>
2977
+ </ThemeProvider>
2978
+ </body>
2979
+ </html>
2980
+ )
2981
+ }
2982
+ `),await n(a(c,`app/[locale]/page.tsx`),`import { createQueryClient } from '@murumets-ee/core/clients'
2983
+ import { Article, Category } from '@${s}/config/entities'
2984
+ import { getToolkitApp } from '@${s}/config/app'
2985
+
2986
+ export default async function HomePage() {
2987
+ await getToolkitApp()
2988
+ const articles = createQueryClient(Article)
2989
+ const categories = createQueryClient(Category)
2990
+
2991
+ const [articleList, categoryList] = await Promise.all([
2992
+ articles.findMany({ limit: 10 }),
2993
+ categories.findMany({}),
2994
+ ])
2995
+
2996
+ return (
2997
+ <div className="min-h-screen p-8">
2998
+ <div className="max-w-4xl mx-auto">
2999
+ <h1 className="text-4xl font-bold mb-8">Welcome to ${s}</h1>
3000
+
3001
+ <section className="mb-12">
3002
+ <h2 className="text-2xl font-semibold mb-4">
3003
+ Categories ({categoryList.length})
3004
+ </h2>
3005
+ <div className="grid gap-4 md:grid-cols-2">
3006
+ {categoryList.map((cat) => (
3007
+ <div
3008
+ key={cat.id}
3009
+ className="border border-zinc-200 dark:border-zinc-800 rounded-lg p-4"
3010
+ >
3011
+ <h3 className="font-semibold text-lg">{cat.name}</h3>
3012
+ <p className="text-sm text-zinc-600 dark:text-zinc-400">
3013
+ {cat.description}
3014
+ </p>
3015
+ </div>
3016
+ ))}
3017
+ </div>
3018
+ </section>
3019
+
3020
+ <section>
3021
+ <h2 className="text-2xl font-semibold mb-4">
3022
+ Articles ({articleList.length})
3023
+ </h2>
3024
+ {articleList.length === 0 ? (
3025
+ <p className="text-zinc-500">No published articles yet.</p>
3026
+ ) : (
3027
+ <div className="space-y-4">
3028
+ {articleList.map((article) => (
3029
+ <div
3030
+ key={article.id}
3031
+ className="border border-zinc-200 dark:border-zinc-800 rounded-lg p-6"
3032
+ >
3033
+ <h3 className="text-xl font-bold">{article.title}</h3>
3034
+ <p className="text-zinc-600 dark:text-zinc-400 mt-2">
3035
+ {article.excerpt}
3036
+ </p>
3037
+ </div>
3038
+ ))}
3039
+ </div>
3040
+ )}
3041
+ </section>
3042
+ </div>
3043
+ </div>
3044
+ )
3045
+ }
3046
+ `)}async function v(e,t){let{name:r}=t;await n(a(e,`next.config.ts`),`import type { NextConfig } from 'next'
3047
+ import createNextIntlPlugin from 'next-intl/plugin'
3048
+
3049
+ const withNextIntl = createNextIntlPlugin('./i18n/request.ts')
3050
+
3051
+ const nextConfig: NextConfig = {
3052
+ output: 'standalone',
3053
+ reactCompiler: true,
3054
+ transpilePackages: [
3055
+ '@murumets-ee/core', '@murumets-ee/entity', '@murumets-ee/db',
3056
+ '@murumets-ee/logging', '@murumets-ee/auth', '@murumets-ee/auth-ui',
3057
+ '@murumets-ee/admin-ui', '@murumets-ee/content', '@murumets-ee/settings',
3058
+ '@murumets-ee/storage', '@murumets-ee/media', '@murumets-ee/taxonomy',
3059
+ '@murumets-ee/queue', '@murumets-ee/mail', '@murumets-ee/ticketing',
3060
+ '@murumets-ee/ticketing-ui', '@murumets-ee/tokens', '@murumets-ee/ui',
3061
+ ],
3062
+ serverExternalPackages: ['drizzle-orm', 'postgres', 'pino', 'file-type'],
3063
+ experimental: {
3064
+ serverActions: {
3065
+ bodySizeLimit: '2mb',
3066
+ },
3067
+ },
3068
+ }
3069
+
3070
+ export default withNextIntl(nextConfig)
3071
+ `),await n(a(e,`proxy.ts`),`import { NextRequest, NextResponse } from 'next/server'
3072
+ import { getSessionCookie } from 'better-auth/cookies'
3073
+ import createMiddleware from 'next-intl/middleware'
3074
+ import { routing } from './i18n/routing'
3075
+
3076
+ const intlMiddleware = createMiddleware(routing)
3077
+
3078
+ const protectedPaths = ['/setup']
3079
+
3080
+ export function proxy(request: NextRequest) {
3081
+ const { pathname } = request.nextUrl
3082
+
3083
+ // Strip locale prefix to check actual path
3084
+ const localePattern = new RegExp(\`^/(\${routing.locales.join('|')})\`)
3085
+ const pathWithoutLocale = pathname.replace(localePattern, '') || '/'
3086
+
3087
+ // Auth check for protected paths
3088
+ if (protectedPaths.some((p) => pathWithoutLocale.startsWith(p))) {
3089
+ const session = getSessionCookie(request)
3090
+ if (!session) {
3091
+ const locale = pathname.match(localePattern)?.[1] || routing.defaultLocale
3092
+ return NextResponse.redirect(new URL(\`/\${locale}/auth/sign-in\`, request.url))
3093
+ }
3094
+ }
3095
+
3096
+ // Locale routing
3097
+ return intlMiddleware(request)
3098
+ }
3099
+
3100
+ export const config = {
3101
+ matcher: '/((?!api|_next|_vercel|.*\\\\..*).*)',
3102
+ }
3103
+ `),await n(a(e,`app/layout.tsx`),`import './globals.css'
3104
+
3105
+ export default function RootLayout({ children }: { children: React.ReactNode }) {
3106
+ return children
3107
+ }
3108
+ `),await n(a(e,`app/[locale]/layout.tsx`),`import type { Metadata } from 'next'
3109
+ import { Geist, Geist_Mono } from 'next/font/google'
3110
+ import { NextIntlClientProvider } from 'next-intl'
3111
+ import { getMessages } from 'next-intl/server'
3112
+ import { notFound } from 'next/navigation'
3113
+ import { routing } from '@/i18n/routing'
3114
+ import { ThemeProvider } from '../theme-provider'
3115
+ import { NavHeader } from '../nav-header'
3116
+
3117
+ const geistSans = Geist({
3118
+ variable: '--font-geist-sans',
3119
+ subsets: ['latin'],
3120
+ })
3121
+
3122
+ const geistMono = Geist_Mono({
3123
+ variable: '--font-geist-mono',
3124
+ subsets: ['latin'],
3125
+ })
3126
+
3127
+ export const metadata: Metadata = {
3128
+ title: '${r}',
3129
+ description: 'Built with Lumi CMS Toolkit',
3130
+ }
3131
+
3132
+ export default async function LocaleLayout({
3133
+ children,
3134
+ params,
3135
+ }: {
3136
+ children: React.ReactNode
3137
+ params: Promise<{ locale: string }>
3138
+ }) {
3139
+ const { locale } = await params
3140
+ if (!routing.locales.includes(locale as any)) notFound()
3141
+
3142
+ const messages = await getMessages()
3143
+
3144
+ return (
3145
+ <html lang={locale} suppressHydrationWarning>
3146
+ <body className={\`\${geistSans.variable} \${geistMono.variable} antialiased\`}>
3147
+ <ThemeProvider>
3148
+ <NextIntlClientProvider locale={locale} messages={messages}>
3149
+ <NavHeader />
3150
+ {children}
3151
+ </NextIntlClientProvider>
3152
+ </ThemeProvider>
3153
+ </body>
3154
+ </html>
3155
+ )
3156
+ }
3157
+ `),await n(a(e,`app/[locale]/page.tsx`),`import { createQueryClient } from '@murumets-ee/core/clients'
3158
+ import { Article, Category } from '@/entities'
3159
+ import { getToolkitApp } from '@/lib/app'
3160
+
3161
+ export default async function HomePage() {
3162
+ await getToolkitApp()
3163
+ const articles = createQueryClient(Article)
3164
+ const categories = createQueryClient(Category)
3165
+
3166
+ const [articleList, categoryList] = await Promise.all([
3167
+ articles.findMany({ limit: 10 }),
3168
+ categories.findMany({}),
3169
+ ])
3170
+
3171
+ return (
3172
+ <div className="min-h-screen p-8">
3173
+ <div className="max-w-4xl mx-auto">
3174
+ <h1 className="text-4xl font-bold mb-8">Welcome to ${r}</h1>
3175
+
3176
+ <section className="mb-12">
3177
+ <h2 className="text-2xl font-semibold mb-4">
3178
+ Categories ({categoryList.length})
3179
+ </h2>
3180
+ <div className="grid gap-4 md:grid-cols-2">
3181
+ {categoryList.map((cat) => (
3182
+ <div
3183
+ key={cat.id}
3184
+ className="border border-zinc-200 dark:border-zinc-800 rounded-lg p-4"
3185
+ >
3186
+ <h3 className="font-semibold text-lg">{cat.name}</h3>
3187
+ <p className="text-sm text-zinc-600 dark:text-zinc-400">
3188
+ {cat.description}
3189
+ </p>
3190
+ </div>
3191
+ ))}
3192
+ </div>
3193
+ </section>
3194
+
3195
+ <section>
3196
+ <h2 className="text-2xl font-semibold mb-4">
3197
+ Articles ({articleList.length})
3198
+ </h2>
3199
+ {articleList.length === 0 ? (
3200
+ <p className="text-zinc-500">No published articles yet.</p>
3201
+ ) : (
3202
+ <div className="space-y-4">
3203
+ {articleList.map((article) => (
3204
+ <div
3205
+ key={article.id}
3206
+ className="border border-zinc-200 dark:border-zinc-800 rounded-lg p-6"
3207
+ >
3208
+ <h3 className="text-xl font-bold">{article.title}</h3>
3209
+ <p className="text-zinc-600 dark:text-zinc-400 mt-2">
3210
+ {article.excerpt}
3211
+ </p>
3212
+ </div>
3213
+ ))}
3214
+ </div>
3215
+ )}
3216
+ </section>
3217
+ </div>
3218
+ </div>
3219
+ )
3220
+ }
3221
+ `)}async function y(e,t){await n(a(e,`scripts/generate-schema.ts`),`import { execSync } from 'node:child_process'
3222
+ execSync('npx @murumets-ee/cli generate', { stdio: 'inherit', cwd: import.meta.dirname + '/..' })
3223
+ `),await n(a(e,`scripts/migrate.ts`),`import { execSync } from 'node:child_process'
3224
+ execSync('npx @murumets-ee/cli migrate', { stdio: 'inherit', cwd: import.meta.dirname + '/..' })
3225
+ `),await n(a(e,`scripts/reset-db.ts`),`import { execSync } from 'node:child_process'
3226
+ execSync('npx @murumets-ee/cli reset --force', { stdio: 'inherit', cwd: import.meta.dirname + '/..' })
3227
+ `),await n(a(e,`scripts/worker.ts`),`/**
3228
+ * Standalone queue worker process.
3229
+ *
3230
+ * Run separately from the Next.js web server:
3231
+ * pnpm worker (or: tsx --env-file=.env scripts/worker.ts)
3232
+ *
3233
+ * The web server should set QUEUE_WORKER=false so it only enqueues jobs.
3234
+ * This process handles job execution.
3235
+ */
3236
+
3237
+ import { createApp, setApp } from '@murumets-ee/core'
3238
+ import config from '../toolkit.config'
3239
+
3240
+ process.env.QUEUE_WORKER = 'true'
3241
+
3242
+ const app = await createApp(config)
3243
+ setApp(app)
3244
+
3245
+ app.logger.info('Queue worker process running. Press Ctrl+C to stop.')
3246
+
3247
+ const shutdown = async () => {
3248
+ app.logger.info('Shutting down queue worker...')
3249
+
3250
+ const worker = (globalThis as Record<symbol, unknown>)[
3251
+ Symbol.for('@murumets-ee/queue:worker')
3252
+ ] as { stop: () => Promise<void> } | undefined
3253
+
3254
+ if (worker) {
3255
+ await worker.stop()
3256
+ }
3257
+
3258
+ process.exit(0)
3259
+ }
3260
+
3261
+ process.on('SIGINT', shutdown)
3262
+ process.on('SIGTERM', shutdown)
3263
+ `)}async function b(e,t){let{name:r}=t;await n(a(e,`app/globals.css`),`@import "tailwindcss";
3264
+ @source "../node_modules/@murumets-ee/auth-ui/dist";
3265
+
3266
+ @custom-variant dark (&:where(.dark, .dark *));
3267
+
3268
+ :root {
3269
+ --background: #ffffff;
3270
+ --foreground: #171717;
3271
+ }
3272
+
3273
+ @theme inline {
3274
+ --color-background: var(--background);
3275
+ --color-foreground: var(--foreground);
3276
+ --font-sans: var(--font-geist-sans);
3277
+ --font-mono: var(--font-geist-mono);
3278
+ }
3279
+
3280
+ .dark {
3281
+ --background: #0a0a0a;
3282
+ --foreground: #ededed;
3283
+ }
3284
+
3285
+ body {
3286
+ background: var(--background);
3287
+ color: var(--foreground);
3288
+ font-family: Arial, Helvetica, sans-serif;
3289
+ }
3290
+ `),await n(a(e,`app/theme-provider.tsx`),`'use client'
3291
+
3292
+ import { ThemeProvider as NextThemesProvider } from 'next-themes'
3293
+ import type { ReactNode } from 'react'
3294
+
3295
+ export function ThemeProvider({ children }: { children: ReactNode }) {
3296
+ return (
3297
+ <NextThemesProvider
3298
+ attribute="class"
3299
+ defaultTheme="system"
3300
+ enableSystem
3301
+ disableTransitionOnChange
3302
+ >
3303
+ {children}
3304
+ </NextThemesProvider>
3305
+ )
3306
+ }
3307
+ `),await n(a(e,`app/theme-toggle.tsx`),`'use client'
3308
+
3309
+ import { useTheme } from 'next-themes'
3310
+ import { useState, useEffect } from 'react'
3311
+ import { Sun, Moon } from 'lucide-react'
3312
+
3313
+ export function ThemeToggle() {
3314
+ const [mounted, setMounted] = useState(false)
3315
+ const { resolvedTheme, setTheme } = useTheme()
3316
+
3317
+ useEffect(() => { setMounted(true) }, [])
3318
+
3319
+ if (!mounted) {
3320
+ return <div className="h-8 w-8" />
3321
+ }
3322
+
3323
+ return (
3324
+ <button
3325
+ type="button"
3326
+ onClick={() => setTheme(resolvedTheme === 'dark' ? 'light' : 'dark')}
3327
+ className="rounded-md p-1.5 text-zinc-400 transition-colors hover:bg-zinc-100 hover:text-zinc-600 dark:hover:bg-zinc-800 dark:hover:text-zinc-200 cursor-pointer"
3328
+ aria-label={resolvedTheme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'}
3329
+ >
3330
+ {resolvedTheme === 'dark' ? <Sun className="h-5 w-5" /> : <Moon className="h-5 w-5" />}
3331
+ </button>
3332
+ )
3333
+ }
3334
+ `),await n(a(e,`app/nav-header.tsx`),`'use client'
3335
+
3336
+ import Link from 'next/link'
3337
+ import { usePathname } from 'next/navigation'
3338
+ import { ThemeToggle } from './theme-toggle'
3339
+
3340
+ const links = [
3341
+ { href: '/', label: 'Home' },
3342
+ { href: '/auth/sign-in', label: 'Sign In' },
3343
+ { href: '/setup', label: 'Setup' },
3344
+ ]
3345
+
3346
+ export function NavHeader() {
3347
+ const pathname = usePathname()
3348
+
3349
+ function isActive(href: string) {
3350
+ return href === '/' ? pathname === '/' : pathname.startsWith(href)
3351
+ }
3352
+
3353
+ const linkClass = (href: string) =>
3354
+ \`px-3 py-1.5 rounded-md text-sm transition-colors \${
3355
+ isActive(href)
3356
+ ? 'bg-zinc-200 text-zinc-900 dark:bg-zinc-800 dark:text-zinc-50'
3357
+ : 'text-zinc-500 hover:text-zinc-700 hover:bg-zinc-100 dark:text-zinc-400 dark:hover:text-zinc-200 dark:hover:bg-zinc-800/50'
3358
+ }\`
3359
+
3360
+ return (
3361
+ <header className="sticky top-0 z-50 backdrop-blur-md border-b bg-white/80 border-zinc-200 dark:bg-zinc-950/80 dark:border-zinc-800">
3362
+ <nav className="max-w-6xl mx-auto flex items-center gap-1 px-4 h-12">
3363
+ <span className="font-semibold text-sm text-zinc-700 dark:text-zinc-300 mr-3 select-none">
3364
+ ${r}
3365
+ </span>
3366
+ {links.map(({ href, label }) => (
3367
+ <Link key={href} href={href} className={linkClass(href)}>
3368
+ {label}
3369
+ </Link>
3370
+ ))}
3371
+ <div className="ml-auto">
3372
+ <ThemeToggle />
3373
+ </div>
3374
+ </nav>
3375
+ </header>
3376
+ )
3377
+ }
3378
+ `)}async function x(e,t){let{name:r}=t;await n(a(e,`toolkit.config.ts`),`import { auth } from '@murumets-ee/auth/plugin'
3379
+ import { content } from '@murumets-ee/content/plugin'
3380
+ import { defineConfig } from '@murumets-ee/core'
3381
+ import { logging } from '@murumets-ee/logging/plugin'
3382
+ import { mail, ResendMailProvider } from '@murumets-ee/mail'
3383
+ import { media } from '@murumets-ee/media/plugin'
3384
+ import { queue } from '@murumets-ee/queue/plugin'
3385
+ import { settings } from '@murumets-ee/settings/plugin'
3386
+ import { storage } from '@murumets-ee/storage/plugin'
3387
+ import { taxonomy } from '@murumets-ee/taxonomy/plugin'
3388
+ import { ticketing } from '@murumets-ee/ticketing/plugin'
3389
+ import { Article, Category } from './entities'
3390
+ import * as authSchema from './generated/auth-schema'
3391
+
3392
+ if (!process.env.DATABASE_URL) {
3393
+ throw new Error('DATABASE_URL environment variable is required')
3394
+ }
3395
+
3396
+ export default defineConfig({
3397
+ db: {
3398
+ url: process.env.DATABASE_URL,
3399
+ poolMin: 2,
3400
+ poolMax: 10,
3401
+ },
3402
+ logging: {
3403
+ level: (process.env.LOG_LEVEL || 'info') as 'debug' | 'info' | 'warn' | 'error',
3404
+ name: '${r}',
3405
+ },
3406
+ entities: [Category, Article],
3407
+ plugins: [
3408
+ auth({ providers: ['email'], schema: authSchema }),
3409
+ content({
3410
+ locales: [{ code: 'en', label: 'English' }],
3411
+ defaultLocale: 'en',
3412
+ }),
3413
+ logging(),
3414
+ settings(),
3415
+ storage(),
3416
+ media(),
3417
+ taxonomy(),
3418
+ queue(),
3419
+ mail({
3420
+ provider: process.env.RESEND_API_KEY
3421
+ ? new ResendMailProvider({ apiKey: process.env.RESEND_API_KEY })
3422
+ : undefined,
3423
+ defaultFrom: process.env.MAIL_FROM ?? 'noreply@example.com',
3424
+ webhookSecret: process.env.RESEND_WEBHOOK_SECRET,
3425
+ }),
3426
+ ticketing({
3427
+ csatSecret: process.env.CSAT_SECRET,
3428
+ }),
3429
+ ],
3430
+ projectRoot: import.meta.dirname,
3431
+ })
3432
+ `),await n(a(e,`lib/app.ts`),`import { createApp, setApp, type ToolkitApp } from '@murumets-ee/core'
3433
+ import config from '../toolkit.config'
3434
+
3435
+ let appInstance: ToolkitApp | null = null
3436
+
3437
+ export async function getToolkitApp(): Promise<ToolkitApp> {
3438
+ if (!appInstance) {
3439
+ appInstance = await createApp(config)
3440
+ setApp(appInstance)
3441
+ }
3442
+ return appInstance
3443
+ }
3444
+ `),await n(a(e,`drizzle.config.ts`),`import type { Config } from 'drizzle-kit'
3445
+
3446
+ if (!process.env.DATABASE_URL) {
3447
+ throw new Error('DATABASE_URL environment variable is required')
3448
+ }
3449
+
3450
+ export default {
3451
+ schema: ['./generated/schema.ts', './generated/auth-schema.ts'],
3452
+ out: './migrations',
3453
+ dialect: 'postgresql',
3454
+ dbCredentials: {
3455
+ url: process.env.DATABASE_URL,
3456
+ },
3457
+ } satisfies Config
3458
+ `),await n(a(e,`auth.config.ts`),`import { betterAuth } from 'better-auth'
3459
+ import { drizzleAdapter } from 'better-auth/adapters/drizzle'
3460
+ import { admin } from 'better-auth/plugins'
3461
+ import { organization } from 'better-auth/plugins/organization'
3462
+ import { drizzle } from 'drizzle-orm/postgres-js'
3463
+ import postgres from 'postgres'
3464
+
3465
+ const sql = postgres(process.env.DATABASE_URL!)
3466
+ const db = drizzle(sql)
3467
+
3468
+ export const auth = betterAuth({
3469
+ database: drizzleAdapter(db, { provider: 'pg' }),
3470
+ emailAndPassword: { enabled: true },
3471
+ plugins: [
3472
+ admin(),
3473
+ organization(),
3474
+ ],
3475
+ })
3476
+ `),await n(a(e,`generated/auth-schema.ts`),`// This file is generated by better-auth CLI.
3477
+ // Run: npx @better-auth/cli generate --config auth.config.ts -y
3478
+ export {}
3479
+ `)}async function S(e,t){e.mode===`single`?await C(e,t):await w(e,t)}async function C(n,i){let o=a(process.cwd(),n.name);i?.(`Creating Next.js app...`),e(`pnpm create next-app@16 ${n.name} --typescript --tailwind --no-eslint --app --no-src-dir --turbopack --react-compiler --skip-install --import-alias "@/*"`),await t(o,[`app/page.tsx`,`app/page.module.css`,`app/fonts`,`README.md`]),await r(a(o,`package.json`),{type:`module`,dependencies:{"@murumets-ee/core":`^${f.myorgCore}`,"@murumets-ee/db":`^${f.myorgDb}`,"@murumets-ee/entity":`^${f.myorgEntity}`,"@murumets-ee/logging":`^${f.myorgLogging}`,"@murumets-ee/auth":`^${f.myorgAuth}`,"@murumets-ee/auth-ui":`^${f.myorgAuthUi}`,"@murumets-ee/admin-ui":`^${f.myorgAdminUi}`,"@murumets-ee/content":`^${f.myorgContent}`,"@murumets-ee/settings":`^${f.myorgSettings}`,"@murumets-ee/storage":`^${f.myorgStorage}`,"@murumets-ee/media":`^${f.myorgMedia}`,"@murumets-ee/taxonomy":`^${f.myorgTaxonomy}`,"@murumets-ee/queue":`^${f.myorgQueue}`,"@murumets-ee/mail":`^${f.myorgMail}`,"@murumets-ee/ticketing":`^${f.myorgTicketing}`,"@murumets-ee/ticketing-ui":`^${f.myorgTicketingUi}`,"@murumets-ee/tokens":`^${f.myorgTokens}`,"@murumets-ee/editor":`^${f.myorgEditor}`,"@murumets-ee/blocks":`^${f.myorgBlocks}`,"@murumets-ee/ui":`^${f.myorgUi}`,"better-auth":`^${f.betterAuth}`,"drizzle-orm":`^${f.drizzleOrm}`,"next-intl":`^${f.nextIntl}`,"next-themes":`^${f.nextThemes}`,"lucide-react":`^${f.lucideReact}`,postgres:`^${f.postgres}`,"@tanstack/react-query":`^${f.tanstackReactQuery}`,"@tanstack/react-table":`^${f.tanstackReactTable}`,"react-hook-form":`^${f.reactHookForm}`,"@hookform/resolvers":`^${f.hookformResolvers}`,zod:`^${f.zod}`},devDependencies:{"drizzle-kit":`^${f.drizzleKit}`,tsx:`^${f.tsx}`,"babel-plugin-react-compiler":f.babelReactCompiler},scripts:{"db:generate":`tsx --env-file=.env scripts/generate-schema.ts`,"db:migrate:generate":`drizzle-kit generate`,"db:migrate":`tsx --env-file=.env scripts/migrate.ts`,"db:reset":`tsx --env-file=.env scripts/reset-db.ts`,worker:`tsx --env-file=.env scripts/worker.ts`}}),i?.(`Adding toolkit files...`),await l(o,n),await u(o,n),await x(o,n),await c(o,n),await d(o,n),await v(o,n),await b(o,n),await s(o,n),await y(o,n),n.installDeps&&(i?.(`Installing dependencies...`),e(`pnpm install`,{cwd:o}))}async function w(t,n){let r=a(process.cwd(),t.name);n?.(`Creating workspace...`),await p(r,t,n),t.installDeps&&(n?.(`Installing dependencies...`),e(`pnpm install`,{cwd:r}))}export{S as scaffold};
3480
+ //# sourceMappingURL=index.mjs.map