@murumets-ee/create 0.1.20 → 0.3.0

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