From a7e1b261b941cb3e491833ea71615a65ef29ece8 Mon Sep 17 00:00:00 2001 From: Pratyay360 Date: Sat, 28 Nov 2026 02:12:44 +0530 Subject: [PATCH 1/2] pm --- .devcontainer/devcontainer-lock.json | 14 +- .devcontainer/devcontainer.json | 26 +- .frontmatter/database/taxonomyDb.json | 26 +- .../skills/mcp-analytics/SKILL.md | 119 +- .../mcp-analytics/references/custom-events.md | 26 +- .../skills/mcp-analytics/references/events.md | 5 +- .../references/identifying-users.md | 22 +- .../skills/mcp-analytics/references/intent.md | 52 +- .../mcp-analytics/references/start-here.md | 24 +- .../skills/integration-sveltekit/SKILL.md | 1 + .../references/1-begin.md | 1 + .../references/2-edit.md | 1 + .../references/3-revise.md | 1 + .../references/4-conclude.md | 7 +- .../references/EXAMPLE.md | 497 +++---- .../references/identify-users.md | 30 +- .../references/svelte.md | 50 +- .../skills/audit/SKILL.md | 5 +- .../skills/audit/references/6-report.md | 16 +- .../skills/audit/references/best-practices.md | 10 +- .../skills/audit/references/identify-users.md | 30 +- .../skills/self-driving-setup/SKILL.md | 9 +- .../references/5-connected-tools.md | 4 - .../references/5c-credentials.md | 13 +- .../references/5d-google-search-console.md | 1 - .../references/6c-replay-vision-scanners.md | 2 - .../self-driving-setup/references/7-report.md | 1 - .zed/settings.json | 498 +++---- auth-schema.ts | 199 +-- bun.lock | 604 ++++----- components.json | 36 +- context7.json | 4 +- crowdin.yml | 2 +- drizzle.config.ts | 12 +- drizzle/meta/0000_snapshot.json | 1098 ++++++++-------- drizzle/meta/0001_snapshot.json | 32 +- drizzle/meta/0002_snapshot.json | 1098 ++++++++-------- drizzle/meta/0003_snapshot.json | 1152 ++++++++--------- drizzle/meta/0004_snapshot.json | 1098 ++++++++-------- drizzle/meta/_journal.json | 78 +- drizzle/relations.ts | 49 +- drizzle/schema.ts | 285 ++-- frontmatter.json | 164 +-- messages/en.json | 336 ++--- messages/es.json | 282 ++-- package.json | 396 +++--- src/app.d.ts | 30 +- src/hooks.client.ts | 104 +- src/hooks.server.ts | 188 +-- src/hooks.ts | 2 +- src/lib/auth-client.ts | 2 +- src/lib/bot/content.ts | 16 +- src/lib/bot/handlers/error-handler.ts | 16 +- src/lib/bot/handlers/installation.ts | 99 +- src/lib/bot/handlers/ping.ts | 16 +- src/lib/bot/handlers/pull-request.ts | 333 ++--- src/lib/bot/handlers/push.ts | 313 ++--- src/lib/bot/index.ts | 33 +- src/lib/client/logging.ts | 36 +- src/lib/client/tracing.ts | 66 +- src/lib/client/vercel-analytics.svelte.ts | 30 +- src/lib/cms-urls.ts | 33 +- src/lib/components/DemoPreview.svelte | 2 +- src/lib/components/Featured.svelte | 8 +- src/lib/components/Hero.svelte | 4 +- src/lib/components/Supademo.svelte | 28 +- src/lib/components/cms/EditorWorkspace.svelte | 28 +- .../components/cms/FrontmatterEditor.svelte | 10 +- src/lib/components/cms/SaveStatus.svelte | 6 +- src/lib/components/cms/frontmatter.types.ts | 430 +++--- src/lib/components/custom/CarbonBadge.svelte | 3 +- .../custom/CreateBranchDialog.svelte | 12 +- .../custom/CreateFolderDialog.svelte | 12 +- .../components/custom/DocsBlogBanner.svelte | 8 +- .../custom/FrontmatterDrawer.svelte | 8 +- .../components/custom/LanguageSwitcher.svelte | 16 +- src/lib/components/custom/MetaTags.svelte | 6 +- .../components/custom/StarRepoDialog.svelte | 8 +- src/lib/components/custom/TagManager.svelte | 10 +- .../components/custom/TemplateDrawer.svelte | 2 +- src/lib/components/custom/ToggleMode.svelte | 14 +- .../custom/frontmatter-drawer.types.ts | 4 +- .../components/docs/DocBreadcrumbLlm.svelte | 8 +- src/lib/components/docs/DocSearchModal.svelte | 8 +- src/lib/components/docs/DocSidebar.svelte | 7 +- .../components/docs/DocTableOfContents.svelte | 6 +- src/lib/components/edra/commands/ai.ts | 40 +- src/lib/components/edra/commands/alignment.ts | 132 +- src/lib/components/edra/commands/commands.ts | 40 +- src/lib/components/edra/commands/diagram.ts | 20 +- src/lib/components/edra/commands/headings.ts | 150 +-- src/lib/components/edra/commands/history.ts | 54 +- src/lib/components/edra/commands/lists.ts | 104 +- src/lib/components/edra/commands/math.ts | 56 +- .../components/edra/commands/media.test.ts | 149 ++- src/lib/components/edra/commands/media.ts | 111 +- src/lib/components/edra/commands/prompts.ts | 8 +- src/lib/components/edra/commands/table.ts | 42 +- .../edra/commands/text-formatting.ts | 394 +++--- src/lib/components/edra/commands/types.ts | 20 +- .../edra/docs/packageManager.svelte.ts | 39 +- src/lib/components/edra/extensions.ts | 180 +-- .../edra/harper/HarperPopover.svelte | 4 +- .../components/edra/harper/MicButton.svelte | 12 +- .../edra/harper/MicWidgetPanel.svelte | 6 +- .../edra/harper/dictation-shortcut.test.ts | 160 ++- .../edra/harper/dictation-shortcut.ts | 19 +- .../edra/harper/draggable-widget.svelte.ts | 316 ++--- .../edra/harper/draggable-widget.test.ts | 392 +++--- .../edra/harper/harper-client.test.ts | 325 ++--- .../components/edra/harper/harper-client.ts | 195 +-- .../edra/harper/harper-hover.svelte.ts | 725 ++++++----- .../edra/harper/harper-hover.test.ts | 998 +++++++------- .../edra/harper/speech-recognition.svelte.ts | 1013 ++++++++------- .../edra/harper/speech-recognition.test.ts | 536 ++++---- .../edra/harper/speech-recognition.ts | 443 ++++--- src/lib/components/edra/harper/types.ts | 42 +- src/lib/components/edra/onedark.css | 196 +-- .../edra/shadcn/components/Callout.svelte | 8 +- .../edra/shadcn/components/CodeBlock.svelte | 8 +- .../shadcn/components/ImageExtended.svelte | 45 +- .../shadcn/components/MediaExtended.svelte | 4 +- .../shadcn/components/MediaPlaceHolder.svelte | 412 ++++-- .../edra/shadcn/components/Mermaid.svelte | 6 +- .../shadcn/components/SlashCommand.svelte | 4 +- .../edra/shadcn/components/Toolbar.svelte | 14 +- .../edra/shadcn/components/Tooltip.svelte | 2 +- .../components/media/MediaToolbar.svelte | 12 +- .../shadcn/components/media/resize.svelte.ts | 115 +- .../edra/shadcn/components/menu/AI.svelte | 33 +- .../shadcn/components/menu/BubbleMenu.svelte | 16 +- .../edra/shadcn/components/menu/Link.svelte | 12 +- .../shadcn/components/menu/MathBlock.svelte | 10 +- .../shadcn/components/menu/MathInline.svelte | 12 +- .../shadcn/components/menu/TableCol.svelte | 6 +- .../shadcn/components/menu/TableRow.svelte | 4 +- .../components/menu/ai-content-manager.ts | 428 +++--- .../components/menu/ai/AiActionBar.svelte | 4 +- .../components/menu/ai/AiPromptForm.svelte | 2 +- .../components/menu/ai/AiQuickActions.svelte | 6 +- .../shadcn/components/menu/ai/keyboard.ts | 101 +- .../components/menu/ai/quick-actions.ts | 44 +- .../components/mermaid/MermaidEditor.svelte | 6 +- .../components/mermaid/MermaidPreview.svelte | 2 +- .../shadcn/components/mermaid/download.ts | 66 +- .../edra/shadcn/components/mermaid/render.ts | 101 +- .../shadcn/components/tools/AlignMent.svelte | 10 +- .../shadcn/components/tools/Colors.svelte | 8 +- .../shadcn/components/tools/Export.svelte | 6 +- .../shadcn/components/tools/FontSize.svelte | 6 +- .../edra/shadcn/components/tools/Link.svelte | 10 +- .../edra/shadcn/components/tools/Lists.svelte | 10 +- .../edra/shadcn/drag-handle-actions.ts | 154 ++- .../components/edra/shadcn/drag-handle.svelte | 17 +- .../drag-handle/AlignmentSubmenu.svelte | 2 +- .../shadcn/drag-handle/ColorsSubmenu.svelte | 6 +- .../shadcn/drag-handle/CopyAsSubmenu.svelte | 6 +- .../shadcn/drag-handle/TurnIntoMenu.svelte | 6 +- src/lib/components/edra/shadcn/editor.css | 660 +++++----- src/lib/components/edra/shadcn/editor.svelte | 4 +- src/lib/components/edra/shadcn/editor.ts | 154 +-- .../edra/shadcn/hooks/useAiEnabled.svelte.ts | 17 +- .../shadcn/hooks/useCommandState.svelte.ts | 26 +- src/lib/components/edra/shadcn/index.ts | 14 +- .../edra/shadcn/toc.state.svelte.ts | 2 +- src/lib/components/edra/shadcn/toc.svelte | 6 +- src/lib/components/edra/shadcn/toc.ts | 2 +- src/lib/components/edra/strings.ts | 2 +- src/lib/components/edra/strings/commands.ts | 71 +- src/lib/components/edra/strings/editor.ts | 22 +- src/lib/components/edra/strings/extensions.ts | 172 +-- src/lib/components/edra/strings/index.ts | 50 +- .../components/edra/strings/menu-toolbar.ts | 170 +-- src/lib/components/edra/tiptap/Editor.ts | 70 +- .../edra/tiptap/components/Tiptap.svelte | 2 +- .../tiptap/components/TiptapContent.svelte | 2 +- .../edra/tiptap/components/editorContext.ts | 16 +- .../edra/tiptap/extensions/Callout.ts | 231 ++-- .../tiptap/extensions/ColorHighlighter.ts | 42 +- .../tiptap/extensions/MediaPlaceHolder.ts | 287 ++-- .../SelectAcrossAtoms/SelectAcrossAtoms.ts | 624 ++++----- .../SelectAcrossAtoms/atom-selection.ts | 304 +++-- .../SelectAcrossAtoms/click-handlers.ts | 201 +-- .../SelectAcrossAtoms/hit-testing.ts | 121 +- .../extensions/SelectAcrossAtoms/index.ts | 36 +- .../SelectAcrossAtoms/node-classification.ts | 19 +- .../extensions/SelectAcrossAtoms/types.ts | 14 +- .../edra/tiptap/extensions/ai/index.ts | 389 +++--- .../edra/tiptap/extensions/audio/index.ts | 150 +-- .../tiptap/extensions/autocomplete/catalog.ts | 140 +- .../extensions/autocomplete/decorations.ts | 22 +- .../tiptap/extensions/autocomplete/emoji.ts | 420 +++--- .../tiptap/extensions/autocomplete/index.ts | 32 +- .../extensions/autocomplete/matchers.ts | 124 +- .../tiptap/extensions/autocomplete/plugin.ts | 157 +-- .../tiptap/extensions/autocomplete/types.ts | 36 +- .../edra/tiptap/extensions/harper/index.ts | 496 +++---- .../edra/tiptap/extensions/iframe/index.ts | 306 ++--- .../edra/tiptap/extensions/image-upload.ts | 116 +- .../tiptap/extensions/image/ImageExtended.ts | 312 ++--- .../edra/tiptap/extensions/index.ts | 28 +- .../tiptap/extensions/link/LinkExtended.ts | 100 +- .../edra/tiptap/extensions/mermaid/index.ts | 230 ++-- .../edra/tiptap/extensions/slash/catalog.ts | 462 ++++--- .../edra/tiptap/extensions/slash/index.ts | 54 +- .../edra/tiptap/extensions/slash/plugin.ts | 123 +- .../edra/tiptap/extensions/slash/popup.ts | 212 +-- .../edra/tiptap/extensions/table/dom-utils.ts | 179 +-- .../extensions/table/grip-interaction.ts | 208 +-- .../edra/tiptap/extensions/table/index.ts | 10 +- .../tiptap/extensions/table/move-utils.ts | 233 ++-- .../extensions/table/selection-utils.ts | 429 +++--- .../tiptap/extensions/table/table-cell.ts | 174 +-- .../tiptap/extensions/table/table-header.ts | 259 ++-- .../edra/tiptap/extensions/table/table-row.ts | 4 +- .../edra/tiptap/extensions/table/table.ts | 6 +- .../edra/tiptap/extensions/table/utils.ts | 45 +- .../edra/tiptap/extensions/video/Video.ts | 450 +++---- .../tiptap/extensions/video/VideoExtended.ts | 56 +- .../edra/tiptap/hooks/useEditor.svelte.ts | 30 +- .../tiptap/hooks/useEditorState.svelte.ts | 89 +- .../hooks/useEditorTransaction.svelte.ts | 30 +- src/lib/components/edra/tiptap/index.ts | 8 +- .../renderers/SvelteMarkViewRenderer.ts | 97 +- .../renderers/SvelteNodeViewRenderer.ts | 440 ++++--- .../tiptap/renderers/SvelteRenderer.svelte.ts | 103 +- .../edra/tiptap/renderers/SvelteRenderer.ts | 5 +- src/lib/components/edra/utils.ts | 129 +- src/lib/components/highlighter.ts | 34 +- .../magic/dot-pattern/dot-pattern.svelte | 2 +- .../components/ui/alert/alert-action.svelte | 2 +- .../ui/alert/alert-description.svelte | 2 +- .../components/ui/alert/alert-title.svelte | 2 +- src/lib/components/ui/alert/alert.svelte | 4 +- src/lib/components/ui/alert/alert.ts | 22 +- src/lib/components/ui/alert/index.ts | 18 +- .../ui/avatar/avatar-fallback.svelte | 2 +- .../components/ui/avatar/avatar-image.svelte | 6 +- src/lib/components/ui/avatar/avatar.svelte | 6 +- src/lib/components/ui/avatar/index.ts | 12 +- src/lib/components/ui/badge/badge.svelte | 4 +- src/lib/components/ui/badge/badge.ts | 32 +- src/lib/components/ui/button/button.svelte | 4 +- src/lib/components/ui/button/button.ts | 79 +- src/lib/components/ui/button/index.ts | 23 +- src/lib/components/ui/card/card-action.svelte | 2 +- .../components/ui/card/card-content.svelte | 2 +- .../ui/card/card-description.svelte | 2 +- src/lib/components/ui/card/card-footer.svelte | 2 +- src/lib/components/ui/card/card-header.svelte | 2 +- src/lib/components/ui/card/card-title.svelte | 2 +- src/lib/components/ui/card/card.svelte | 2 +- src/lib/components/ui/card/index.ts | 30 +- .../components/ui/checkbox/checkbox.svelte | 2 +- src/lib/components/ui/checkbox/index.ts | 6 +- .../ui/command/command-dialog.svelte | 4 +- .../ui/command/command-empty.svelte | 2 +- .../ui/command/command-group.svelte | 2 +- .../ui/command/command-input.svelte | 4 +- .../components/ui/command/command-item.svelte | 2 +- .../ui/command/command-link-item.svelte | 2 +- .../components/ui/command/command-list.svelte | 2 +- .../ui/command/command-separator.svelte | 2 +- .../ui/command/command-shortcut.svelte | 2 +- src/lib/components/ui/command/command.svelte | 2 +- src/lib/components/ui/command/index.ts | 46 +- .../ui/dialog/dialog-content.svelte | 6 +- .../ui/dialog/dialog-description.svelte | 2 +- .../components/ui/dialog/dialog-footer.svelte | 4 +- .../components/ui/dialog/dialog-header.svelte | 2 +- .../ui/dialog/dialog-overlay.svelte | 2 +- .../components/ui/dialog/dialog-title.svelte | 2 +- src/lib/components/ui/dialog/index.ts | 42 +- .../dropdown-menu-checkbox-item.svelte | 4 +- .../dropdown-menu-content.svelte | 2 +- .../dropdown-menu-group-heading.svelte | 4 +- .../dropdown-menu/dropdown-menu-item.svelte | 4 +- .../dropdown-menu/dropdown-menu-label.svelte | 4 +- .../dropdown-menu-radio-item.svelte | 2 +- .../dropdown-menu-separator.svelte | 2 +- .../dropdown-menu-shortcut.svelte | 2 +- .../dropdown-menu-sub-content.svelte | 2 +- .../dropdown-menu-sub-trigger.svelte | 2 +- src/lib/components/ui/dropdown-menu/index.ts | 68 +- src/lib/components/ui/input-group/index.ts | 26 +- .../ui/input-group/input-group-addon.svelte | 2 +- .../ui/input-group/input-group-button.svelte | 4 +- .../ui/input-group/input-group-input.svelte | 4 +- .../ui/input-group/input-group-text.svelte | 2 +- .../input-group/input-group-textarea.svelte | 4 +- .../ui/input-group/input-group.svelte | 2 +- src/lib/components/ui/input/index.ts | 6 +- src/lib/components/ui/input/input.svelte | 2 +- src/lib/components/ui/kbd/index.ts | 10 +- src/lib/components/ui/kbd/kbd-group.svelte | 2 +- src/lib/components/ui/kbd/kbd.svelte | 2 +- src/lib/components/ui/label/index.ts | 6 +- src/lib/components/ui/label/label.svelte | 2 +- src/lib/components/ui/popover/index.ts | 34 +- .../ui/popover/popover-content.svelte | 2 +- .../ui/popover/popover-description.svelte | 2 +- .../ui/popover/popover-header.svelte | 2 +- .../ui/popover/popover-title.svelte | 2 +- .../ui/popover/popover-trigger.svelte | 2 +- src/lib/components/ui/separator/index.ts | 6 +- .../components/ui/separator/separator.svelte | 2 +- src/lib/components/ui/spinner/spinner.svelte | 2 +- src/lib/components/ui/tabs/index.ts | 22 +- .../components/ui/tabs/tabs-content.svelte | 2 +- src/lib/components/ui/tabs/tabs-list.svelte | 2 +- src/lib/components/ui/tabs/tabs-list.ts | 20 +- .../components/ui/tabs/tabs-trigger.svelte | 2 +- src/lib/components/ui/tabs/tabs.svelte | 2 +- src/lib/components/ui/textarea/index.ts | 6 +- .../components/ui/textarea/textarea.svelte | 2 +- src/lib/components/ui/tooltip/index.ts | 22 +- .../ui/tooltip/tooltip-content.svelte | 4 +- src/lib/hooks/is-mobile.ts | 20 +- src/lib/i18n.ts | 1 + src/lib/i18n/i18n.test.ts | 168 +-- src/lib/i18n/index.svelte.ts | 275 ++-- src/lib/i18n/messages.ts | 464 ++++--- src/lib/orpc-client.ts | 12 +- src/lib/passkey.ts | 42 +- src/lib/schemas/entry.ts | 275 ++-- src/lib/seo.ts | 233 ++-- src/lib/server/ai-observability.ts | 156 +-- src/lib/server/auth.ts | 249 ++-- src/lib/server/cms-context.ts | 121 +- src/lib/server/cms/entry.ts | 609 +++++---- src/lib/server/cms/folder.ts | 170 +-- src/lib/server/cms/frontmatter.ts | 356 ++--- src/lib/server/cms/index.ts | 79 +- src/lib/server/cms/slug-helpers.ts | 76 +- src/lib/server/cms/storage.ts | 114 +- src/lib/server/cms/tree.ts | 435 ++++--- src/lib/server/cms/types.ts | 50 +- src/lib/server/config.ts | 513 ++++---- src/lib/server/db/auth.schema.ts | 255 ++-- src/lib/server/db/index.ts | 5 +- src/lib/server/docs.ts | 540 ++++---- src/lib/server/github-app.ts | 8 +- src/lib/server/github-install-state.ts | 68 +- src/lib/server/github-user-access.ts | 100 +- src/lib/server/github/branches.ts | 248 ++-- src/lib/server/github/errors.ts | 71 +- src/lib/server/github/helpers.ts | 46 +- src/lib/server/github/index.ts | 31 +- src/lib/server/github/read.ts | 219 ++-- src/lib/server/github/types.ts | 14 +- src/lib/server/github/write.ts | 393 +++--- src/lib/server/i18n.ts | 29 +- src/lib/server/markdown.ts | 196 +-- src/lib/server/matter.ts | 30 +- src/lib/server/orpc/cms-router.ts | 864 +++++++------ src/lib/server/orpc/cms-service.ts | 52 +- src/lib/server/orpc/context.ts | 22 +- src/lib/server/orpc/router.ts | 268 ++-- src/lib/server/paths.ts | 223 ++-- src/lib/server/posthog.ts | 242 ++-- src/lib/server/probot.ts | 26 +- src/lib/server/session.ts | 77 +- src/lib/server/speech-ai-sdk.test.ts | 269 ++-- src/lib/server/speech-ai-sdk.ts | 256 ++-- src/lib/server/transcription.test.ts | 289 +++-- src/lib/server/transcription.ts | 209 +-- src/lib/server/wit-ai.test.ts | 401 +++--- src/lib/server/wit-ai.ts | 467 +++---- src/lib/speech-providers.ts | 7 +- src/lib/templates.ts | 91 +- src/lib/themes.ts | 124 +- src/lib/utils.ts | 12 +- src/lib/utils/cms-url.ts | 38 +- src/lib/utils/mail.ts | 102 +- src/lib/utils/mailtemplate.ts | 6 +- src/lib/utils/time-ago.ts | 16 +- src/lib/utils/upload-file.ts | 173 +-- src/lib/utils/youtube.test.ts | 102 ++ src/lib/utils/youtube.ts | 92 ++ src/routes/+error.svelte | 6 +- src/routes/+layout.server.ts | 8 +- src/routes/+layout.svelte | 157 +-- src/routes/+page.svelte | 11 +- src/routes/+page.ts | 91 +- src/routes/about/+page.svelte | 8 +- src/routes/api/github/webhook/+server.ts | 75 +- src/routes/api/image-upload/+server.ts | 101 +- src/routes/api/rpc/[...rest]/+server.ts | 28 +- src/routes/auth/+page.server.ts | 66 +- src/routes/auth/+page.svelte | 534 ++++---- src/routes/cms/+page.server.ts | 411 +++--- src/routes/cms/+page.svelte | 6 +- src/routes/cms/[collection]/+page.server.ts | 388 +++--- src/routes/cms/[collection]/+page.svelte | 15 +- .../cms/[collection]/[slug]/+page.server.ts | 1104 ++++++++-------- .../cms/[collection]/[slug]/+page.svelte | 8 +- src/routes/cms/edit/[...path]/+page.server.ts | 368 +++--- src/routes/cms/edit/[...path]/+page.svelte | 6 +- src/routes/cms/tree/[...path]/+page.server.ts | 493 +++---- src/routes/cms/tree/[...path]/+page.svelte | 15 +- src/routes/demo/+page.server.ts | 48 +- src/routes/demo/+page.svelte | 9 +- src/routes/docs/+layout.server.ts | 14 +- src/routes/docs/+layout.svelte | 10 +- src/routes/docs/+page.server.ts | 9 +- src/routes/docs/+page.svelte | 10 +- src/routes/docs/[slug]/+page.server.ts | 174 +-- src/routes/docs/[slug]/+page.svelte | 61 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/af/building-a-greener-web.md | 19 +- .../src/af/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/af/how-to-start-a-blog.md | 27 +- src/routes/docs/src/af/newsletter-newsy.md | 25 +- .../docs/src/af/self-hosting-lightcms.md | 27 +- src/routes/docs/src/af/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/ar/building-a-greener-web.md | 19 +- .../src/ar/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/ar/how-to-start-a-blog.md | 27 +- src/routes/docs/src/ar/newsletter-newsy.md | 25 +- .../docs/src/ar/self-hosting-lightcms.md | 27 +- src/routes/docs/src/ar/why-lightcms.md | 29 +- src/routes/docs/src/building-a-greener-web.md | 19 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/ca/building-a-greener-web.md | 19 +- .../src/ca/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/ca/how-to-start-a-blog.md | 27 +- src/routes/docs/src/ca/newsletter-newsy.md | 25 +- .../docs/src/ca/self-hosting-lightcms.md | 27 +- src/routes/docs/src/ca/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/cs/building-a-greener-web.md | 19 +- .../src/cs/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/cs/how-to-start-a-blog.md | 27 +- src/routes/docs/src/cs/newsletter-newsy.md | 25 +- .../docs/src/cs/self-hosting-lightcms.md | 27 +- src/routes/docs/src/cs/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/da/building-a-greener-web.md | 19 +- .../src/da/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/da/how-to-start-a-blog.md | 27 +- src/routes/docs/src/da/newsletter-newsy.md | 25 +- .../docs/src/da/self-hosting-lightcms.md | 27 +- src/routes/docs/src/da/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/de/building-a-greener-web.md | 19 +- .../src/de/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/de/how-to-start-a-blog.md | 27 +- src/routes/docs/src/de/newsletter-newsy.md | 25 +- .../docs/src/de/self-hosting-lightcms.md | 27 +- src/routes/docs/src/de/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/el/building-a-greener-web.md | 19 +- .../src/el/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/el/how-to-start-a-blog.md | 27 +- src/routes/docs/src/el/newsletter-newsy.md | 25 +- .../docs/src/el/self-hosting-lightcms.md | 27 +- src/routes/docs/src/el/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/es/building-a-greener-web.md | 19 +- .../src/es/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/es/how-to-start-a-blog.md | 27 +- src/routes/docs/src/es/newsletter-newsy.md | 25 +- .../docs/src/es/self-hosting-lightcms.md | 27 +- src/routes/docs/src/es/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/fi/building-a-greener-web.md | 19 +- .../src/fi/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/fi/how-to-start-a-blog.md | 27 +- src/routes/docs/src/fi/newsletter-newsy.md | 25 +- .../docs/src/fi/self-hosting-lightcms.md | 27 +- src/routes/docs/src/fi/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/fr/building-a-greener-web.md | 19 +- .../src/fr/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/fr/how-to-start-a-blog.md | 27 +- src/routes/docs/src/fr/newsletter-newsy.md | 25 +- .../docs/src/fr/self-hosting-lightcms.md | 27 +- src/routes/docs/src/fr/why-lightcms.md | 29 +- .../docs/src/getting-started-with-lightcms.md | 31 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/he/building-a-greener-web.md | 19 +- .../src/he/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/he/how-to-start-a-blog.md | 27 +- src/routes/docs/src/he/newsletter-newsy.md | 25 +- .../docs/src/he/self-hosting-lightcms.md | 27 +- src/routes/docs/src/he/why-lightcms.md | 29 +- src/routes/docs/src/how-to-start-a-blog.md | 27 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/hu/building-a-greener-web.md | 19 +- .../src/hu/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/hu/how-to-start-a-blog.md | 27 +- src/routes/docs/src/hu/newsletter-newsy.md | 25 +- .../docs/src/hu/self-hosting-lightcms.md | 27 +- src/routes/docs/src/hu/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/it/building-a-greener-web.md | 19 +- .../src/it/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/it/how-to-start-a-blog.md | 27 +- src/routes/docs/src/it/newsletter-newsy.md | 25 +- .../docs/src/it/self-hosting-lightcms.md | 29 +- src/routes/docs/src/it/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/ja/building-a-greener-web.md | 19 +- .../src/ja/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/ja/how-to-start-a-blog.md | 27 +- src/routes/docs/src/ja/newsletter-newsy.md | 25 +- .../docs/src/ja/self-hosting-lightcms.md | 27 +- src/routes/docs/src/ja/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/ko/building-a-greener-web.md | 19 +- .../src/ko/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/ko/how-to-start-a-blog.md | 27 +- src/routes/docs/src/ko/newsletter-newsy.md | 25 +- .../docs/src/ko/self-hosting-lightcms.md | 27 +- src/routes/docs/src/ko/why-lightcms.md | 29 +- src/routes/docs/src/newsletter-newsy.md | 25 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/nl/building-a-greener-web.md | 19 +- .../src/nl/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/nl/how-to-start-a-blog.md | 27 +- src/routes/docs/src/nl/newsletter-newsy.md | 25 +- .../docs/src/nl/self-hosting-lightcms.md | 27 +- src/routes/docs/src/nl/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/no/building-a-greener-web.md | 19 +- .../src/no/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/no/how-to-start-a-blog.md | 27 +- src/routes/docs/src/no/newsletter-newsy.md | 25 +- .../docs/src/no/self-hosting-lightcms.md | 27 +- src/routes/docs/src/no/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/pl/building-a-greener-web.md | 19 +- .../src/pl/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/pl/how-to-start-a-blog.md | 27 +- src/routes/docs/src/pl/newsletter-newsy.md | 25 +- .../docs/src/pl/self-hosting-lightcms.md | 27 +- src/routes/docs/src/pl/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/pt-BR/building-a-greener-web.md | 19 +- .../pt-BR/getting-started-with-lightcms.md | 31 +- .../docs/src/pt-BR/how-to-start-a-blog.md | 27 +- src/routes/docs/src/pt-BR/newsletter-newsy.md | 25 +- .../docs/src/pt-BR/self-hosting-lightcms.md | 27 +- src/routes/docs/src/pt-BR/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/pt/building-a-greener-web.md | 19 +- .../src/pt/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/pt/how-to-start-a-blog.md | 27 +- src/routes/docs/src/pt/newsletter-newsy.md | 25 +- .../docs/src/pt/self-hosting-lightcms.md | 27 +- src/routes/docs/src/pt/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/ro/building-a-greener-web.md | 19 +- .../src/ro/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/ro/how-to-start-a-blog.md | 27 +- src/routes/docs/src/ro/newsletter-newsy.md | 25 +- .../docs/src/ro/self-hosting-lightcms.md | 27 +- src/routes/docs/src/ro/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/ru/building-a-greener-web.md | 19 +- .../src/ru/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/ru/how-to-start-a-blog.md | 27 +- src/routes/docs/src/ru/newsletter-newsy.md | 25 +- .../docs/src/ru/self-hosting-lightcms.md | 29 +- src/routes/docs/src/ru/why-lightcms.md | 29 +- src/routes/docs/src/self-hosting-lightcms.md | 27 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/sr/building-a-greener-web.md | 19 +- .../src/sr/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/sr/how-to-start-a-blog.md | 27 +- src/routes/docs/src/sr/newsletter-newsy.md | 25 +- .../docs/src/sr/self-hosting-lightcms.md | 27 +- src/routes/docs/src/sr/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/sv/building-a-greener-web.md | 19 +- .../src/sv/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/sv/how-to-start-a-blog.md | 27 +- src/routes/docs/src/sv/newsletter-newsy.md | 25 +- .../docs/src/sv/self-hosting-lightcms.md | 27 +- src/routes/docs/src/sv/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/tr/building-a-greener-web.md | 19 +- .../src/tr/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/tr/how-to-start-a-blog.md | 27 +- src/routes/docs/src/tr/newsletter-newsy.md | 25 +- .../docs/src/tr/self-hosting-lightcms.md | 27 +- src/routes/docs/src/tr/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/uk/building-a-greener-web.md | 19 +- .../src/uk/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/uk/how-to-start-a-blog.md | 27 +- src/routes/docs/src/uk/newsletter-newsy.md | 25 +- .../docs/src/uk/self-hosting-lightcms.md | 27 +- src/routes/docs/src/uk/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/vi/building-a-greener-web.md | 19 +- .../src/vi/getting-started-with-lightcms.md | 31 +- src/routes/docs/src/vi/how-to-start-a-blog.md | 27 +- src/routes/docs/src/vi/newsletter-newsy.md | 25 +- .../docs/src/vi/self-hosting-lightcms.md | 27 +- src/routes/docs/src/vi/why-lightcms.md | 29 +- src/routes/docs/src/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/zh-CN/building-a-greener-web.md | 19 +- .../zh-CN/getting-started-with-lightcms.md | 31 +- .../docs/src/zh-CN/how-to-start-a-blog.md | 27 +- src/routes/docs/src/zh-CN/newsletter-newsy.md | 25 +- .../docs/src/zh-CN/self-hosting-lightcms.md | 27 +- src/routes/docs/src/zh-CN/why-lightcms.md | 29 +- .../2026-10-14-frequently-asked-questions.md | 17 +- ...est-way-to-manage-documentation-in-2027.md | 25 +- .../docs/src/zh-TW/building-a-greener-web.md | 19 +- .../zh-TW/getting-started-with-lightcms.md | 31 +- .../docs/src/zh-TW/how-to-start-a-blog.md | 27 +- src/routes/docs/src/zh-TW/newsletter-newsy.md | 25 +- .../docs/src/zh-TW/self-hosting-lightcms.md | 27 +- src/routes/docs/src/zh-TW/why-lightcms.md | 29 +- src/routes/github/install/+server.ts | 39 +- src/routes/github/setup/+server.ts | 126 +- src/routes/privacy/+page.server.ts | 4 +- src/routes/signout/+page.server.ts | 8 +- src/routes/signout/+page.svelte | 6 +- src/routes/sitemap.xml/+server.ts | 82 +- static/manifest.json | 38 +- tsconfig.json | 34 +- turbo.json | 190 +-- vercel.json | 66 +- vite.config.ts | 63 +- 659 files changed, 27451 insertions(+), 24546 deletions(-) create mode 100644 src/lib/i18n.ts create mode 100644 src/lib/utils/youtube.test.ts create mode 100644 src/lib/utils/youtube.ts diff --git a/.devcontainer/devcontainer-lock.json b/.devcontainer/devcontainer-lock.json index a623d40..dc5d565 100644 --- a/.devcontainer/devcontainer-lock.json +++ b/.devcontainer/devcontainer-lock.json @@ -1,9 +1,9 @@ { - "features": { - "ghcr.io/devcontainers-extra/features/mise:1": { - "version": "1.0.0", - "resolved": "ghcr.io/devcontainers-extra/features/mise@sha256:5c389ab1e3c8e44e5e0ff119f6868d54dbb781bc860bd8587dc66209cb8c4a8c", - "integrity": "sha256:5c389ab1e3c8e44e5e0ff119f6868d54dbb781bc860bd8587dc66209cb8c4a8c" - } - } + "features": { + "ghcr.io/devcontainers-extra/features/mise:1": { + "version": "1.0.0", + "resolved": "ghcr.io/devcontainers-extra/features/mise@sha256:5c389ab1e3c8e44e5e0ff119f6868d54dbb781bc860bd8587dc66209cb8c4a8c", + "integrity": "sha256:5c389ab1e3c8e44e5e0ff119f6868d54dbb781bc860bd8587dc66209cb8c4a8c" + } + } } diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index d243a7c..a3828e2 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,15 +1,15 @@ { - "name": "mise", - "image": "mcr.microsoft.com/devcontainers/base:ubuntu", - "features": { - "ghcr.io/devcontainers-extra/features/mise:1": {} - }, - "customizations": { - "vscode": { - "extensions": ["hverlin.mise-vscode"] - } - }, - "mounts": [], - "containerEnv": {}, - "remoteEnv": {} + "name": "mise", + "image": "mcr.microsoft.com/devcontainers/base:ubuntu", + "features": { + "ghcr.io/devcontainers-extra/features/mise:1": {} + }, + "customizations": { + "vscode": { + "extensions": ["hverlin.mise-vscode"] + } + }, + "mounts": [], + "containerEnv": {}, + "remoteEnv": {} } diff --git a/.frontmatter/database/taxonomyDb.json b/.frontmatter/database/taxonomyDb.json index f0b2348..a2ebc90 100644 --- a/.frontmatter/database/taxonomyDb.json +++ b/.frontmatter/database/taxonomyDb.json @@ -1,15 +1,15 @@ { - "taxonomy": { - "tags": [ - "cms", - "co2", - "faq", - "green-web", - "lightcms", - "philosophy", - "ssg", - "static-sites", - "sustainability" - ] - } + "taxonomy": { + "tags": [ + "cms", + "co2", + "faq", + "green-web", + "lightcms", + "philosophy", + "ssg", + "static-sites", + "sustainability" + ] + } } diff --git a/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/SKILL.md b/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/SKILL.md index 21016f6..323c93c 100644 --- a/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/SKILL.md +++ b/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/SKILL.md @@ -1,15 +1,16 @@ --- + name: mcp-analytics description: >- - Add PostHog MCP analytics to a TypeScript, JavaScript, or Python MCP server. - Captures tool calls, agent intent, failures, and protocol revision, plus - self-reported model identity on supported TypeScript paths. Both SDKs support - legacy sessions and the handshake-free 2026-07-28 revision. Detects the server - style and wires in compatible instrumentation, credentials, conversation - correlation, and graceful shutdown. +Add PostHog MCP analytics to a TypeScript, JavaScript, or Python MCP server. +Captures tool calls, agent intent, failures, and protocol revision, plus +self-reported model identity on supported TypeScript paths. Both SDKs support +legacy sessions and the handshake-free 2026-07-28 revision. Detects the server +style and wires in compatible instrumentation, credentials, conversation +correlation, and graceful shutdown. metadata: - author: PostHog - version: 1.59.0 +author: PostHog +version: 1.59.0 --- # Add PostHog MCP analytics @@ -128,7 +129,7 @@ Create the PostHog client **once at module scope** (never per request), reading import { PostHog } from "posthog-node"; const posthog = new PostHog(process.env.POSTHOG_PROJECT_TOKEN, { - host: process.env.VITE_POSTHOG_HOST, // https://us.i.posthog.com or https://eu.i.posthog.com + host: process.env.VITE_POSTHOG_HOST, // https://us.i.posthog.com or https://eu.i.posthog.com }); ``` @@ -142,7 +143,7 @@ import { instrument } from "@posthog/mcp"; const server = new McpServer({ name: "my-mcp-server", version: "1.0.0" }); const analytics = instrument(server, posthog, { - captureModel: true, + captureModel: true, }); // wrap immediately after constructing the server // register tools as usual — tools added after instrument() are still captured ``` @@ -155,8 +156,8 @@ import { instrument } from "@posthog/mcp"; const server = new McpServer({ name: "my-mcp-server", version: "1.0.0" }); const analytics = instrument(server, posthog, { - captureModel: true, - enableConversationId: true, + captureModel: true, + enableConversationId: true, }); // wrap immediately after constructing the server // register tools with registerTool() as usual — tools added after instrument() are still captured ``` @@ -173,17 +174,23 @@ v2 reminders: import { instrument, getRequestHeaders } from "@posthog/mcp"; const handler = createMcpHandler((server) => { - instrument(server, posthog, { - captureModel: true, - enableConversationId: true, - identify: async (request, extra) => { - const token = getRequestHeaders(extra)?.["authorization"]; - return token ? { distinctId: await resolveUserId(token) } : null; - }, - }); - server.registerTool("...", {/* ... */}, async () => { - /* ... */ - }); + instrument(server, posthog, { + captureModel: true, + enableConversationId: true, + identify: async (request, extra) => { + const token = getRequestHeaders(extra)?.["authorization"]; + return token ? { distinctId: await resolveUserId(token) } : null; + }, + }); + server.registerTool( + "...", + { + /* ... */ + }, + async () => { + /* ... */ + }, + ); }); ``` @@ -195,8 +202,8 @@ const handler = createMcpHandler((server) => { import { PostHogMCP } from "@posthog/mcp"; const posthog = new PostHogMCP(process.env.POSTHOG_PROJECT_TOKEN, { - host: process.env.VITE_POSTHOG_HOST, - captureModel: true, + host: process.env.VITE_POSTHOG_HOST, + captureModel: true, }); // when building the tools/list response: @@ -204,30 +211,36 @@ const serverTools = getServerTools(); const advertisedTools = posthog.prepareToolList(serverTools); // only on a 2025-11-25 initialize handshake: -posthog.captureInitialize({ clientName, clientVersion, distinctId, protocolVersion: "2025-11-25" }); +posthog.captureInitialize({ + clientName, + clientVersion, + distinctId, + protocolVersion: "2025-11-25", +}); // after each tools/call resolves (wrap the existing handler, time it): const start = Date.now(); -const originalTool = serverTools.find((tool) => tool.name === request.params.name); -const { args, intent, intentSource, llmModel, llmModelSource } = posthog.prepareToolCall( - request.params.name, - request.params.arguments, - { originalTool }, +const originalTool = serverTools.find( + (tool) => tool.name === request.params.name, ); +const { args, intent, intentSource, llmModel, llmModelSource } = + posthog.prepareToolCall(request.params.name, request.params.arguments, { + originalTool, + }); const result = await runTool(request.params.name, args); posthog.captureToolCall({ - toolName: request.params.name, - parameters: args, - response: result, - durationMs: Date.now() - start, - isError: false, - intent, - intentSource, - llmModel, - llmModelSource, - distinctId, // who the request is from, if known - sessionId, // your transport/session id, if you have one - protocolVersion, // read this from the current request + toolName: request.params.name, + parameters: args, + response: result, + durationMs: Date.now() - start, + isError: false, + intent, + intentSource, + llmModel, + llmModelSource, + distinctId, // who the request is from, if known + sessionId, // your transport/session id, if you have one + protocolVersion, // read this from the current request }); ``` @@ -243,19 +256,19 @@ import { McpModule } from "@rekog/mcp-nest"; import { PostHog, instrumentMutator } from "@posthog/mcp"; const posthog = new PostHog(process.env.POSTHOG_PROJECT_TOKEN, { - host: process.env.VITE_POSTHOG_HOST, + host: process.env.VITE_POSTHOG_HOST, }); @Module({ - imports: [ - McpModule.forRoot({ - name: "my-mcp-server", - version: "1.0.0", - serverMutator: instrumentMutator(posthog, { - enableConversationId: true, - }), - }), - ], + imports: [ + McpModule.forRoot({ + name: "my-mcp-server", + version: "1.0.0", + serverMutator: instrumentMutator(posthog, { + enableConversationId: true, + }), + }), + ], }) class AppModule {} ``` diff --git a/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/references/custom-events.md b/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/references/custom-events.md index 521e580..64ecde9 100644 --- a/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/references/custom-events.md +++ b/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/references/custom-events.md @@ -22,10 +22,10 @@ Pass a callback to attach extra properties to automatically captured MCP events. import { instrument, getRequestHeaders } from "@posthog/mcp"; const analytics = instrument(server, posthog, { - eventProperties: async (request, extra) => ({ - $app_version: process.env.GIT_SHA ?? "unknown", - request_id: getRequestHeaders(extra)?.["x-request-id"], - }), + eventProperties: async (request, extra) => ({ + $app_version: process.env.GIT_SHA ?? "unknown", + request_id: getRequestHeaders(extra)?.["x-request-id"], + }), }); ``` @@ -74,13 +74,13 @@ The returned object is spread flat onto the event's properties alongside the bui ```json { - "event": "$mcp_tool_call", - "properties": { - "$mcp_tool_name": "search_events", - "$app_version": "a1b2c3d", - "region": "iad", - "request_id": "req_…" - } + "event": "$mcp_tool_call", + "properties": { + "$mcp_tool_name": "search_events", + "$app_version": "a1b2c3d", + "region": "iad", + "request_id": "req_…" + } } ``` @@ -106,8 +106,8 @@ You name the event. It's sent verbatim – it's your event, so it is **not** `$` const analytics = instrument(server, posthog); await analytics.capture({ - event: "feedback_submitted", - properties: { rating: 5 }, + event: "feedback_submitted", + properties: { rating: 5 }, }); ``` diff --git a/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/references/events.md b/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/references/events.md index adb1dfb..70646f0 100644 --- a/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/references/events.md +++ b/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/references/events.md @@ -173,7 +173,10 @@ For product code that queries against the SDK's contract, the package exports: Use them instead of hard-coding strings so renames stay typesafe: ```typescript -import { PostHogMCPAnalyticsEvent, PostHogMCPAnalyticsProperty } from "@posthog/mcp"; +import { + PostHogMCPAnalyticsEvent, + PostHogMCPAnalyticsProperty, +} from "@posthog/mcp"; const event = PostHogMCPAnalyticsEvent.ToolCall; // "$mcp_tool_call" const key = PostHogMCPAnalyticsProperty.ToolName; // "$mcp_tool_name" diff --git a/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/references/identifying-users.md b/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/references/identifying-users.md index f3c10df..72c6c27 100644 --- a/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/references/identifying-users.md +++ b/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/references/identifying-users.md @@ -41,17 +41,17 @@ Events for sessions with **no** resolved identity are sent with `$process_person import { instrument, getRequestHeaders } from "@posthog/mcp"; instrument(server, posthog, { - identify: async (request, extra) => { - const token = getRequestHeaders(extra)?.["authorization"]; - if (!token) return null; - const user = await resolveUserFromToken(token); - if (!user) return null; - return { - distinctId: user.id, // becomes distinct_id - properties: { name: user.name, plan: user.plan }, // written to $set - groups: { organization: user.orgId }, // becomes $groups on every event - }; - }, + identify: async (request, extra) => { + const token = getRequestHeaders(extra)?.["authorization"]; + if (!token) return null; + const user = await resolveUserFromToken(token); + if (!user) return null; + return { + distinctId: user.id, // becomes distinct_id + properties: { name: user.name, plan: user.plan }, // written to $set + groups: { organization: user.orgId }, // becomes $groups on every event + }; + }, }); ``` diff --git a/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/references/intent.md b/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/references/intent.md index 7c07884..75c4cd3 100644 --- a/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/references/intent.md +++ b/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/references/intent.md @@ -30,15 +30,15 @@ What the agent sees in the schema: ```json { - "type": "object", - "properties": { - "context": { - "type": "string", - "description": "Explain in 15-25 words, in third person, why this tool is called and how it supports the user's goal. For analytics only. ..." - }, - "...": "your real tool arguments" - }, - "required": ["context", "..."] + "type": "object", + "properties": { + "context": { + "type": "string", + "description": "Explain in 15-25 words, in third person, why this tool is called and how it supports the user's goal. For analytics only. ..." + }, + "...": "your real tool arguments" + }, + "required": ["context", "..."] } ``` @@ -62,10 +62,10 @@ If you want to nudge the agent toward a specific style of context (use case, use ```typescript instrument(server, posthog, { - context: { - description: - "Describe the user's underlying goal in one sentence, not the tool you're calling.", - }, + context: { + description: + "Describe the user's underlying goal in one sentence, not the tool you're calling.", + }, }); ``` @@ -112,12 +112,12 @@ Use a synchronous callback when you can derive intent from the tool name and arg ```typescript instrument(server, posthog, { - intentFallback: (request) => { - const tool = request.params?.name; - const args = request.params?.arguments ?? {}; - if (tool === "search_events") return `Searching events for "${args.query}"`; - return tool ? `Invoking ${tool}` : null; - }, + intentFallback: (request) => { + const tool = request.params?.name; + const args = request.params?.arguments ?? {}; + if (tool === "search_events") return `Searching events for "${args.query}"`; + return tool ? `Invoking ${tool}` : null; + }, }); ``` @@ -145,8 +145,8 @@ instrument(server, posthog, MCPAnalyticsOptions(intent_fallback=intent_fallback) import { getRequestHeaders } from "@posthog/mcp"; intentFallback: (request, extra) => { - const ua = getRequestHeaders(extra)?.["user-agent"]; - return `${ua ?? "unknown client"} invoked ${request.params?.name}`; + const ua = getRequestHeaders(extra)?.["user-agent"]; + return `${ua ?? "unknown client"} invoked ${request.params?.name}`; }; ``` @@ -158,11 +158,11 @@ An LLM call in `intentFallback` adds latency to each tool call that lacks contex ```typescript intentFallback: async (request) => { - try { - return await summariseIntent(request.params); - } catch { - return null; // the SDK swallows null gracefully - } + try { + return await summariseIntent(request.params); + } catch { + return null; // the SDK swallows null gracefully + } }; ``` diff --git a/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/references/start-here.md b/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/references/start-here.md index 9d6c427..7800b7f 100644 --- a/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/references/start-here.md +++ b/.posthog/wizard-spellbook-3Pm3hv/skills/mcp-analytics/references/start-here.md @@ -68,14 +68,14 @@ import { PostHog } from "posthog-node"; import { instrument } from "@posthog/mcp"; const posthog = new PostHog(process.env.POSTHOG_PROJECT_TOKEN, { - host: "https://us.i.posthog.com", // or https://eu.i.posthog.com + host: "https://us.i.posthog.com", // or https://eu.i.posthog.com }); instrument(server, posthog); process.on("SIGTERM", async () => { - await posthog.shutdown(); - process.exit(0); + await posthog.shutdown(); + process.exit(0); }); ``` @@ -157,10 +157,10 @@ To inspect, change, or drop events before they're sent, add a before-send hook. ```typescript instrument(server, posthog, { - beforeSend: (event) => { - delete event.properties.$mcp_response; // keep tool results out of PostHog - return event; - }, + beforeSend: (event) => { + delete event.properties.$mcp_response; // keep tool results out of PostHog + return event; + }, }); ``` @@ -250,10 +250,12 @@ By default, each event uses an SDK-generated session ID. Add an identify callbac import { instrument, getRequestHeaders } from "@posthog/mcp"; instrument(server, posthog, { - identify: async (request, extra) => { - const user = await resolveUser(getRequestHeaders(extra)?.["authorization"]); - return user ? { distinctId: user.id, properties: { plan: user.plan } } : null; - }, + identify: async (request, extra) => { + const user = await resolveUser(getRequestHeaders(extra)?.["authorization"]); + return user + ? { distinctId: user.id, properties: { plan: user.plan } } + : null; + }, }); ``` diff --git a/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/SKILL.md b/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/SKILL.md index b63c7e2..f86d7ba 100644 --- a/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/SKILL.md +++ b/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/SKILL.md @@ -1,4 +1,5 @@ --- + name: integration-sveltekit description: PostHog integration for SvelteKit applications metadata: diff --git a/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/references/1-begin.md b/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/references/1-begin.md index 8032d89..3ef7552 100644 --- a/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/references/1-begin.md +++ b/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/references/1-begin.md @@ -1,4 +1,5 @@ --- + title: PostHog Setup - Begin description: Start the event tracking setup process by analyzing the project and creating an event tracking plan --- diff --git a/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/references/2-edit.md b/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/references/2-edit.md index 506ec78..a8305c1 100644 --- a/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/references/2-edit.md +++ b/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/references/2-edit.md @@ -1,4 +1,5 @@ --- + title: PostHog Setup - Edit description: Implement PostHog event tracking in the identified files, following best practices and the example project --- diff --git a/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/references/3-revise.md b/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/references/3-revise.md index a5910bf..dd4acb1 100644 --- a/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/references/3-revise.md +++ b/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/references/3-revise.md @@ -1,4 +1,5 @@ --- + title: PostHog Setup - Revise description: Review and fix any errors in the PostHog integration implementation --- diff --git a/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/references/4-conclude.md b/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/references/4-conclude.md index 3d57f5d..ddc93ef 100644 --- a/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/references/4-conclude.md +++ b/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/references/4-conclude.md @@ -1,4 +1,5 @@ --- + title: PostHog Setup - Conclusion description: Review and fix any errors in the PostHog integration implementation --- @@ -30,9 +31,9 @@ Create the parent dashboard first with `dashboard-create`, capture its returned ```json { - "name": "Analytics basics (wizard)", - "description": "Key views for the events instrumented by the PostHog wizard.", - "tags": ["wizard"] + "name": "Analytics basics (wizard)", + "description": "Key views for the events instrumented by the PostHog wizard.", + "tags": ["wizard"] } ``` diff --git a/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/references/EXAMPLE.md b/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/references/EXAMPLE.md index 0d48c3c..cae2b70 100644 --- a/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/references/EXAMPLE.md +++ b/.posthog/wizard-spellbook-WsJDnA/skills/integration-sveltekit/references/EXAMPLE.md @@ -88,12 +88,12 @@ PostHog is initialized in the SvelteKit client hooks `init` function, which runs import posthog from "posthog-js"; export async function init() { - posthog.init(PUBLIC_POSTHOG_PROJECT_TOKEN, { - api_host: "/ingest", - ui_host: "https://us.posthog.com", - defaults: "2026-01-30", - capture_exceptions: true, - }); + posthog.init(PUBLIC_POSTHOG_PROJECT_TOKEN, { + api_host: "/ingest", + ui_host: "https://us.posthog.com", + defaults: "2026-01-30", + capture_exceptions: true, + }); } ``` @@ -107,14 +107,14 @@ import { PostHog } from "posthog-node"; let posthogClient: PostHog | null = null; export function getPostHogClient() { - if (!posthogClient) { - posthogClient = new PostHog(PUBLIC_POSTHOG_PROJECT_TOKEN, { - host: PUBLIC_VITE_POSTHOG_HOST, - flushAt: 1, - flushInterval: 0, - }); - } - return posthogClient; + if (!posthogClient) { + posthogClient = new PostHog(PUBLIC_POSTHOG_PROJECT_TOKEN, { + host: PUBLIC_VITE_POSTHOG_HOST, + flushAt: 1, + flushInterval: 0, + }); + } + return posthogClient; } ``` @@ -124,14 +124,14 @@ The server hooks handle proxies requests through `/ingest` to avoid ad blockers: ```typescript export const handle: Handle = async ({ event, resolve }) => { - if (event.url.pathname.startsWith("/ingest")) { - const pathname = event.url.pathname.replace("/ingest", ""); - const host = pathname.startsWith("/static") - ? "https://us-assets.i.posthog.com" - : "https://us.i.posthog.com"; - // Proxy to PostHog... - } - return resolve(event); + if (event.url.pathname.startsWith("/ingest")) { + const pathname = event.url.pathname.replace("/ingest", ""); + const host = pathname.startsWith("/static") + ? "https://us-assets.i.posthog.com" + : "https://us.i.posthog.com"; + // Proxy to PostHog... + } + return resolve(event); }; ``` @@ -157,8 +157,8 @@ Errors are automatically captured via the `handleError` hook: ```typescript export const handleError: HandleClientError = async ({ error }) => { - posthog.captureException(error); - return { message: "An error occurred" }; + posthog.captureException(error); + return { message: "An error occurred" }; }; ``` @@ -166,9 +166,9 @@ You can also manually capture errors: ```typescript try { - // Some operation + // Some operation } catch (err) { - posthog.captureException(err); + posthog.captureException(err); } ``` @@ -178,11 +178,11 @@ For session replay to work correctly, add this to `svelte.config.js`: ```javascript export default { - kit: { - paths: { - relative: false, - }, - }, + kit: { + paths: { + relative: false, + }, + }, }; ``` @@ -228,13 +228,13 @@ min-release-age=7 // See https://svelte.dev/docs/kit/types#app.d.ts // for information about these interfaces declare global { - namespace App { - // interface Error {} - // interface Locals {} - // interface PageData {} - // interface PageState {} - // interface Platform {} - } + namespace App { + // interface Error {} + // interface Locals {} + // interface PageData {} + // interface PageState {} + // interface Platform {} + } } export {}; @@ -269,22 +269,26 @@ import type { HandleClientError } from "@sveltejs/kit"; // Initialize PostHog when the app starts in the browser export async function init() { - posthog.init(PUBLIC_POSTHOG_PROJECT_TOKEN, { - api_host: "/ingest", - ui_host: "https://us.posthog.com", - defaults: "2026-01-30", - capture_exceptions: true, - }); + posthog.init(PUBLIC_POSTHOG_PROJECT_TOKEN, { + api_host: "/ingest", + ui_host: "https://us.posthog.com", + defaults: "2026-01-30", + capture_exceptions: true, + }); } // Capture client-side errors with PostHog -export const handleError: HandleClientError = async ({ error, status, message }) => { - posthog.captureException(error); - - return { - message, - status, - }; +export const handleError: HandleClientError = async ({ + error, + status, + message, +}) => { + posthog.captureException(error); + + return { + message, + status, + }; }; ``` @@ -294,68 +298,76 @@ export const handleError: HandleClientError = async ({ error, status, message }) ```ts import type { Handle, HandleServerError } from "@sveltejs/kit"; -import { getPostHogClient } from "$lib/server/posthog"; +import { getPostHogClient } from "#lib/server/posthog"; // Handle requests - includes reverse proxy for PostHog export const handle: Handle = async ({ event, resolve }) => { - const { pathname } = event.url; - - // Reverse proxy for PostHog - route /ingest requests to PostHog servers - if (pathname.startsWith("/ingest")) { - const useAssetHost = - pathname.startsWith("/ingest/static/") || pathname.startsWith("/ingest/array/"); - const hostname = useAssetHost ? "us-assets.i.posthog.com" : "us.i.posthog.com"; - - const url = new URL(event.request.url); - url.protocol = "https:"; - url.hostname = hostname; - url.port = "443"; - url.pathname = pathname.replace(/^\/ingest/, ""); - - const headers = new Headers(event.request.headers); - headers.set("host", hostname); - headers.set("accept-encoding", ""); - - const clientIp = event.request.headers.get("x-forwarded-for") || event.getClientAddress(); - if (clientIp) { - headers.set("x-forwarded-for", clientIp); - } - - const response = await fetch(url.toString(), { - method: event.request.method, - headers, - body: event.request.body, - // @ts-expect-error - duplex is required for streaming request bodies - duplex: "half", - }); - - return response; - } - - return resolve(event); + const { pathname } = event.url; + + // Reverse proxy for PostHog - route /ingest requests to PostHog servers + if (pathname.startsWith("/ingest")) { + const useAssetHost = + pathname.startsWith("/ingest/static/") || + pathname.startsWith("/ingest/array/"); + const hostname = useAssetHost + ? "us-assets.i.posthog.com" + : "us.i.posthog.com"; + + const url = new URL(event.request.url); + url.protocol = "https:"; + url.hostname = hostname; + url.port = "443"; + url.pathname = pathname.replace(/^\/ingest/, ""); + + const headers = new Headers(event.request.headers); + headers.set("host", hostname); + headers.set("accept-encoding", ""); + + const clientIp = + event.request.headers.get("x-forwarded-for") || event.getClientAddress(); + if (clientIp) { + headers.set("x-forwarded-for", clientIp); + } + + const response = await fetch(url.toString(), { + method: event.request.method, + headers, + body: event.request.body, + // @ts-expect-error - duplex is required for streaming request bodies + duplex: "half", + }); + + return response; + } + + return resolve(event); }; // Capture server-side errors with PostHog -export const handleError: HandleServerError = async ({ error, status, message }) => { - const posthog = getPostHogClient(); - - posthog.capture({ - distinctId: "server", - event: "server_error", - properties: { - error: error instanceof Error ? error.message : String(error), - status, - message, - }, - }); - - // handleError runs per request; flush so the enqueued event sends before it returns - await posthog.flush(); - - return { - message, - status, - }; +export const handleError: HandleServerError = async ({ + error, + status, + message, +}) => { + const posthog = getPostHogClient(); + + posthog.capture({ + distinctId: "server", + event: "server_error", + properties: { + error: error instanceof Error ? error.message : String(error), + status, + message, + }, + }); + + // handleError runs per request; flush so the enqueued event sends before it returns + await posthog.flush(); + + return { + message, + status, + }; }; ``` @@ -369,8 +381,8 @@ import posthog from "posthog-js"; import { browser } from "$app/environment"; export interface User { - username: string; - burritoConsiderations: number; + username: string; + burritoConsiderations: number; } const AUTH_KEY = Symbol("auth"); @@ -378,70 +390,70 @@ const AUTH_KEY = Symbol("auth"); // Class-based auth state using Svelte 5 $state in class fields // This is the recommended pattern for encapsulating reactive state + behavior export class AuthState { - user = $state(null); - - constructor() { - // Restore user from localStorage on creation (browser only) - if (browser) { - const storedUsername = localStorage.getItem("currentUser"); - if (storedUsername) { - this.user = { username: storedUsername, burritoConsiderations: 0 }; - } - } - } - - login = async (username: string, password: string): Promise => { - try { - const response = await fetch("/api/auth/login", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ username, password }), - }); - - if (response.ok) { - const { user: userData } = await response.json(); - this.user = userData as User; - - if (browser) { - localStorage.setItem("currentUser", username); - posthog.identify(username, { username }); - posthog.capture("user_logged_in", { username }); - } - - return true; - } - return false; - } catch (error) { - console.error("Login error:", error); - return false; - } - }; - - logout = (): void => { - if (browser) { - posthog.capture("user_logged_out"); - posthog.reset(); - localStorage.removeItem("currentUser"); - } - this.user = null; - }; - - incrementBurritoConsiderations = (): void => { - if (this.user) { - this.user = { - ...this.user, - burritoConsiderations: this.user.burritoConsiderations + 1, - }; - } - }; + user = $state(null); + + constructor() { + // Restore user from localStorage on creation (browser only) + if (browser) { + const storedUsername = localStorage.getItem("currentUser"); + if (storedUsername) { + this.user = { username: storedUsername, burritoConsiderations: 0 }; + } + } + } + + login = async (username: string, password: string): Promise => { + try { + const response = await fetch("/api/auth/login", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ username, password }), + }); + + if (response.ok) { + const { user: userData } = await response.json(); + this.user = userData as User; + + if (browser) { + localStorage.setItem("currentUser", username); + posthog.identify(username, { username }); + posthog.capture("user_logged_in", { username }); + } + + return true; + } + return false; + } catch (error) { + console.error("Login error:", error); + return false; + } + }; + + logout = (): void => { + if (browser) { + posthog.capture("user_logged_out"); + posthog.reset(); + localStorage.removeItem("currentUser"); + } + this.user = null; + }; + + incrementBurritoConsiderations = (): void => { + if (this.user) { + this.user = { + ...this.user, + burritoConsiderations: this.user.burritoConsiderations + 1, + }; + } + }; } export function setAuthContext(auth: AuthState) { - setContext(AUTH_KEY, auth); + setContext(AUTH_KEY, auth); } export function getAuthContext(): AuthState { - return getContext(AUTH_KEY); + return getContext(AUTH_KEY); } ``` @@ -451,7 +463,7 @@ export function getAuthContext(): AuthState { ```svelte @@ -481,7 +493,7 @@ export function getAuthContext(): AuthState { ## src/lib/index.ts ```ts -// place files you want to import through the `$lib` alias in this folder. +// place files you want to import through the `#lib` alias in this folder. ``` --- @@ -494,20 +506,20 @@ import { PostHog } from "posthog-node"; let posthogClient: PostHog | null = null; export function getPostHogClient() { - if (!posthogClient) { - posthogClient = new PostHog(process.env.VITE_POSTHOG_PROJECT_TOKEN!, { - host: process.env.VITE_VITE_POSTHOG_HOST!, - flushAt: 1, - flushInterval: 0, - }); - } - return posthogClient; + if (!posthogClient) { + posthogClient = new PostHog(process.env.VITE_POSTHOG_PROJECT_TOKEN!, { + host: process.env.VITE_VITE_POSTHOG_HOST!, + flushAt: 1, + flushInterval: 0, + }); + } + return posthogClient; } export async function shutdownPostHog() { - if (posthogClient) { - await posthogClient.shutdown(); - } + if (posthogClient) { + await posthogClient.shutdown(); + } } ``` @@ -517,8 +529,8 @@ export async function shutdownPostHog() { ```svelte + {/if} + + + + {mediaType} + + + + {#if activeTab === "upload"} + +
+ void handleFiles(e.currentTarget.files)} + class="hidden" + /> + + {#if isUploading} +
+ + {uploadStatus} +
+ {:else} +
+ + + + + +
+ {#if mediaType === "video"} +
+ +
+ +
+
+ +
+ + Click to upload {mediaType} + + or drag and drop +
+ +

Maximum 3 files, {mediaConstraint.label} each.

+ {/if}
{:else} - -
- - - - - - - -
- {#if mediaType === "video"} -
diff --git a/src/lib/components/edra/shadcn/components/Mermaid.svelte b/src/lib/components/edra/shadcn/components/Mermaid.svelte index 017fc06..6411617 100644 --- a/src/lib/components/edra/shadcn/components/Mermaid.svelte +++ b/src/lib/components/edra/shadcn/components/Mermaid.svelte @@ -1,15 +1,15 @@ diff --git a/src/lib/components/edra/shadcn/toc.ts b/src/lib/components/edra/shadcn/toc.ts index be45fdc..8a84392 100644 --- a/src/lib/components/edra/shadcn/toc.ts +++ b/src/lib/components/edra/shadcn/toc.ts @@ -1 +1 @@ -export { getTocItems, setTocItems } from "./toc.state.svelte.js"; +export { getTocItems, setTocItems } from "./toc.state.svelte"; diff --git a/src/lib/components/edra/strings.ts b/src/lib/components/edra/strings.ts index 0e8fddc..11668fc 100644 --- a/src/lib/components/edra/strings.ts +++ b/src/lib/components/edra/strings.ts @@ -1,2 +1,2 @@ // Re-export from the split strings module -export { default } from "./strings/index.js"; +export { default } from "./strings/index"; diff --git a/src/lib/components/edra/strings/commands.ts b/src/lib/components/edra/strings/commands.ts index 1de6d3b..28eebbb 100644 --- a/src/lib/components/edra/strings/commands.ts +++ b/src/lib/components/edra/strings/commands.ts @@ -1,37 +1,38 @@ export const commandStrings = { - undo: "Undo", - redo: "Redo", - h1: "Heading 1", - h2: "Heading 2", - h3: "Heading 3", - h4: "Heading 4", - link: "Link", - paragraph: "Paragraph", - bold: "Bold", - italic: "Italic", - underline: "Underline", - strikethrough: "Strikethrough", - blockQuote: "BlockQuote", - code: "Inline Code", - codeBlock: "Code Block", - superscript: "Superscript", - subscript: "Subscript", - alignLeft: "Align Left", - alignCenter: "Align Center", - alignRight: "Align Right", - alignJustify: "Align Justify", - bulletList: "Bullet List", - orderedList: "Ordered List", - taskList: "Task List", - imagePlaceholder: "Image Placeholder", - videoPlaceholder: "Video Placeholder", - audioPlaceholder: "Audio Placeholder", - iframePlaceholder: "Iframe Placeholder", - table: "Table", - inlineExpression: "Inline Expression", - blockExpression: "Block Expression", - horizontalRule: "Horizontal Rule", - mermaidDiagram: "Mermaid Diagram", - formatGroup: "Format", - insertGroup: "Insert", + undo: "Undo", + redo: "Redo", + h1: "Heading 1", + h2: "Heading 2", + h3: "Heading 3", + h4: "Heading 4", + link: "Link", + paragraph: "Paragraph", + bold: "Bold", + italic: "Italic", + underline: "Underline", + strikethrough: "Strikethrough", + blockQuote: "BlockQuote", + code: "Inline Code", + codeBlock: "Code Block", + superscript: "Superscript", + subscript: "Subscript", + alignLeft: "Align Left", + alignCenter: "Align Center", + alignRight: "Align Right", + alignJustify: "Align Justify", + bulletList: "Bullet List", + orderedList: "Ordered List", + taskList: "Task List", + imagePlaceholder: "Image Placeholder", + videoPlaceholder: "Video Placeholder", + audioPlaceholder: "Audio Placeholder", + iframePlaceholder: "Iframe Placeholder", + youtubePlaceholder: "YouTube Video", + table: "Table", + inlineExpression: "Inline Expression", + blockExpression: "Block Expression", + horizontalRule: "Horizontal Rule", + mermaidDiagram: "Mermaid Diagram", + formatGroup: "Format", + insertGroup: "Insert", }; diff --git a/src/lib/components/edra/strings/editor.ts b/src/lib/components/edra/strings/editor.ts index 2c7be69..816f956 100644 --- a/src/lib/components/edra/strings/editor.ts +++ b/src/lib/components/edra/strings/editor.ts @@ -1,16 +1,16 @@ export const dragHandleStrings = { - title: "Drag Handle", - turnInto: "Turn into", - insertNext: "Insert Next", - removeFormatting: "Remove Formatting", - duplicate: "Duplicate", - copy: "Copy", - delete: "Delete Node", + title: "Drag Handle", + turnInto: "Turn into", + insertNext: "Insert Next", + removeFormatting: "Remove Formatting", + duplicate: "Duplicate", + copy: "Copy", + delete: "Delete Node", }; export const editorStrings = { - headingPlaceholder: "What's the title?", - paragraphPlaceholder: "Write, press space for AI or / for commands", - contentErrorTitle: "Unable to load the content", - contentErrorDescription: "The content of this page might be corrupted.", + headingPlaceholder: "What's the title?", + paragraphPlaceholder: "Write, press space for AI or / for commands", + contentErrorTitle: "Unable to load the content", + contentErrorDescription: "The content of this page might be corrupted.", }; diff --git a/src/lib/components/edra/strings/extensions.ts b/src/lib/components/edra/strings/extensions.ts index 27b5a9e..cc5d017 100644 --- a/src/lib/components/edra/strings/extensions.ts +++ b/src/lib/components/edra/strings/extensions.ts @@ -1,106 +1,106 @@ export const audioStrings = { - multiplePasteWarningTitle: "Can not paste multiple files at once!", - multiplePasteWarningDescription: - "You can only paste one file at a time. Only the first file will be pasted.", - pasteProcessing: "Processing Pasted Audio", - pasteError: "Could not paste audio", - multipleDropWarningTitle: "Can not drop multiple files at once!", - multipleDropWarningDescription: - "You can only drop one file at a time. Only the first file will be dropped.", - dropProcessing: "Processing Dropped Audio", - dropError: "Could not upload audio", - enterURLPrompt: "Enter Audio URL", - insertPlaceholder: "Insert an audio", - uploadProcessing: "Uploading Audio File", - openButton: "Open", - openError: "Could not process audio files.", - uploadTab: "Upload", - embedLinkTab: "Embed Link", - uploadButton: "Upload Audio", - embedLinkButton: "Insert", - embedLinkPlaceholder: "Embed Audio", + multiplePasteWarningTitle: "Can not paste multiple files at once!", + multiplePasteWarningDescription: + "You can only paste one file at a time. Only the first file will be pasted.", + pasteProcessing: "Processing Pasted Audio", + pasteError: "Could not paste audio", + multipleDropWarningTitle: "Can not drop multiple files at once!", + multipleDropWarningDescription: + "You can only drop one file at a time. Only the first file will be dropped.", + dropProcessing: "Processing Dropped Audio", + dropError: "Could not upload audio", + enterURLPrompt: "Enter Audio URL", + insertPlaceholder: "Insert an audio", + uploadProcessing: "Uploading Audio File", + openButton: "Open", + openError: "Could not process audio files.", + uploadTab: "Upload", + embedLinkTab: "Embed Link", + uploadButton: "Upload Audio", + embedLinkButton: "Insert", + embedLinkPlaceholder: "Embed Audio", }; export const codeStrings = { - copy: "Copy", - copied: "Copied!", - plainText: "Plain Text", - searchLanguagePlaceholder: "Search language...", - searchLanguageEmpty: "No Language found.", + copy: "Copy", + copied: "Copied!", + plainText: "Plain Text", + searchLanguagePlaceholder: "Search language...", + searchLanguageEmpty: "No Language found.", }; export const iframeStrings = { - enterURLPrompt: "Please enter the iframe URL", - insertPlaceholder: "Insert an iframe", - openButton: "Open", - embedLinkPlaceholder: "Embed Iframe", - embedLinkButton: "Insert", + enterURLPrompt: "Please enter the iframe URL", + insertPlaceholder: "Insert an iframe", + openButton: "Open", + embedLinkPlaceholder: "Embed Iframe", + embedLinkButton: "Insert", }; export const imageStrings = { - enterURLPrompt: "Please enter the image URL", - insertPlaceholder: "Insert an image", - uploadProcessing: "Uploading Image File", - openButton: "Open", - openError: "Could not process image files.", - uploadTab: "Upload", - embedLinkTab: "Embed Link", - uploadButton: "Upload Image", - embedLinkButton: "Insert", - embedLinkPlaceholder: "Embed Image", + enterURLPrompt: "Please enter the image URL", + insertPlaceholder: "Insert an image", + uploadProcessing: "Uploading Image File", + openButton: "Open", + openError: "Could not process image files.", + uploadTab: "Upload", + embedLinkTab: "Embed Link", + uploadButton: "Upload Image", + embedLinkButton: "Insert", + embedLinkPlaceholder: "Embed Image", }; export const mediaStrings = { - back: "Back", - resizeLeft: "Resize Left", - resizeRight: "Resize Right", - alignLeft: "Align Left", - alignCenter: "Align Center", - alignRight: "Align Right", - moreOptions: "More Options", - caption: "Caption", - captionPlaceholder: "Your Media Caption", - duplicate: "Duplicate", - fullscreen: "Full Screen", - delete: "Delete", - link: "Link", - removeLink: "Remove Link", - openLink: "Open Link", + back: "Back", + resizeLeft: "Resize Left", + resizeRight: "Resize Right", + alignLeft: "Align Left", + alignCenter: "Align Center", + alignRight: "Align Right", + moreOptions: "More Options", + caption: "Caption", + captionPlaceholder: "Your Media Caption", + duplicate: "Duplicate", + fullscreen: "Full Screen", + delete: "Delete", + link: "Link", + removeLink: "Remove Link", + openLink: "Open Link", }; export const tableStrings = { - selectCell: "Select Cell", - selectRow: "Select Row", - addRow: "Add Row", - addRowAfter: "Add Row After", - addRowBefore: "Add Row Before", - deleteRow: "Delete Row", - selectColumn: "Select Column", - addColumn: "Add Column", - addColumnAfter: "Add Column After", - addColumnBefore: "Add Column Before", - deleteColumn: "Delete Column", + selectCell: "Select Cell", + selectRow: "Select Row", + addRow: "Add Row", + addRowAfter: "Add Row After", + addRowBefore: "Add Row Before", + deleteRow: "Delete Row", + selectColumn: "Select Column", + addColumn: "Add Column", + addColumnAfter: "Add Column After", + addColumnBefore: "Add Column Before", + deleteColumn: "Delete Column", }; export const videoStrings = { - multiplePasteWarningTitle: "Can not paste multiple files at once!", - multiplePasteWarningDescription: - "You can only paste one file at a time. Only the first file will be pasted.", - pasteProcessing: "Processing Pasted Video", - pasteError: "Could not handle pasted video", - multipleDropWarningTitle: "Can not drop multiple files at once!", - multipleDropWarningDescription: - "You can only drop one file at a time. Only the first file will be processed.", - dropProcessing: "Processing Dropped Video", - dropError: "Could not upload video", - enterURLPrompt: "Please enter the video URL", - insertPlaceholder: "Insert a video", - uploadProcessing: "Uploading Video", - openButton: "Open", - openError: "Could not process video files.", - uploadTab: "Upload", - embedLinkTab: "Embed Link", - uploadButton: "Upload Video", - embedLinkButton: "Insert", - embedLinkPlaceholder: "Embed Video", + multiplePasteWarningTitle: "Can not paste multiple files at once!", + multiplePasteWarningDescription: + "You can only paste one file at a time. Only the first file will be pasted.", + pasteProcessing: "Processing Pasted Video", + pasteError: "Could not handle pasted video", + multipleDropWarningTitle: "Can not drop multiple files at once!", + multipleDropWarningDescription: + "You can only drop one file at a time. Only the first file will be processed.", + dropProcessing: "Processing Dropped Video", + dropError: "Could not upload video", + enterURLPrompt: "Please enter the video URL", + insertPlaceholder: "Insert a video", + uploadProcessing: "Uploading Video", + openButton: "Open", + openError: "Could not process video files.", + uploadTab: "Upload", + embedLinkTab: "Embed Link", + uploadButton: "Upload Video", + embedLinkButton: "Insert", + embedLinkPlaceholder: "Embed Video", }; diff --git a/src/lib/components/edra/strings/index.ts b/src/lib/components/edra/strings/index.ts index 5c1b358..6312541 100644 --- a/src/lib/components/edra/strings/index.ts +++ b/src/lib/components/edra/strings/index.ts @@ -1,31 +1,31 @@ -import { commandStrings } from "./commands.js"; -import { dragHandleStrings, editorStrings } from "./editor.js"; +import { commandStrings } from "./commands"; +import { dragHandleStrings, editorStrings } from "./editor"; import { - audioStrings, - codeStrings, - iframeStrings, - imageStrings, - mediaStrings, - tableStrings, - videoStrings, -} from "./extensions.js"; -import { menuStrings, toolbarStrings } from "./menu-toolbar.js"; + audioStrings, + codeStrings, + iframeStrings, + imageStrings, + mediaStrings, + tableStrings, + videoStrings, +} from "./extensions"; +import { menuStrings, toolbarStrings } from "./menu-toolbar"; const strings = { - command: commandStrings, - dragHandle: dragHandleStrings, - editor: editorStrings, - extension: { - audio: audioStrings, - code: codeStrings, - iframe: iframeStrings, - image: imageStrings, - media: mediaStrings, - table: tableStrings, - video: videoStrings, - }, - menu: menuStrings, - toolbar: toolbarStrings, + command: commandStrings, + dragHandle: dragHandleStrings, + editor: editorStrings, + extension: { + audio: audioStrings, + code: codeStrings, + iframe: iframeStrings, + image: imageStrings, + media: mediaStrings, + table: tableStrings, + video: videoStrings, + }, + menu: menuStrings, + toolbar: toolbarStrings, }; export default strings; diff --git a/src/lib/components/edra/strings/menu-toolbar.ts b/src/lib/components/edra/strings/menu-toolbar.ts index 5d226b0..004cac8 100644 --- a/src/lib/components/edra/strings/menu-toolbar.ts +++ b/src/lib/components/edra/strings/menu-toolbar.ts @@ -1,90 +1,90 @@ export const menuStrings = { - link: { - open: "Open Link", - edit: "Edit Link", - copy: "Copy Link", - remove: "Remove Link", - save: "Save", - enterLinkPlaceholder: "Type or paste a link", - enterLinkButton: "Set new link", - }, - math: { - enterExpressionPlaceholder: "Enter Math Expression", - }, - table: { - headerColumn: "Header Column", - addColumnAfter: "Add Column After", - addColumnBefore: "Add Column Before", - moveColumnLeft: "Move Column Left", - moveColumnRight: "Move Column Right", - deleteColumn: "Delete This Column", - headerRow: "Header Row", - addRowAfter: "Add Row After", - addRowBefore: "Add Row Before", - moveRowUp: "Move Row Up", - moveRowDown: "Move Row Down", - deleteRow: "Delete This Row", - }, + link: { + open: "Open Link", + edit: "Edit Link", + copy: "Copy Link", + remove: "Remove Link", + save: "Save", + enterLinkPlaceholder: "Type or paste a link", + enterLinkButton: "Set new link", + }, + math: { + enterExpressionPlaceholder: "Enter Math Expression", + }, + table: { + headerColumn: "Header Column", + addColumnAfter: "Add Column After", + addColumnBefore: "Add Column Before", + moveColumnLeft: "Move Column Left", + moveColumnRight: "Move Column Right", + deleteColumn: "Delete This Column", + headerRow: "Header Row", + addRowAfter: "Add Row After", + addRowBefore: "Add Row Before", + moveRowUp: "Move Row Up", + moveRowDown: "Move Row Down", + deleteRow: "Delete This Row", + }, }; export const toolbarStrings = { - alignment: { - buttonTitle: "Alignment", - dropdownTitle: "Alignments", - }, - color: { - buttonTitle: "Quick Colors", - textColor: "Text Color", - textColors: "Text Colors", - highlightColor: "Highlight Color", - highlightColors: "Highlight Colors", - templateCharacter: "A", - default: "Default", - blue: "Blue", - red: "Red", - brown: "Brown", - green: "Green", - gray: "Gray", - orange: "Orange", - pink: "Pink", - purple: "Purple", - yellow: "Yellow", - }, - font: { - buttonTitle: "Font Size", - dropdownTitle: "Font Size", - tiny: "Tiny", - smaller: "Smaller", - small: "Small", - default: "Default", - large: "Large", - extraLarge: "Extra Large", - }, - heading: { - buttonTitle: "Headings", - }, - link: { - buttonTitle: "Link", - insertLinkPlaceholder: "Insert Link", - insertLink: "Insert Link", - }, - list: { - buttonTitle: "Lists", - dropdownTitle: "Lists", - }, - searchAndReplace: { - buttonTitle: "Search and Replace", - showMore: "Show More", - goBack: "Go Back", - searchAndReplace: "Search and Replace", - searchPlaceholder: "Search...", - caseSensitive: "Case Sensitive", - goToPrevious: "Go to Previous", - goToNext: "Go to Next", - previous: "Previous", - next: "Next", - replacePlaceholder: "Replace...", - replace: "Replace", - replaceAll: "Replace All", - }, + alignment: { + buttonTitle: "Alignment", + dropdownTitle: "Alignments", + }, + color: { + buttonTitle: "Quick Colors", + textColor: "Text Color", + textColors: "Text Colors", + highlightColor: "Highlight Color", + highlightColors: "Highlight Colors", + templateCharacter: "A", + default: "Default", + blue: "Blue", + red: "Red", + brown: "Brown", + green: "Green", + gray: "Gray", + orange: "Orange", + pink: "Pink", + purple: "Purple", + yellow: "Yellow", + }, + font: { + buttonTitle: "Font Size", + dropdownTitle: "Font Size", + tiny: "Tiny", + smaller: "Smaller", + small: "Small", + default: "Default", + large: "Large", + extraLarge: "Extra Large", + }, + heading: { + buttonTitle: "Headings", + }, + link: { + buttonTitle: "Link", + insertLinkPlaceholder: "Insert Link", + insertLink: "Insert Link", + }, + list: { + buttonTitle: "Lists", + dropdownTitle: "Lists", + }, + searchAndReplace: { + buttonTitle: "Search and Replace", + showMore: "Show More", + goBack: "Go Back", + searchAndReplace: "Search and Replace", + searchPlaceholder: "Search...", + caseSensitive: "Case Sensitive", + goToPrevious: "Go to Previous", + goToNext: "Go to Next", + previous: "Previous", + next: "Next", + replacePlaceholder: "Replace...", + replace: "Replace", + replaceAll: "Replace All", + }, }; diff --git a/src/lib/components/edra/tiptap/Editor.ts b/src/lib/components/edra/tiptap/Editor.ts index aeecdb4..b7c2d72 100644 --- a/src/lib/components/edra/tiptap/Editor.ts +++ b/src/lib/components/edra/tiptap/Editor.ts @@ -3,50 +3,52 @@ import { Editor as CoreEditor } from "@tiptap/core"; import type { EditorState, Plugin, PluginKey } from "@tiptap/pm/state"; export class Editor extends CoreEditor { - public reactiveState: EditorState = this.view.state; + public reactiveState: EditorState = this.view.state; - public reactiveExtensionStorage: Storage = this.extensionStorage; + public reactiveExtensionStorage: Storage = this.extensionStorage; - constructor(options: Partial = {}) { - super(options); + constructor(options: Partial = {}) { + super(options); - this.reactiveState = this.view.state; - this.reactiveExtensionStorage = this.extensionStorage; + this.reactiveState = this.view.state; + this.reactiveExtensionStorage = this.extensionStorage; - this.on("beforeTransaction", ({ nextState }) => { - this.reactiveState = nextState; - this.reactiveExtensionStorage = this.extensionStorage; - }); - } + this.on("beforeTransaction", ({ nextState }) => { + this.reactiveState = nextState; + this.reactiveExtensionStorage = this.extensionStorage; + }); + } - get state() { - return this.reactiveState ?? this.view.state; - } + get state() { + return this.reactiveState ?? this.view.state; + } - get storage() { - return this.reactiveExtensionStorage ?? super.storage; - } + get storage() { + return this.reactiveExtensionStorage ?? super.storage; + } - public registerPlugin( - plugin: Plugin, - handlePlugins?: (newPlugin: Plugin, plugins: Plugin[]) => Plugin[], - ): EditorState { - const nextState = super.registerPlugin(plugin, handlePlugins); + public registerPlugin( + plugin: Plugin, + handlePlugins?: (newPlugin: Plugin, plugins: Plugin[]) => Plugin[], + ): EditorState { + const nextState = super.registerPlugin(plugin, handlePlugins); - if (this.reactiveState) { - this.reactiveState = nextState; - } + if (this.reactiveState) { + this.reactiveState = nextState; + } - return nextState; - } + return nextState; + } - public unregisterPlugin(nameOrPluginKey: string | PluginKey): EditorState | undefined { - const nextState = super.unregisterPlugin(nameOrPluginKey); + public unregisterPlugin( + nameOrPluginKey: string | PluginKey, + ): EditorState | undefined { + const nextState = super.unregisterPlugin(nameOrPluginKey); - if (this.reactiveState && nextState) { - this.reactiveState = nextState; - } + if (this.reactiveState && nextState) { + this.reactiveState = nextState; + } - return nextState; - } + return nextState; + } } diff --git a/src/lib/components/edra/tiptap/components/Tiptap.svelte b/src/lib/components/edra/tiptap/components/Tiptap.svelte index fbd896b..177890b 100644 --- a/src/lib/components/edra/tiptap/components/Tiptap.svelte +++ b/src/lib/components/edra/tiptap/components/Tiptap.svelte @@ -1,7 +1,7 @@ diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 191aef1..8bc428d 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -3,10 +3,11 @@ import ArrowRight from "@lucide/svelte/icons/arrow-right"; import BookOpen from "@lucide/svelte/icons/book-open"; import Sparkles from "@lucide/svelte/icons/sparkles"; import { onMount } from "svelte"; -import DemoPreview from "$lib/components/DemoPreview.svelte"; -import Hero from "$lib/components/Hero.svelte"; -import { localizeHref } from "$lib/i18n"; -import * as m from "$lib/i18n/messages"; +import DemoPreview from "#lib/components/DemoPreview.svelte"; +import Hero from "#lib/components/Hero.svelte"; +import Supademo from "#lib/components/Supademo.svelte"; +import { localizeHref } from "#lib/i18n"; +import * as m from "#lib/i18n/messages"; interface SupademoWindow { Supademo?: { @@ -92,6 +93,8 @@ onMount(() => {
+ + diff --git a/src/routes/+page.ts b/src/routes/+page.ts index 5d4d49d..9c1783b 100644 --- a/src/routes/+page.ts +++ b/src/routes/+page.ts @@ -1,51 +1,48 @@ -import type { PageSeoOverride } from "$lib/seo"; -import { HOME_DESCRIPTION, SITE } from "$lib/seo"; +import type { PageSeoOverride } from "#lib/seo"; +import { HOME_DESCRIPTION, SITE } from "#lib/seo"; -// since there's no dynamic data here, we can prerender -// it so that it gets served as a static asset in production export const prerender = true; - export const load = (): { seo: PageSeoOverride } => ({ - seo: { - jsonLd: [ - { - "@type": "SoftwareApplication", - name: SITE.name, - url: SITE.origin, - applicationCategory: "BusinessApplication", - operatingSystem: "Web", - description: HOME_DESCRIPTION, - offers: { "@type": "Offer", price: "0", priceCurrency: "USD" }, - }, - { - "@type": "FAQPage", - mainEntity: [ - { - "@type": "Question", - name: "What is LightCMS?", - acceptedAnswer: { - "@type": "Answer", - text: "LightCMS is a lightweight, Git-backed headless content workspace designed for editing and publishing Markdown content directly to GitHub repositories.", - }, - }, - { - "@type": "Question", - name: "Which static site generators are supported by LightCMS?", - acceptedAnswer: { - "@type": "Answer", - text: "LightCMS supports Hugo, Astro, Zola, Eleventy, Jekyll, Zine, and mdBook with standardized YAML and TOML front matter conventions.", - }, - }, - { - "@type": "Question", - name: "Does LightCMS require an external database?", - acceptedAnswer: { - "@type": "Answer", - text: "No. LightCMS is completely database-free for content storage. All posts and assets live directly inside your Git repository as flat files.", - }, - }, - ], - }, - ], - }, + seo: { + jsonLd: [ + { + "@type": "SoftwareApplication", + name: SITE.name, + url: SITE.origin, + applicationCategory: "BusinessApplication", + operatingSystem: "Web", + description: HOME_DESCRIPTION, + offers: { "@type": "Offer", price: "0", priceCurrency: "USD" }, + }, + { + "@type": "FAQPage", + mainEntity: [ + { + "@type": "Question", + name: "What is LightCMS?", + acceptedAnswer: { + "@type": "Answer", + text: "LightCMS is a lightweight, Git-backed headless content workspace designed for editing and publishing Markdown content directly to GitHub repositories.", + }, + }, + { + "@type": "Question", + name: "Which static site generators are supported by LightCMS?", + acceptedAnswer: { + "@type": "Answer", + text: "LightCMS supports Hugo, Astro, Zola, Eleventy, Jekyll, Zine, and mdBook with standardized YAML and TOML front matter conventions.", + }, + }, + { + "@type": "Question", + name: "Does LightCMS require an external database?", + acceptedAnswer: { + "@type": "Answer", + text: "No. LightCMS is 100% database free for content storage. All posts and assets live directly inside your Git repository as flat files.", + }, + }, + ], + }, + ], + }, }); diff --git a/src/routes/about/+page.svelte b/src/routes/about/+page.svelte index c51271f..3abc3f5 100644 --- a/src/routes/about/+page.svelte +++ b/src/routes/about/+page.svelte @@ -4,10 +4,10 @@ import Heart from "@lucide/svelte/icons/heart"; import Mail from "@lucide/svelte/icons/mail"; import MessageCircle from "@lucide/svelte/icons/message-circle"; import ShieldCheck from "@lucide/svelte/icons/shield-check"; -import { Button } from "$lib/components/ui/button"; -import { localizeHref } from "$lib/i18n"; -import * as m from "$lib/i18n/messages"; -import { SITE } from "$lib/seo"; +import { Button } from "#lib/components/ui/button"; +import { localizeHref } from "#lib/i18n"; +import * as m from "#lib/i18n/messages"; +import { SITE } from "#lib/seo"; type FooterAction = { href: string; diff --git a/src/routes/api/github/webhook/+server.ts b/src/routes/api/github/webhook/+server.ts index b5604d4..0b63605 100644 --- a/src/routes/api/github/webhook/+server.ts +++ b/src/routes/api/github/webhook/+server.ts @@ -1,49 +1,52 @@ import type { EmitterWebhookEventName } from "@octokit/webhooks"; -import { getProbot } from "$lib/server/probot.js"; -import type { RequestHandler } from "./$types.js"; +import { getProbot } from "#lib/server/probot"; +import type { RequestHandler } from "./$types"; function missingHeadersResponse(): Response { - return Response.json({ error: "Missing required GitHub webhook headers" }, { status: 400 }); + return Response.json( + { error: "Missing required GitHub webhook headers" }, + { status: 400 }, + ); } function signatureErrorResponse(): Response { - return Response.json({ error: "Invalid webhook signature" }, { status: 401 }); + return Response.json({ error: "Invalid webhook signature" }, { status: 401 }); } function processingErrorResponse(): Response { - return Response.json({ error: "Failed to process webhook" }, { status: 500 }); + return Response.json({ error: "Failed to process webhook" }, { status: 500 }); } export const POST: RequestHandler = async ({ request }): Promise => { - const eventName = request.headers.get("x-github-event"); - const signature = request.headers.get("x-hub-signature-256"); - const deliveryId = request.headers.get("x-github-delivery"); - - if (eventName === null || signature === null || deliveryId === null) { - return missingHeadersResponse(); - } - - const rawBody = await request.text(); - - try { - const probot = await getProbot(); - await probot.webhooks.verifyAndReceive({ - id: deliveryId, - name: eventName as EmitterWebhookEventName, - payload: rawBody, - signature, - }); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - if (message.toLowerCase().includes("signature")) { - console.error("GitHub webhook signature verification failed", { - deliveryId, - }); - return signatureErrorResponse(); - } - console.error("GitHub webhook processing failed", { deliveryId, message }); - return processingErrorResponse(); - } - - return new Response("OK", { status: 200 }); + const eventName = request.headers.get("x-github-event"); + const signature = request.headers.get("x-hub-signature-256"); + const deliveryId = request.headers.get("x-github-delivery"); + + if (eventName === null || signature === null || deliveryId === null) { + return missingHeadersResponse(); + } + + const rawBody = await request.text(); + + try { + const probot = await getProbot(); + await probot.webhooks.verifyAndReceive({ + id: deliveryId, + name: eventName as EmitterWebhookEventName, + payload: rawBody, + signature, + }); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + if (message.toLowerCase().includes("signature")) { + console.error("GitHub webhook signature verification failed", { + deliveryId, + }); + return signatureErrorResponse(); + } + console.error("GitHub webhook processing failed", { deliveryId, message }); + return processingErrorResponse(); + } + + return new Response("OK", { status: 200 }); }; diff --git a/src/routes/api/image-upload/+server.ts b/src/routes/api/image-upload/+server.ts index 3723c6f..4b76f45 100644 --- a/src/routes/api/image-upload/+server.ts +++ b/src/routes/api/image-upload/+server.ts @@ -2,59 +2,62 @@ import { json } from "@sveltejs/kit"; import type { RequestHandler } from "./$types"; export const POST: RequestHandler = async ({ request }) => { - const incoming = await request.formData(); - const source = incoming.get("source"); - if (!(source instanceof File)) { - return json({ error: "No file uploaded" }, { status: 400 }); - } - const buffer = await source.arrayBuffer(); - const base64 = Buffer.from(buffer).toString("base64"); - const dataUrl = `data:${source.type};base64,${base64}`; + const incoming = await request.formData(); + const source = incoming.get("source"); + if (!(source instanceof File)) { + return json({ error: "No file uploaded" }, { status: 400 }); + } + const buffer = await source.arrayBuffer(); + const base64 = Buffer.from(buffer).toString("base64"); + const dataUrl = `data:${source.type};base64,${base64}`; - try { - const apiKey = process.env.CDN_KEY!; - const cdnUrl = process.env.CDN_URL!; - const uploadUrl = new URL(cdnUrl); - if (!uploadUrl.searchParams.has("key")) { - uploadUrl.searchParams.set("key", apiKey); - } + try { + const apiKey = process.env.CDN_KEY!; + const cdnUrl = process.env.CDN_URL!; + const uploadUrl = new URL(cdnUrl); + if (!uploadUrl.searchParams.has("key")) { + uploadUrl.searchParams.set("key", apiKey); + } - const form = new FormData(); - form.set("image", base64); - form.set("name", source.name); + const form = new FormData(); + form.set("image", base64); + form.set("name", source.name); - const response = await fetch(uploadUrl.toString(), { - method: "POST", - body: form, - }); + const response = await fetch(uploadUrl.toString(), { + method: "POST", + body: form, + }); - if (response.ok) { - const result = (await response.json()) as { - data?: { - url?: string; - display_url?: string; - image?: { url?: string }; - }; - image?: { url?: string; display_url?: string }; - url?: string; - }; - const url = - result.data?.url ?? - result.data?.display_url ?? - result.data?.image?.url ?? - result.image?.url ?? - result.image?.display_url ?? - result.url; - if (url) { - return json({ url }); - } - } + if (response.ok) { + const result = (await response.json()) as { + data?: { + url?: string; + display_url?: string; + image?: { url?: string }; + }; + image?: { url?: string; display_url?: string }; + url?: string; + }; + const url = + result.data?.url ?? + result.data?.display_url ?? + result.data?.image?.url ?? + result.image?.url ?? + result.image?.display_url ?? + result.url; + if (url) { + return json({ url }); + } + } - const text = await response.text(); - throw new Error(`CDN upload failed (${response.status}): ${text}`); - } catch (cause) { - console.warn("External CDN upload failed, falling back to data URL:", cause); - } + const text = await response.text(); + throw new Error(`CDN upload failed (${response.status}): ${text}`); + } catch (cause) { + console.warn( + "External CDN upload failed, falling back to data URL:", + cause, + ); + } - return json({ url: dataUrl }); + return json({ url: dataUrl }); }; diff --git a/src/routes/api/rpc/[...rest]/+server.ts b/src/routes/api/rpc/[...rest]/+server.ts index 0a249b6..342e454 100644 --- a/src/routes/api/rpc/[...rest]/+server.ts +++ b/src/routes/api/rpc/[...rest]/+server.ts @@ -1,27 +1,27 @@ import { onError } from "@orpc/server"; import { RPCHandler } from "@orpc/server/fetch"; -import { router } from "$lib/server/orpc/router"; +import { router } from "#lib/server/orpc/router"; import type { RequestHandler } from "./$types"; const handler = new RPCHandler(router, { - interceptors: [ - onError((error) => { - throw new Error(error instanceof Error ? error.message : String(error)); - }), - ], + interceptors: [ + onError((error) => { + throw new Error(error instanceof Error ? error.message : String(error)); + }), + ], }); const handle: RequestHandler = async ({ locals, request }) => { - const { response } = await handler.handle(request, { - prefix: "/api/rpc", - context: { session: locals.session ?? null }, - }); + const { response } = await handler.handle(request, { + prefix: "/api/rpc", + context: { session: locals.session ?? null }, + }); - if (response) { - return response; - } + if (response) { + return response; + } - return new Response("Not found", { status: 404 }); + return new Response("Not found", { status: 404 }); }; export const GET = handle; diff --git a/src/routes/auth/+page.server.ts b/src/routes/auth/+page.server.ts index 6b2b67f..e996cab 100644 --- a/src/routes/auth/+page.server.ts +++ b/src/routes/auth/+page.server.ts @@ -2,50 +2,50 @@ import { fail } from "@sveltejs/kit"; import { message, superValidate } from "sveltekit-superforms"; import { zod4 } from "sveltekit-superforms/adapters"; import { z } from "zod"; -import { getAuth } from "$lib/server/auth"; +import { getAuth } from "#lib/server/auth"; import type { PageServerLoad } from "./$types"; const authFormSchema = z.object({ - email: z.string().trim().min(1, "Enter an email address."), + email: z.string().trim().min(1, "Enter an email address."), }); export const load: PageServerLoad = async ({ url }) => { - const next = url.searchParams.get("next"); - const safeNext = next?.startsWith("/cms") ? next : "/cms"; - return { - next: safeNext, - form: await superValidate(zod4(authFormSchema), { id: "auth-magic-link" }), - }; + const next = url.searchParams.get("next"); + const safeNext = next?.startsWith("/cms") ? next : "/cms"; + return { + next: safeNext, + form: await superValidate(zod4(authFormSchema), { id: "auth-magic-link" }), + }; }; export const actions = { - default: async (event: { request: Request; url: URL }) => { - const form = await superValidate(event.request, zod4(authFormSchema), { - id: "auth-magic-link", - }); + default: async (event: { request: Request; url: URL }) => { + const form = await superValidate(event.request, zod4(authFormSchema), { + id: "auth-magic-link", + }); - if (!form.valid) { - return fail(400, { form }); - } + if (!form.valid) { + return fail(400, { form }); + } - const next = event.url.searchParams.get("next"); - const safeNext = next?.startsWith("/cms") ? next : "/cms"; - const auth = getAuth(); - try { - await auth.api.signInMagicLink({ - body: { - email: form.data.email, - callbackURL: safeNext, - newUserCallbackURL: safeNext, - }, - headers: event.request.headers, - }); - } catch (cause) { - console.error("Failed to send magic link:", cause); - return message(form, "Failed to send magic link", { status: 500 }); - } + const next = event.url.searchParams.get("next"); + const safeNext = next?.startsWith("/cms") ? next : "/cms"; + const auth = getAuth(); + try { + await auth.api.signInMagicLink({ + body: { + email: form.data.email, + callbackURL: safeNext, + newUserCallbackURL: safeNext, + }, + headers: event.request.headers, + }); + } catch (cause) { + console.error("Failed to send magic link:", cause); + return message(form, "Failed to send magic link", { status: 500 }); + } - return message(form, "Check your inbox for a secure sign-in link."); - }, + return message(form, "Check your inbox for a secure sign-in link."); + }, }; diff --git a/src/routes/auth/+page.svelte b/src/routes/auth/+page.svelte index 259273d..fd28dce 100644 --- a/src/routes/auth/+page.svelte +++ b/src/routes/auth/+page.svelte @@ -8,37 +8,37 @@ import ShieldCheck from "@lucide/svelte/icons/shield-check"; import Trash2 from "@lucide/svelte/icons/trash-2"; import { untrack } from "svelte"; import { superForm } from "sveltekit-superforms"; +import { authClient, signIn, signOut } from "#lib/auth-client"; +import { Button } from "#lib/components/ui/button"; +import { Input } from "#lib/components/ui/input"; +import * as m from "#lib/i18n/messages"; +import { getAuthenticatorName } from "#lib/passkey"; import { goto } from "$app/navigation"; import { page } from "$app/state"; -import { authClient, signIn, signOut } from "$lib/auth-client"; -import { Button } from "$lib/components/ui/button"; -import { Input } from "$lib/components/ui/input"; -import * as m from "$lib/i18n/messages"; -import { getAuthenticatorName } from "$lib/passkey"; import type { PageData } from "./$types"; type PasskeySummary = { - id: string; - name?: string | null; - aaguid?: string | null; - backedUp?: boolean | null; - createdAt?: Date | string | null; + id: string; + name?: string | null; + aaguid?: string | null; + backedUp?: boolean | null; + createdAt?: Date | string | null; }; type PasskeyError = { - code?: string; - message?: string; + code?: string; + message?: string; }; let { data }: { data: PageData } = $props(); const nextPath = $derived(data.next ?? "/cms"); const authForm = untrack(() => superForm(data.form)); const { - form: authValues, - errors: authErrors, - enhance: authEnhance, - message: authMessage, - submitting: authSubmitting, + form: authValues, + errors: authErrors, + enhance: authEnhance, + message: authMessage, + submitting: authSubmitting, } = authForm; let isUsingPasskey = $state(false); @@ -59,337 +59,343 @@ let passkeyNotice = $state(null); let conditionalPasskeyStarted = false; const headingTitle = $derived( - data.session ? m.auth_account_title() : m.auth_sign_in_title(), + data.session ? m.auth_account_title() : m.auth_sign_in_title(), ); const headingDesc = $derived( - data.session ? m.auth_account_desc() : m.auth_sign_in_desc(), + data.session ? m.auth_account_desc() : m.auth_sign_in_desc(), ); const githubButtonText = $derived( - isSigningInWithGitHub - ? m.auth_redirecting_github() - : m.auth_continue_github(), + isSigningInWithGitHub + ? m.auth_redirecting_github() + : m.auth_continue_github(), ); const passkeyButtonText = $derived( - isUsingPasskey - ? m.auth_authenticating_passkey() - : m.auth_use_passkey(), + isUsingPasskey ? m.auth_authenticating_passkey() : m.auth_use_passkey(), ); const submitButtonText = $derived( - $authSubmitting ? m.auth_email_submitting() : m.auth_email_submit(), + $authSubmitting ? m.auth_email_submitting() : m.auth_email_submit(), ); const passkeyDateFormatter = new Intl.DateTimeFormat(undefined, { - dateStyle: "medium", + dateStyle: "medium", }); function describePasskeyError(error: PasskeyError | null | undefined): string { - if (!error) { - return m.auth_passkey_error(); - } - - if (error.code === "AUTH_CANCELLED" || error.code === "REGISTRATION_CANCELLED") { - return m.auth_passkey_canceled(); - } - - return error.message || m.auth_passkey_error(); + if (!error) { + return m.auth_passkey_error(); + } + + if ( + error.code === "AUTH_CANCELLED" || + error.code === "REGISTRATION_CANCELLED" + ) { + return m.auth_passkey_canceled(); + } + + return error.message || m.auth_passkey_error(); } function getPasskeyLabel(passkey: PasskeySummary): string { - return ( - passkey.name?.trim() || - getAuthenticatorName(passkey.aaguid) || - m.auth_passkey_unnamed() - ); + return ( + passkey.name?.trim() || + getAuthenticatorName(passkey.aaguid) || + m.auth_passkey_unnamed() + ); } -function formatPasskeyDate(createdAt: Date | string | null | undefined): string { - if (!createdAt) { - return ""; - } +function formatPasskeyDate( + createdAt: Date | string | null | undefined, +): string { + if (!createdAt) { + return ""; + } - const date = createdAt instanceof Date ? createdAt : new Date(createdAt); - if (Number.isNaN(date.getTime())) { - return ""; - } + const date = createdAt instanceof Date ? createdAt : new Date(createdAt); + if (Number.isNaN(date.getTime())) { + return ""; + } - return `${m.auth_passkey_created()} ${passkeyDateFormatter.format(date)}`; + return `${m.auth_passkey_created()} ${passkeyDateFormatter.format(date)}`; } function describePasskeyMeta(passkey: PasskeySummary): string { - const parts: string[] = []; - const authenticatorName = getAuthenticatorName(passkey.aaguid); + const parts: string[] = []; + const authenticatorName = getAuthenticatorName(passkey.aaguid); - if (passkey.name?.trim() && authenticatorName) { - parts.push(authenticatorName); - } + if (passkey.name?.trim() && authenticatorName) { + parts.push(authenticatorName); + } - parts.push( - passkey.backedUp ? m.auth_passkey_synced() : m.auth_passkey_device_bound(), - ); + parts.push( + passkey.backedUp ? m.auth_passkey_synced() : m.auth_passkey_device_bound(), + ); - const created = formatPasskeyDate(passkey.createdAt); - if (created) { - parts.push(created); - } + const created = formatPasskeyDate(passkey.createdAt); + if (created) { + parts.push(created); + } - return parts.join(" · "); + return parts.join(" · "); } async function refreshPasskeys() { - isLoadingPasskeys = true; - try { - const result = await authClient.passkey.listUserPasskeys(); - if (result.error) { - passkeyError = describePasskeyError(result.error); - return; - } - passkeys = result.data ?? []; - } catch (cause) { - passkeyError = - cause instanceof Error ? cause.message : m.auth_passkey_error(); - } finally { - isLoadingPasskeys = false; - } + isLoadingPasskeys = true; + try { + const result = await authClient.passkey.listUserPasskeys(); + if (result.error) { + passkeyError = describePasskeyError(result.error); + return; + } + passkeys = result.data ?? []; + } catch (cause) { + passkeyError = + cause instanceof Error ? cause.message : m.auth_passkey_error(); + } finally { + isLoadingPasskeys = false; + } } async function startConditionalPasskey() { - try { - const conditionalSupported = - typeof PublicKeyCredential !== "undefined" && - typeof PublicKeyCredential.isConditionalMediationAvailable === "function" && - (await PublicKeyCredential.isConditionalMediationAvailable()); - - if (!conditionalSupported) { - return; - } - - const result = await signIn.passkey({ autoFill: true }); - if (result.error) { - return; - } - - window.location.assign(nextPath); - } catch { - // Conditional UI is best-effort; the passkey button surfaces real errors. - } + try { + const conditionalSupported = + typeof PublicKeyCredential !== "undefined" && + typeof PublicKeyCredential.isConditionalMediationAvailable === + "function" && + (await PublicKeyCredential.isConditionalMediationAvailable()); + + if (!conditionalSupported) { + return; + } + + const result = await signIn.passkey({ autoFill: true }); + if (result.error) { + return; + } + + window.location.assign(nextPath); + } catch { + // Conditional UI is best-effort; the passkey button surfaces real errors. + } } async function signInWithGitHub() { - if (isSigningInWithGitHub) return; - isSigningInWithGitHub = true; - try { - await signIn.social({ - provider: "github", - callbackURL: nextPath, - errorCallbackURL: "/auth", - }); - } finally { - isSigningInWithGitHub = false; - } + if (isSigningInWithGitHub) return; + isSigningInWithGitHub = true; + try { + await signIn.social({ + provider: "github", + callbackURL: nextPath, + errorCallbackURL: "/auth", + }); + } finally { + isSigningInWithGitHub = false; + } } let _isLinkingGitHub = $state(false); async function _linkGitHub() { - _isLinkingGitHub = true; - try { - await authClient.linkSocial({ - provider: "github", - callbackURL: "/cms", - errorCallbackURL: "/auth", - }); - } finally { - _isLinkingGitHub = false; - } + _isLinkingGitHub = true; + try { + await authClient.linkSocial({ + provider: "github", + callbackURL: "/cms", + errorCallbackURL: "/auth", + }); + } finally { + _isLinkingGitHub = false; + } } async function _signOutUser() { - try { - await signOut(); - } finally { - await goto("/signout", { invalidateAll: true }); - } + try { + await signOut(); + } finally { + await goto("/signout", { invalidateAll: true }); + } } async function signInWithPasskey() { - if (isUsingPasskey) return; - isUsingPasskey = true; - passkeyError = null; - passkeyNotice = null; - - try { - const result = await signIn.passkey({ autoFill: false }); - if (result.error) { - passkeyError = describePasskeyError(result.error); - return; - } - - window.location.assign(nextPath); - } catch (cause) { - passkeyError = - cause instanceof Error ? cause.message : m.auth_passkey_error(); - } finally { - isUsingPasskey = false; - } + if (isUsingPasskey) return; + isUsingPasskey = true; + passkeyError = null; + passkeyNotice = null; + + try { + const result = await signIn.passkey({ autoFill: false }); + if (result.error) { + passkeyError = describePasskeyError(result.error); + return; + } + + window.location.assign(nextPath); + } catch (cause) { + passkeyError = + cause instanceof Error ? cause.message : m.auth_passkey_error(); + } finally { + isUsingPasskey = false; + } } function openPasskeyForm() { - if (isAddingPasskey) { - return; - } - - passkeyError = null; - passkeyNotice = null; - editingPasskeyId = null; - editingPasskeyName = ""; - newPasskeyName = ""; - isNamingPasskey = true; + if (isAddingPasskey) { + return; + } + + passkeyError = null; + passkeyNotice = null; + editingPasskeyId = null; + editingPasskeyName = ""; + newPasskeyName = ""; + isNamingPasskey = true; } function closePasskeyForm() { - if (isAddingPasskey) { - return; - } + if (isAddingPasskey) { + return; + } - isNamingPasskey = false; - newPasskeyName = ""; + isNamingPasskey = false; + newPasskeyName = ""; } async function createPasskey() { - if (isAddingPasskey) return; - isAddingPasskey = true; - passkeyError = null; - passkeyNotice = null; - - try { - const name = newPasskeyName.trim(); - const result = await authClient.passkey.addPasskey(name ? { name } : undefined); - if (result.error) { - passkeyError = describePasskeyError(result.error); - return; - } - - isNamingPasskey = false; - newPasskeyName = ""; - await refreshPasskeys(); - passkeyNotice = m.auth_passkey_added(); - } catch (cause) { - passkeyError = - cause instanceof Error ? cause.message : m.auth_passkey_error(); - } finally { - isAddingPasskey = false; - } + if (isAddingPasskey) return; + isAddingPasskey = true; + passkeyError = null; + passkeyNotice = null; + + try { + const name = newPasskeyName.trim(); + const result = await authClient.passkey.addPasskey( + name ? { name } : undefined, + ); + if (result.error) { + passkeyError = describePasskeyError(result.error); + return; + } + + isNamingPasskey = false; + newPasskeyName = ""; + await refreshPasskeys(); + passkeyNotice = m.auth_passkey_added(); + } catch (cause) { + passkeyError = + cause instanceof Error ? cause.message : m.auth_passkey_error(); + } finally { + isAddingPasskey = false; + } } function startRenamingPasskey(passkey: PasskeySummary) { - if (savingPasskeyId) { - return; - } - - passkeyError = null; - passkeyNotice = null; - isNamingPasskey = false; - newPasskeyName = ""; - editingPasskeyId = passkey.id; - editingPasskeyName = passkey.name?.trim() ?? ""; + if (savingPasskeyId) { + return; + } + + passkeyError = null; + passkeyNotice = null; + isNamingPasskey = false; + newPasskeyName = ""; + editingPasskeyId = passkey.id; + editingPasskeyName = passkey.name?.trim() ?? ""; } function cancelRenamingPasskey() { - if (savingPasskeyId) { - return; - } + if (savingPasskeyId) { + return; + } - editingPasskeyId = null; - editingPasskeyName = ""; + editingPasskeyId = null; + editingPasskeyName = ""; } async function renamePasskey(id: string) { - if (savingPasskeyId) return; - - const name = editingPasskeyName.trim(); - if (!name) { - passkeyError = m.auth_passkey_name_required(); - return; - } - - savingPasskeyId = id; - passkeyError = null; - passkeyNotice = null; - - try { - const result = await authClient.passkey.updatePasskey({ id, name }); - if (result.error) { - passkeyError = describePasskeyError(result.error); - return; - } - - editingPasskeyId = null; - editingPasskeyName = ""; - await refreshPasskeys(); - passkeyNotice = m.auth_passkey_renamed(); - } catch (cause) { - passkeyError = - cause instanceof Error ? cause.message : m.auth_passkey_error(); - } finally { - savingPasskeyId = null; - } + if (savingPasskeyId) return; + + const name = editingPasskeyName.trim(); + if (!name) { + passkeyError = m.auth_passkey_name_required(); + return; + } + + savingPasskeyId = id; + passkeyError = null; + passkeyNotice = null; + + try { + const result = await authClient.passkey.updatePasskey({ id, name }); + if (result.error) { + passkeyError = describePasskeyError(result.error); + return; + } + + editingPasskeyId = null; + editingPasskeyName = ""; + await refreshPasskeys(); + passkeyNotice = m.auth_passkey_renamed(); + } catch (cause) { + passkeyError = + cause instanceof Error ? cause.message : m.auth_passkey_error(); + } finally { + savingPasskeyId = null; + } } async function removePasskey(id: string) { - if (removingPasskeyId) return; - removingPasskeyId = id; - passkeyError = null; - passkeyNotice = null; - - try { - const result = await authClient.passkey.deletePasskey({ id }); - if (result.error) { - passkeyError = describePasskeyError(result.error); - return; - } - - if (editingPasskeyId === id) { - editingPasskeyId = null; - editingPasskeyName = ""; - } - - await refreshPasskeys(); - passkeyNotice = m.auth_passkey_removed(); - } catch (cause) { - passkeyError = - cause instanceof Error ? cause.message : m.auth_passkey_error(); - } finally { - removingPasskeyId = null; - } + if (removingPasskeyId) return; + removingPasskeyId = id; + passkeyError = null; + passkeyNotice = null; + + try { + const result = await authClient.passkey.deletePasskey({ id }); + if (result.error) { + passkeyError = describePasskeyError(result.error); + return; + } + + if (editingPasskeyId === id) { + editingPasskeyId = null; + editingPasskeyName = ""; + } + + await refreshPasskeys(); + passkeyNotice = m.auth_passkey_removed(); + } catch (cause) { + passkeyError = + cause instanceof Error ? cause.message : m.auth_passkey_error(); + } finally { + removingPasskeyId = null; + } } $effect(() => { - if (!data.session) { - passkeys = []; - return; - } + if (!data.session) { + passkeys = []; + return; + } - void refreshPasskeys(); + void refreshPasskeys(); }); $effect(() => { - if (data.session || conditionalPasskeyStarted) { - return; - } + if (data.session || conditionalPasskeyStarted) { + return; + } - conditionalPasskeyStarted = true; - void startConditionalPasskey(); + conditionalPasskeyStarted = true; + void startConditionalPasskey(); }); $effect(() => { - if (isNamingPasskey) { - passkeyNameInput?.focus(); - } + if (isNamingPasskey) { + passkeyNameInput?.focus(); + } }); $effect(() => { - if (editingPasskeyId) { - renamePasskeyInput?.focus(); - } + if (editingPasskeyId) { + renamePasskeyInput?.focus(); + } }); diff --git a/src/routes/cms/+page.server.ts b/src/routes/cms/+page.server.ts index 311fdad..d6c3a8f 100644 --- a/src/routes/cms/+page.server.ts +++ b/src/routes/cms/+page.server.ts @@ -1,210 +1,231 @@ import { fail, redirect } from "@sveltejs/kit"; -import { createFolderAtPath, listDirectory, resolveRepository } from "$lib/server/cms"; -import { getCmsQuery, getCmsSelection, tryGetCmsSelection } from "$lib/server/cms-context"; -import { assertCollectionName, getCollection, type LightCmsCollection } from "$lib/server/config"; import { - isGitHubStatus, - listBranches as listRepoBranches, - listRepositories, -} from "$lib/server/github"; -import { captureServerEvent } from "$lib/server/posthog"; + createFolderAtPath, + listDirectory, + resolveRepository, +} from "#lib/server/cms"; import { - getCmsContext, - listGitHubInstallations, - removeStaleInstallation, -} from "$lib/server/session"; -import { fetchTemplates, type TemplatesResult } from "$lib/templates"; + getCmsQuery, + getCmsSelection, + tryGetCmsSelection, +} from "#lib/server/cms-context"; +import { + assertCollectionName, + getCollection, + type LightCmsCollection, +} from "#lib/server/config"; +import { + isGitHubStatus, + listBranches as listRepoBranches, + listRepositories, +} from "#lib/server/github"; +import { captureServerEvent } from "#lib/server/posthog"; +import { + getCmsContext, + listGitHubInstallations, + removeStaleInstallation, +} from "#lib/server/session"; +import { fetchTemplates, type TemplatesResult } from "#lib/templates"; import type { Actions, PageServerLoad } from "./$types"; const TEMPLATE_OWNER = "light-cms"; async function loadTemplates(fetchFn: typeof fetch): Promise { - try { - const templates = await fetchTemplates(TEMPLATE_OWNER, { - fetch: fetchFn, - org: true, - }); - return { templates, error: null }; - } catch (cause) { - console.warn("Failed to load repository templates:", cause); - return { - templates: [], - error: "Could not load templates from GitHub. Please try again later.", - }; - } + try { + const templates = await fetchTemplates(TEMPLATE_OWNER, { + fetch: fetchFn, + org: true, + }); + return { templates, error: null }; + } catch (cause) { + console.warn("Failed to load repository templates:", cause); + return { + templates: [], + error: "Could not load templates from GitHub. Please try again later.", + }; + } } export const load: PageServerLoad = async ({ locals, url, fetch }) => { - if (!locals.session) throw redirect(302, "/auth"); - - // Not awaited: streamed to the client so a slow GitHub call never blocks the console. - const templates = loadTemplates(fetch); - - const { userId } = locals.session; - const installations = await listGitHubInstallations(userId); - const results = await Promise.allSettled( - installations.map(async (installation) => { - const context = await getCmsContext(userId, installation.installationId); - const repos = await listRepositories(context.client); - return repos.map((repository) => ({ - ...repository, - installationId: installation.installationId, - accountLogin: installation.accountLogin, - })); - }), - ); - const repositories: Array<{ - name: string; - fullName: string; - private: boolean; - defaultBranch: string; - installationId: number; - accountLogin: string; - }> = []; - const repositoryWarnings: string[] = []; - for (const [index, result] of results.entries()) { - if (result.status === "rejected") { - const { installationId } = installations[index]; - if (isGitHubStatus(result.reason, 404)) { - await removeStaleInstallation(userId, installationId); - console.warn(`Removed stale installation ${installationId}`); - repositoryWarnings.push( - `The GitHub installation for ${installations[index].accountLogin} is no longer available.`, - ); - } else { - console.warn(`Skipping inaccessible installation ${installationId}:`, result.reason); - repositoryWarnings.push( - `Repositories for ${installations[index].accountLogin} could not be loaded.`, - ); - } - } else { - repositories.push(...result.value); - } - } - const selection = tryGetCmsSelection(url); - const query = selection ? getCmsQuery(selection) : ""; - - const collectionsList: LightCmsCollection[] = []; - const branches: Array<{ - name: string; - protected: boolean; - isDefault: boolean; - }> = []; - let defaultBranch = ""; - if (selection) { - try { - const activeContext = await getCmsContext( - userId, - selection.installationId, - selection.repository, - selection.branch, - ); - // Collections are discovered from the repository's root directories — - // there is no predefined content root or default collection. - const contentEntries = await listDirectory("", { - client: activeContext.client, - repository: selection.repository, - branch: selection.branch, - }); - const contentFolders = contentEntries.filter( - (entry) => entry.type === "dir" && !entry.name.startsWith("."), - ); - for (const folder of contentFolders) { - if (!collectionsList.some((col) => col.name === folder.name)) { - collectionsList.push(getCollection(folder.name)); - } - } - } catch { - // Ignore errors when the repository root cannot be listed yet - } - - try { - const branchContext = await getCmsContext( - userId, - selection.installationId, - selection.repository, - ); - const repo = resolveRepository(branchContext); - const repoBranches = await listRepoBranches(branchContext.client, repo); - for (const branch of repoBranches) { - branches.push({ - name: branch.name, - protected: branch.protected, - isDefault: branch.isDefault, - }); - if (branch.isDefault) { - defaultBranch = branch.name; - } - } - } catch (cause) { - console.warn(`Failed to list branches for ${selection.repository}:`, cause); - } - } - - return { - templates, - repositories, - installations, - repositoryWarnings, - selection, - query, - branches, - defaultBranch, - collections: collectionsList.map((collection) => ({ - name: collection.name, - label: collection.label ?? collection.name, - path: collection.path, - fields: collection.fields, - href: `/cms/${encodeURIComponent(collection.name)}?${query}`, - })), - }; + if (!locals.session) throw redirect(302, "/auth"); + + // Not awaited: streamed to the client so a slow GitHub call never blocks the console. + const templates = loadTemplates(fetch); + + const { userId } = locals.session; + const installations = await listGitHubInstallations(userId); + const results = await Promise.allSettled( + installations.map(async (installation) => { + const context = await getCmsContext(userId, installation.installationId); + const repos = await listRepositories(context.client); + return repos.map((repository) => ({ + ...repository, + installationId: installation.installationId, + accountLogin: installation.accountLogin, + })); + }), + ); + const repositories: Array<{ + name: string; + fullName: string; + private: boolean; + defaultBranch: string; + installationId: number; + accountLogin: string; + }> = []; + const repositoryWarnings: string[] = []; + for (const [index, result] of results.entries()) { + if (result.status === "rejected") { + const { installationId } = installations[index]; + if (isGitHubStatus(result.reason, 404)) { + await removeStaleInstallation(userId, installationId); + console.warn(`Removed stale installation ${installationId}`); + repositoryWarnings.push( + `The GitHub installation for ${installations[index].accountLogin} is no longer available.`, + ); + } else { + console.warn( + `Skipping inaccessible installation ${installationId}:`, + result.reason, + ); + repositoryWarnings.push( + `Repositories for ${installations[index].accountLogin} could not be loaded.`, + ); + } + } else { + repositories.push(...result.value); + } + } + const selection = tryGetCmsSelection(url); + const query = selection ? getCmsQuery(selection) : ""; + + const collectionsList: LightCmsCollection[] = []; + const branches: Array<{ + name: string; + protected: boolean; + isDefault: boolean; + }> = []; + let defaultBranch = ""; + if (selection) { + try { + const activeContext = await getCmsContext( + userId, + selection.installationId, + selection.repository, + selection.branch, + ); + // Collections are discovered from the repository's root directories — + // there is no predefined content root or default collection. + const contentEntries = await listDirectory("", { + client: activeContext.client, + repository: selection.repository, + branch: selection.branch, + }); + const contentFolders = contentEntries.filter( + (entry) => entry.type === "dir" && !entry.name.startsWith("."), + ); + for (const folder of contentFolders) { + if (!collectionsList.some((col) => col.name === folder.name)) { + collectionsList.push(getCollection(folder.name)); + } + } + } catch { + // Ignore errors when the repository root cannot be listed yet + } + + try { + const branchContext = await getCmsContext( + userId, + selection.installationId, + selection.repository, + ); + const repo = resolveRepository(branchContext); + const repoBranches = await listRepoBranches(branchContext.client, repo); + for (const branch of repoBranches) { + branches.push({ + name: branch.name, + protected: branch.protected, + isDefault: branch.isDefault, + }); + if (branch.isDefault) { + defaultBranch = branch.name; + } + } + } catch (cause) { + console.warn( + `Failed to list branches for ${selection.repository}:`, + cause, + ); + } + } + + return { + templates, + repositories, + installations, + repositoryWarnings, + selection, + query, + branches, + defaultBranch, + collections: collectionsList.map((collection) => ({ + name: collection.name, + label: collection.label ?? collection.name, + path: collection.path, + fields: collection.fields, + href: `/cms/${encodeURIComponent(collection.name)}?${query}`, + })), + }; }; export const actions: Actions = { - createCollection: async ({ locals, request, url }) => { - if (!locals.session) throw redirect(302, "/auth"); - - const selection = getCmsSelection(url); - if (!selection) return fail(400, { error: "No repository selected." }); - - const formData = await request.formData(); - const rawName = formData.get("name"); - const name = typeof rawName === "string" ? rawName.trim() : ""; - - if (!name) { - return fail(400, { error: "Folder name is required." }); - } - - let cleanName: string; - try { - cleanName = assertCollectionName(name); - } catch { - return fail(400, { - error: "Folder name must contain valid alphanumeric characters.", - }); - } - - try { - const context = await getCmsContext( - locals.session.userId, - selection.installationId, - selection.repository, - selection.branch, - ); - await createFolderAtPath("", cleanName, { - client: context.client, - repository: selection.repository, - branch: selection.branch, - }); - } catch (cause) { - return fail(400, { - error: cause instanceof Error ? cause.message : "Could not create collection folder.", - }); - } - - await captureServerEvent(locals.session.userId, "collection_created"); - - const query = getCmsQuery(selection); - throw redirect(303, `/cms/${encodeURIComponent(cleanName)}?${query}`); - }, + createCollection: async ({ locals, request, url }) => { + if (!locals.session) throw redirect(302, "/auth"); + + const selection = getCmsSelection(url); + if (!selection) return fail(400, { error: "No repository selected." }); + + const formData = await request.formData(); + const rawName = formData.get("name"); + const name = typeof rawName === "string" ? rawName.trim() : ""; + + if (!name) { + return fail(400, { error: "Folder name is required." }); + } + + let cleanName: string; + try { + cleanName = assertCollectionName(name); + } catch { + return fail(400, { + error: "Folder name must contain valid alphanumeric characters.", + }); + } + + try { + const context = await getCmsContext( + locals.session.userId, + selection.installationId, + selection.repository, + selection.branch, + ); + await createFolderAtPath("", cleanName, { + client: context.client, + repository: selection.repository, + branch: selection.branch, + }); + } catch (cause) { + return fail(400, { + error: + cause instanceof Error + ? cause.message + : "Could not create collection folder.", + }); + } + + await captureServerEvent(locals.session.userId, "collection_created"); + + const query = getCmsQuery(selection); + throw redirect(303, `/cms/${encodeURIComponent(cleanName)}?${query}`); + }, }; diff --git a/src/routes/cms/+page.svelte b/src/routes/cms/+page.svelte index ed55d57..8458a1f 100644 --- a/src/routes/cms/+page.svelte +++ b/src/routes/cms/+page.svelte @@ -11,13 +11,13 @@ import LayoutTemplate from "@lucide/svelte/icons/layout-template"; import Settings from "@lucide/svelte/icons/settings"; import Sparkles from "@lucide/svelte/icons/sparkles"; import { toast } from "svelte-sonner"; -import { goto, refreshAll } from "$app/navigation"; import { CreateBranchDialog, CreateFolderDialog, TemplateDrawer, -} from "$lib/components/custom"; -import { Button } from "$lib/components/ui/button"; +} from "#lib/components/custom"; +import { Button } from "#lib/components/ui/button"; +import { goto, refreshAll } from "$app/navigation"; import type { PageData } from "./$types"; let { data, form }: { data: PageData; form?: { error?: string } | null } = diff --git a/src/routes/cms/[collection]/+page.server.ts b/src/routes/cms/[collection]/+page.server.ts index 99e9011..2cdd2e7 100644 --- a/src/routes/cms/[collection]/+page.server.ts +++ b/src/routes/cms/[collection]/+page.server.ts @@ -1,194 +1,218 @@ import { fail, redirect } from "@sveltejs/kit"; import { - createCollectionFolder, - deleteCollectionFolder, - initializeCollection, - listCollectionEntries, - moveCollectionEntry, -} from "$lib/server/cms"; - -import { getConfiguredCollection } from "$lib/server/cms-context"; -import { joinPath, normalizeContentPath, normalizeFolder } from "$lib/server/paths"; -import { captureServerEvent } from "$lib/server/posthog"; + createCollectionFolder, + deleteCollectionFolder, + initializeCollection, + listCollectionEntries, + moveCollectionEntry, +} from "#lib/server/cms"; + +import { getConfiguredCollection } from "#lib/server/cms-context"; +import { + joinPath, + normalizeContentPath, + normalizeFolder, +} from "#lib/server/paths"; +import { captureServerEvent } from "#lib/server/posthog"; import type { Actions, PageServerLoad } from "./$types"; function getInitializeErrorMessage(error: unknown): string { - const fallback = "Failed to initialize collection"; - if (error instanceof Error) { - const message = error.message.trim(); - if (message.length > 0) { - return message; - } - return fallback; - } - if (typeof error === "string") { - const trimmed = error.trim(); - if (trimmed.length > 0) { - return trimmed; - } - return fallback; - } - return fallback; + const fallback = "Failed to initialize collection"; + if (error instanceof Error) { + const message = error.message.trim(); + if (message.length > 0) { + return message; + } + return fallback; + } + if (typeof error === "string") { + const trimmed = error.trim(); + if (trimmed.length > 0) { + return trimmed; + } + return fallback; + } + return fallback; } export const load: PageServerLoad = async ({ locals, params, url }) => { - if (!locals.session) throw redirect(302, "/auth"); - - const { collection, ctx, query, selection } = await getConfiguredCollection( - locals.session.userId, - url, - params.collection, - ); - const folder = normalizeFolder(url.searchParams.get("folder") ?? ""); - const listing = await listCollectionEntries(collection, ctx, folder); - - return { - collection, - folder, - folders: listing.folders, - entries: listing.entries, - query, - selection, - primaryField: collection.view?.primary ?? collection.fields[0].name, - }; + if (!locals.session) throw redirect(302, "/auth"); + + const { collection, ctx, query, selection } = await getConfiguredCollection( + locals.session.userId, + url, + params.collection, + ); + const folder = normalizeFolder(url.searchParams.get("folder") ?? ""); + const listing = await listCollectionEntries(collection, ctx, folder); + + return { + collection, + folder, + folders: listing.folders, + entries: listing.entries, + query, + selection, + primaryField: collection.view?.primary ?? collection.fields[0].name, + }; }; export const actions: Actions = { - initialize: async ({ locals, params, url }) => { - if (!locals.session) throw redirect(302, "/auth"); - - const { collection, ctx, query } = await getConfiguredCollection( - locals.session.userId, - url, - params.collection, - ); - - try { - await initializeCollection(collection, ctx); - } catch (error) { - const errorMessage = getInitializeErrorMessage(error); - throw new Error(errorMessage, { cause: error }); - } - - await captureServerEvent(locals.session.userId, "collection_initialized"); - - throw redirect(303, `/cms/${encodeURIComponent(collection.name)}?${query}`); - }, - - createFolder: async ({ locals, params, url, request }) => { - if (!locals.session) throw redirect(302, "/auth"); - - const { collection, ctx, query } = await getConfiguredCollection( - locals.session.userId, - url, - params.collection, - ); - - const formData = await request.formData(); - const rawName = formData.get("name"); - const name = typeof rawName === "string" ? rawName.trim() : ""; - if (!name) { - throw new Error("Folder name is required."); - } - const folder = normalizeFolder(url.searchParams.get("folder") ?? ""); - await createCollectionFolder(collection, folder, name, ctx); - await captureServerEvent(locals.session.userId, "collection_folder_created"); - - const folderQuery = new URLSearchParams(query); - if (folder) folderQuery.set("folder", folder); - throw redirect(303, `/cms/${encodeURIComponent(collection.name)}?${folderQuery}`); - }, - - deleteFolder: async ({ locals, params, url, request }) => { - if (!locals.session) throw redirect(302, "/auth"); - - const { collection, ctx, query } = await getConfiguredCollection( - locals.session.userId, - url, - params.collection, - ); - - const folder = normalizeFolder(url.searchParams.get("folder") ?? ""); - const formData = await request.formData(); - const rawName = formData.get("name"); - const rawPath = formData.get("folderPath"); - const name = typeof rawName === "string" ? rawName : ""; - const folderPathInput = typeof rawPath === "string" ? rawPath : ""; - - let folderToDelete: string; - if (folderPathInput.trim()) { - folderToDelete = normalizeFolder(folderPathInput); - } else if (name.trim()) { - const normalizedName = normalizeContentPath(name); - folderToDelete = normalizeFolder(joinPath(folder, normalizedName)); - } else { - return fail(400, { - folder, - folderError: "Folder name is required.", - }); - } - - try { - await deleteCollectionFolder(collection, folderToDelete, ctx); - } catch (cause) { - return fail(400, { - folder, - folderError: cause instanceof Error ? cause.message : "Could not delete the folder.", - }); - } - - await captureServerEvent(locals.session.userId, "collection_folder_deleted"); - - const folderQuery = new URLSearchParams(query); - if (folderToDelete) folderQuery.set("folder", folderToDelete); - else folderQuery.delete("folder"); - throw redirect(303, `/cms/${encodeURIComponent(collection.name)}?${folderQuery}`); - }, - - moveEntry: async ({ locals, params, url, request }) => { - if (!locals.session) throw redirect(302, "/auth"); - - const { collection, ctx, query } = await getConfiguredCollection( - locals.session.userId, - url, - params.collection, - ); - - const formData = await request.formData(); - const rawSlug = formData.get("slug"); - const rawFromFolder = formData.get("fromFolder"); - const rawToFolder = formData.get("toFolder"); - - const slug = typeof rawSlug === "string" ? rawSlug.trim() : ""; - const fromFolder = typeof rawFromFolder === "string" ? rawFromFolder.trim() : ""; - const toFolder = typeof rawToFolder === "string" ? rawToFolder.trim() : ""; - - if (!slug) { - return fail(400, { - folder: fromFolder, - folderError: "Entry slug is required.", - }); - } - - try { - await moveCollectionEntry(collection, slug, fromFolder, toFolder, ctx); - } catch (cause) { - return fail(400, { - folder: fromFolder, - folderError: cause instanceof Error ? cause.message : "Could not move the entry.", - }); - } - - await captureServerEvent(locals.session.userId, "collection_entry_moved", { - surface: "collection_list", - }); - - const folderQuery = new URLSearchParams(query); - if (toFolder.length > 0) { - folderQuery.set("folder", toFolder); - } else { - folderQuery.delete("folder"); - } - throw redirect(303, `/cms/${encodeURIComponent(collection.name)}?${folderQuery}`); - }, + initialize: async ({ locals, params, url }) => { + if (!locals.session) throw redirect(302, "/auth"); + + const { collection, ctx, query } = await getConfiguredCollection( + locals.session.userId, + url, + params.collection, + ); + + try { + await initializeCollection(collection, ctx); + } catch (error) { + const errorMessage = getInitializeErrorMessage(error); + throw new Error(errorMessage, { cause: error }); + } + + await captureServerEvent(locals.session.userId, "collection_initialized"); + + throw redirect(303, `/cms/${encodeURIComponent(collection.name)}?${query}`); + }, + + createFolder: async ({ locals, params, url, request }) => { + if (!locals.session) throw redirect(302, "/auth"); + + const { collection, ctx, query } = await getConfiguredCollection( + locals.session.userId, + url, + params.collection, + ); + + const formData = await request.formData(); + const rawName = formData.get("name"); + const name = typeof rawName === "string" ? rawName.trim() : ""; + if (!name) { + throw new Error("Folder name is required."); + } + const folder = normalizeFolder(url.searchParams.get("folder") ?? ""); + await createCollectionFolder(collection, folder, name, ctx); + await captureServerEvent( + locals.session.userId, + "collection_folder_created", + ); + + const folderQuery = new URLSearchParams(query); + if (folder) folderQuery.set("folder", folder); + throw redirect( + 303, + `/cms/${encodeURIComponent(collection.name)}?${folderQuery}`, + ); + }, + + deleteFolder: async ({ locals, params, url, request }) => { + if (!locals.session) throw redirect(302, "/auth"); + + const { collection, ctx, query } = await getConfiguredCollection( + locals.session.userId, + url, + params.collection, + ); + + const folder = normalizeFolder(url.searchParams.get("folder") ?? ""); + const formData = await request.formData(); + const rawName = formData.get("name"); + const rawPath = formData.get("folderPath"); + const name = typeof rawName === "string" ? rawName : ""; + const folderPathInput = typeof rawPath === "string" ? rawPath : ""; + + let folderToDelete: string; + if (folderPathInput.trim()) { + folderToDelete = normalizeFolder(folderPathInput); + } else if (name.trim()) { + const normalizedName = normalizeContentPath(name); + folderToDelete = normalizeFolder(joinPath(folder, normalizedName)); + } else { + return fail(400, { + folder, + folderError: "Folder name is required.", + }); + } + + try { + await deleteCollectionFolder(collection, folderToDelete, ctx); + } catch (cause) { + return fail(400, { + folder, + folderError: + cause instanceof Error + ? cause.message + : "Could not delete the folder.", + }); + } + + await captureServerEvent( + locals.session.userId, + "collection_folder_deleted", + ); + + const folderQuery = new URLSearchParams(query); + if (folderToDelete) folderQuery.set("folder", folderToDelete); + else folderQuery.delete("folder"); + throw redirect( + 303, + `/cms/${encodeURIComponent(collection.name)}?${folderQuery}`, + ); + }, + + moveEntry: async ({ locals, params, url, request }) => { + if (!locals.session) throw redirect(302, "/auth"); + + const { collection, ctx, query } = await getConfiguredCollection( + locals.session.userId, + url, + params.collection, + ); + + const formData = await request.formData(); + const rawSlug = formData.get("slug"); + const rawFromFolder = formData.get("fromFolder"); + const rawToFolder = formData.get("toFolder"); + + const slug = typeof rawSlug === "string" ? rawSlug.trim() : ""; + const fromFolder = + typeof rawFromFolder === "string" ? rawFromFolder.trim() : ""; + const toFolder = typeof rawToFolder === "string" ? rawToFolder.trim() : ""; + + if (!slug) { + return fail(400, { + folder: fromFolder, + folderError: "Entry slug is required.", + }); + } + + try { + await moveCollectionEntry(collection, slug, fromFolder, toFolder, ctx); + } catch (cause) { + return fail(400, { + folder: fromFolder, + folderError: + cause instanceof Error ? cause.message : "Could not move the entry.", + }); + } + + await captureServerEvent(locals.session.userId, "collection_entry_moved", { + surface: "collection_list", + }); + + const folderQuery = new URLSearchParams(query); + if (toFolder.length > 0) { + folderQuery.set("folder", toFolder); + } else { + folderQuery.delete("folder"); + } + throw redirect( + 303, + `/cms/${encodeURIComponent(collection.name)}?${folderQuery}`, + ); + }, }; diff --git a/src/routes/cms/[collection]/+page.svelte b/src/routes/cms/[collection]/+page.svelte index 074193e..1e31ac9 100644 --- a/src/routes/cms/[collection]/+page.svelte +++ b/src/routes/cms/[collection]/+page.svelte @@ -14,10 +14,8 @@ import Sparkles from "@lucide/svelte/icons/sparkles"; import Trash from "@lucide/svelte/icons/trash"; import TriangleAlert from "@lucide/svelte/icons/triangle-alert"; import { toast } from "svelte-sonner"; -import { enhance } from "$app/forms"; -import { goto, refreshAll } from "$app/navigation"; -import { CreateFolderDialog } from "$lib/components/custom"; -import { Button } from "$lib/components/ui/button"; +import { CreateFolderDialog } from "#lib/components/custom"; +import { Button } from "#lib/components/ui/button"; import { Dialog, DialogContent, @@ -25,15 +23,16 @@ import { DialogFooter, DialogHeader, DialogTitle, -} from "$lib/components/ui/dialog"; - -import { createLightCmsClient } from "$lib/orpc-client"; +} from "#lib/components/ui/dialog"; +import { createLightCmsClient } from "#lib/orpc-client"; import { buildEntryUrl, buildFolderUrl, buildPayloadQuery, withFolder, -} from "$lib/utils/cms-url"; +} from "#lib/utils/cms-url"; +import { enhance } from "$app/forms"; +import { goto, refreshAll } from "$app/navigation"; import type { PageData } from "./$types"; let { data, form }: { data: PageData; form?: { folderError?: string } | null } = diff --git a/src/routes/cms/[collection]/[slug]/+page.server.ts b/src/routes/cms/[collection]/[slug]/+page.server.ts index 3baee41..4952269 100644 --- a/src/routes/cms/[collection]/[slug]/+page.server.ts +++ b/src/routes/cms/[collection]/[slug]/+page.server.ts @@ -2,95 +2,114 @@ import { error, fail, redirect } from "@sveltejs/kit"; import { message, setError, superValidate } from "sveltekit-superforms"; import { zod4 } from "sveltekit-superforms/adapters"; import { z } from "zod"; -import { buildEntrySchema } from "$lib/schemas/entry"; +import { createDefaultFrontMatter } from "#lib/components/cms/frontmatter.types"; +import { buildEntrySchema } from "#lib/schemas/entry"; import { - buildFrontMatter, - createCollectionEntry, - deleteCollectionEntry, - type FrontMatter, - getCollectionEntry, - moveCollectionEntry, - updateCollectionEntry, -} from "$lib/server/cms"; - -import { createDefaultFrontMatter } from "$lib/components/cms/frontmatter.types"; -import { getConfiguredCollection } from "$lib/server/cms-context"; -import { isGitHubStatus } from "$lib/server/github"; -import { normalizeFolder, resolveEntryPath } from "$lib/server/paths"; -import { captureServerEvent } from "$lib/server/posthog"; + buildFrontMatter, + createCollectionEntry, + deleteCollectionEntry, + type FrontMatter, + getCollectionEntry, + moveCollectionEntry, + updateCollectionEntry, +} from "#lib/server/cms"; +import { getConfiguredCollection } from "#lib/server/cms-context"; +import { isGitHubStatus } from "#lib/server/github"; +import { normalizeFolder, resolveEntryPath } from "#lib/server/paths"; +import { captureServerEvent } from "#lib/server/posthog"; import type { Actions, PageServerLoad } from "./$types"; -const INLINE_FRONTMATTER_KEYS = new Set(["title", "slug", "description", "date", "draft", "tags"]); - -const RESERVED_FRONTMATTER_KEYS = new Set(["body", "__proto__", "constructor", "prototype"]); +const INLINE_FRONTMATTER_KEYS = new Set([ + "title", + "slug", + "description", + "date", + "draft", + "tags", +]); + +const RESERVED_FRONTMATTER_KEYS = new Set([ + "body", + "__proto__", + "constructor", + "prototype", +]); const FRONTMATTER_KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_.-]*$/; function isAdditionalFrontMatterKey(key: string): boolean { - const normalized = key.trim().toLowerCase(); - return ( - normalized.length > 0 && - !INLINE_FRONTMATTER_KEYS.has(normalized) && - !RESERVED_FRONTMATTER_KEYS.has(normalized) - ); + const normalized = key.trim().toLowerCase(); + return ( + normalized.length > 0 && + !INLINE_FRONTMATTER_KEYS.has(normalized) && + !RESERVED_FRONTMATTER_KEYS.has(normalized) + ); } function toEntryValue(value: unknown): string { - if (value === undefined || value === null) return ""; - if (typeof value === "string") return value; - if (typeof value === "object") return JSON.stringify(value); - if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") { - return String(value); - } - return ""; + if (value === undefined || value === null) return ""; + if (typeof value === "string") return value; + if (typeof value === "object") return JSON.stringify(value); + if ( + typeof value === "number" || + typeof value === "boolean" || + typeof value === "bigint" + ) { + return String(value); + } + return ""; } function serializeAdditionalFrontMatter(frontMatter: FrontMatter): string { - const entries = Object.entries(frontMatter) - .filter(([key]) => isAdditionalFrontMatterKey(key)) - .map(([key, value]) => ({ key, value: toEntryValue(value) })); - return JSON.stringify(entries); + const entries = Object.entries(frontMatter) + .filter(([key]) => isAdditionalFrontMatterKey(key)) + .map(([key, value]) => ({ key, value: toEntryValue(value) })); + return JSON.stringify(entries); } function parseEntryValue(value: string): unknown { - const trimmed = value.trim(); - if (trimmed.length === 0) return ""; - try { - return JSON.parse(trimmed); - } catch { - return value; - } + const trimmed = value.trim(); + if (trimmed.length === 0) return ""; + try { + return JSON.parse(trimmed); + } catch { + return value; + } } -function parseAdditionalFrontMatter(rawEntries: string): Array<{ key: string; value: unknown }> { - let parsed: unknown; - try { - parsed = JSON.parse(rawEntries.trim().length > 0 ? rawEntries : "[]"); - } catch { - throw new Error("Additional fields could not be parsed."); - } - if (!Array.isArray(parsed)) { - throw new Error("Additional fields must be a list."); - } - - const fields: Array<{ key: string; value: unknown }> = []; - for (const item of parsed) { - if (typeof item !== "object" || item === null) continue; - const { key, value } = item as { key?: unknown; value?: unknown }; - if (typeof key !== "string") continue; - - const trimmedKey = key.trim(); - if (!isAdditionalFrontMatterKey(trimmedKey)) continue; - if (!FRONTMATTER_KEY_PATTERN.test(trimmedKey)) { - throw new Error(`"${trimmedKey}" is not a valid front matter key.`); - } - - fields.push({ - key: trimmedKey, - value: parseEntryValue(typeof value === "string" ? value : toEntryValue(value)), - }); - } - return fields; +function parseAdditionalFrontMatter( + rawEntries: string, +): Array<{ key: string; value: unknown }> { + let parsed: unknown; + try { + parsed = JSON.parse(rawEntries.trim().length > 0 ? rawEntries : "[]"); + } catch { + throw new Error("Additional fields could not be parsed."); + } + if (!Array.isArray(parsed)) { + throw new Error("Additional fields must be a list."); + } + + const fields: Array<{ key: string; value: unknown }> = []; + for (const item of parsed) { + if (typeof item !== "object" || item === null) continue; + const { key, value } = item as { key?: unknown; value?: unknown }; + if (typeof key !== "string") continue; + + const trimmedKey = key.trim(); + if (!isAdditionalFrontMatterKey(trimmedKey)) continue; + if (!FRONTMATTER_KEY_PATTERN.test(trimmedKey)) { + throw new Error(`"${trimmedKey}" is not a valid front matter key.`); + } + + fields.push({ + key: trimmedKey, + value: parseEntryValue( + typeof value === "string" ? value : toEntryValue(value), + ), + }); + } + return fields; } /** @@ -98,469 +117,526 @@ function parseAdditionalFrontMatter(rawEntries: string): Array<{ key: string; va * replace the hidden form defaults before the frontmatter is built. */ function applyAdditionalFrontMatter( - collection: Parameters[0], - values: Record, - fields: Array<{ key: string; value: unknown }>, + collection: Parameters[0], + values: Record, + fields: Array<{ key: string; value: unknown }>, ): FrontMatter { - const fieldValues: Record = { ...values }; - - for (const field of collection.fields) { - if (isAdditionalFrontMatterKey(field.name)) { - delete fieldValues[field.name]; - } - } - for (const { key, value } of fields) { - fieldValues[key] = value; - } - - const frontMatter = buildFrontMatter(collection, fieldValues); - for (const { key, value } of fields) { - if (!(key in frontMatter)) { - frontMatter[key] = value; - } - } - return frontMatter; + const fieldValues: Record = { ...values }; + + for (const field of collection.fields) { + if (isAdditionalFrontMatterKey(field.name)) { + delete fieldValues[field.name]; + } + } + for (const { key, value } of fields) { + fieldValues[key] = value; + } + + const frontMatter = buildFrontMatter(collection, fieldValues); + for (const { key, value } of fields) { + if (!(key in frontMatter)) { + frontMatter[key] = value; + } + } + return frontMatter; } function buildEditorSchema(collection: Parameters[0]) { - return z.object({ - ...buildEntrySchema(collection).shape, - additionalFrontMatter: z.string().default("[]"), - }); + return z.object({ + ...buildEntrySchema(collection).shape, + additionalFrontMatter: z.string().default("[]"), + }); } export const load: PageServerLoad = async ({ locals, params, url }) => { - if (!locals.session) { - throw redirect(302, "/auth"); - } - - const { collection, ctx, query, selection } = await getConfiguredCollection( - locals.session.userId, - url, - params.collection, - ); - - const folder = normalizeFolder(url.searchParams.get("folder") ?? ""); - const schema = buildEditorSchema(collection); - - if (params.slug === "new") { - const emptyFormData = buildEmptyFormData(collection); - const form = await superValidate(emptyFormData, zod4(schema)); - form.errors = {}; - - const initialFrontMatter = createDefaultFrontMatter(); - for (const field of collection.fields) { - if (field.required && field.name !== "body" && field.name !== "slug") { - if (!(field.name in initialFrontMatter)) { - initialFrontMatter[field.name] = emptyFormData[field.name]; - } - } - } - - return { - isNew: true, - query, - collection, - selection, - folder, - primaryField: collection.view?.primary ?? collection.fields[0].name, - entry: { - slug: String(emptyFormData.slug), - path: resolveEntryPath(collection.path, folder, `${params.slug}.md`), - body: "", - frontMatter: initialFrontMatter as FrontMatter, - }, - form, - }; - } - - const entry = await getCollectionEntry(collection, params.slug, ctx, folder); - if (!entry.frontMatter.slug) { - entry.frontMatter.slug = entry.slug; - } - const formData = { - slug: entry.slug, - body: entry.body, - ...flattenFrontMatter(collection, entry.frontMatter), - additionalFrontMatter: serializeAdditionalFrontMatter(entry.frontMatter), - }; - const form = await superValidate(formData, zod4(schema)); - - return { - isNew: false, - query, - collection, - selection, - folder, - primaryField: collection.view?.primary ?? collection.fields[0].name, - entry, - form, - }; + if (!locals.session) { + throw redirect(302, "/auth"); + } + + const { collection, ctx, query, selection } = await getConfiguredCollection( + locals.session.userId, + url, + params.collection, + ); + + const folder = normalizeFolder(url.searchParams.get("folder") ?? ""); + const schema = buildEditorSchema(collection); + + if (params.slug === "new") { + const emptyFormData = buildEmptyFormData(collection); + const form = await superValidate(emptyFormData, zod4(schema)); + form.errors = {}; + + const initialFrontMatter = createDefaultFrontMatter(); + for (const field of collection.fields) { + if (field.required && field.name !== "body" && field.name !== "slug") { + if (!(field.name in initialFrontMatter)) { + initialFrontMatter[field.name] = emptyFormData[field.name]; + } + } + } + + return { + isNew: true, + query, + collection, + selection, + folder, + primaryField: collection.view?.primary ?? collection.fields[0].name, + entry: { + slug: String(emptyFormData.slug), + path: resolveEntryPath(collection.path, folder, `${params.slug}.md`), + body: "", + frontMatter: initialFrontMatter as FrontMatter, + }, + form, + }; + } + + const entry = await getCollectionEntry(collection, params.slug, ctx, folder); + if (!entry.frontMatter.slug) { + entry.frontMatter.slug = entry.slug; + } + const formData = { + slug: entry.slug, + body: entry.body, + ...flattenFrontMatter(collection, entry.frontMatter), + additionalFrontMatter: serializeAdditionalFrontMatter(entry.frontMatter), + }; + const form = await superValidate(formData, zod4(schema)); + + return { + isNew: false, + query, + collection, + selection, + folder, + primaryField: collection.view?.primary ?? collection.fields[0].name, + entry, + form, + }; }; export const actions: Actions = { - save: async ({ locals, request, params, url }) => { - if (!locals.session) { - throw redirect(302, "/auth"); - } - - const { collection, ctx, query } = await getConfiguredCollection( - locals.session.userId, - url, - params.collection, - ); - - const folder = normalizeFolder(url.searchParams.get("folder") ?? ""); - const collectionUrl = `/cms/${encodeURIComponent(collection.name)}?${appendFolder(query, folder)}`; - - const formData = await request.formData(); - const rawContent = formData.get("content"); - const rawFrontMatter = formData.get("frontMatter"); - - if (typeof rawContent === "string" || typeof rawFrontMatter === "string") { - const body = typeof rawContent === "string" ? rawContent : ""; - let parsedFrontMatter: FrontMatter = {}; - - if (typeof rawFrontMatter === "string" && rawFrontMatter.trim().length > 0) { - try { - parsedFrontMatter = JSON.parse(rawFrontMatter) as FrontMatter; - } catch { - return fail(400, { error: "Invalid front matter format." }); - } - } - - for (const field of collection.fields) { - if (field.required && field.name !== "body" && field.name !== "slug") { - const val = parsedFrontMatter[field.name]; - if ( - val === undefined || - val === null || - (typeof val === "string" && val.trim().length === 0) - ) { - return fail(400, { error: `${field.label ?? field.name} is required.` }); - } - if (field.list && Array.isArray(val) && val.length === 0) { - return fail(400, { error: `${field.label ?? field.name} is required.` }); - } - } - } - - let _slug = params.slug; - if (params.slug === "new") { - const fmSlug = - typeof parsedFrontMatter.slug === "string" ? parsedFrontMatter.slug.trim() : ""; - if (fmSlug.length > 0) { - _slug = fmSlug; - } else if ( - typeof parsedFrontMatter.title === "string" && - parsedFrontMatter.title.trim().length > 0 - ) { - _slug = parsedFrontMatter.title - .toLowerCase() - .trim() - .replace(/[^\w\s-]/g, "") - .replace(/[\s_-]+/g, "-") - .replace(/^-+|-+$/g, ""); - } else { - _slug = Math.floor(Date.now() / 1000).toString(); - } - - try { - await createCollectionEntry(collection, _slug, parsedFrontMatter, body, ctx, folder); - } catch (cause) { - return fail(500, { error: cause instanceof Error ? cause.message : String(cause) }); - } - await captureServerEvent(locals.session.userId, "collection_entry_created"); - throw redirect(303, collectionUrl); - } - - const fmSlug = - typeof parsedFrontMatter.slug === "string" ? parsedFrontMatter.slug.trim() : ""; - if (fmSlug.length > 0) { - _slug = fmSlug; - } - - try { - await updateCollectionEntry( - collection, - params.slug, - _slug, - parsedFrontMatter, - body, - ctx, - folder, - ); - } catch (cause) { - return fail(500, { - error: cause instanceof Error ? cause.message : "Could not update the entry.", - }); - } - - await captureServerEvent(locals.session.userId, "collection_entry_updated"); - - if (_slug !== params.slug) { - const entryUrl = `/cms/${encodeURIComponent(collection.name)}/${encodeURIComponent(_slug)}?${appendFolder(query, folder)}`; - throw redirect(303, entryUrl); - } - - return { success: true, savedAt: new Date().toISOString() }; - } - - const schema = buildEditorSchema(collection); - const form = await superValidate(formData, zod4(schema)); - - if (!form.valid) { - return fail(400, { form }); - } - - const { - slug: _slug, - body, - additionalFrontMatter, - ...rawFieldValues - } = form.data as { - slug: string; - body: string; - additionalFrontMatter: string; - [key: string]: unknown; - }; - - let frontMatter: FrontMatter; - try { - frontMatter = applyAdditionalFrontMatter( - collection, - rawFieldValues, - parseAdditionalFrontMatter(additionalFrontMatter), - ); - } catch (cause) { - return setError( - form, - "", - cause instanceof Error ? cause.message : "Some fields are invalid.", - ); - } - - if (params.slug === "new") { - try { - await createCollectionEntry(collection, _slug, frontMatter, body, ctx, folder); - } catch (cause) { - throw new Error(cause instanceof Error ? cause.message : String(cause)); - } - await captureServerEvent(locals.session.userId, "collection_entry_created"); - throw redirect(303, collectionUrl); - } - - try { - await updateCollectionEntry(collection, params.slug, _slug, frontMatter, body, ctx, folder); - } catch (cause) { - return setError( - form, - "", - cause instanceof Error ? cause.message : "Could not update the entry.", - ); - } - - await captureServerEvent(locals.session.userId, "collection_entry_updated"); - - // If the slug changed, redirect to the new URL - if (_slug !== params.slug) { - const entryUrl = `/cms/${encodeURIComponent(collection.name)}/${encodeURIComponent(_slug)}?${appendFolder(query, folder)}`; - throw redirect(303, entryUrl); - } - - return message(form, "Saved successfully."); - }, - - delete: async ({ locals, params, url }) => { - if (!locals.session) { - throw redirect(302, "/auth"); - } - - if (params.slug === "new") { - throw error(400, "Cannot delete an entry that hasn't been created yet."); - } - - const { collection, ctx, query } = await getConfiguredCollection( - locals.session.userId, - url, - params.collection, - ); - - const folder = normalizeFolder(url.searchParams.get("folder") ?? ""); - - try { - await deleteCollectionEntry(collection, params.slug, ctx, folder); - } catch (cause) { - throw error( - isGitHubStatus(cause, 404) ? 404 : 500, - cause instanceof Error ? cause.message : "Could not delete the entry.", - ); - } - - await captureServerEvent(locals.session.userId, "collection_entry_deleted"); - - const collectionUrl = `/cms/${encodeURIComponent(collection.name)}?${appendFolder(query, folder)}`; - throw redirect(303, collectionUrl); - }, - - move: async ({ locals, request, params, url }) => { - if (!locals.session) { - throw redirect(302, "/auth"); - } - - if (params.slug === "new") { - throw error(400, "Cannot move an entry that has not been created yet."); - } - - const { collection, ctx, query } = await getConfiguredCollection( - locals.session.userId, - url, - params.collection, - ); - - const folder = normalizeFolder(url.searchParams.get("folder") ?? ""); - const formData = await request.formData(); - const rawToFolder = formData.get("destinationFolder") ?? formData.get("toFolder"); - const rawNewSlug = formData.get("newFilename") ?? formData.get("newSlug"); - - const toFolder = typeof rawToFolder === "string" ? rawToFolder.trim() : ""; - let newSlug = params.slug; - if (typeof rawNewSlug === "string" && rawNewSlug.trim().length > 0) { - newSlug = rawNewSlug.trim().replace(/\.md$/, ""); - } - - try { - await moveCollectionEntry(collection, params.slug, folder, toFolder, ctx, newSlug); - } catch (cause) { - return fail(400, { - error: cause instanceof Error ? cause.message : "Could not move entry.", - }); - } - - await captureServerEvent(locals.session.userId, "collection_entry_moved", { - surface: "collection_editor", - }); - - const entryUrl = `/cms/${encodeURIComponent(collection.name)}/${encodeURIComponent(newSlug)}?${appendFolder(query, toFolder)}`; - throw redirect(303, entryUrl); - }, + save: async ({ locals, request, params, url }) => { + if (!locals.session) { + throw redirect(302, "/auth"); + } + + const { collection, ctx, query } = await getConfiguredCollection( + locals.session.userId, + url, + params.collection, + ); + + const folder = normalizeFolder(url.searchParams.get("folder") ?? ""); + const collectionUrl = `/cms/${encodeURIComponent(collection.name)}?${appendFolder(query, folder)}`; + + const formData = await request.formData(); + const rawContent = formData.get("content"); + const rawFrontMatter = formData.get("frontMatter"); + + if (typeof rawContent === "string" || typeof rawFrontMatter === "string") { + const body = typeof rawContent === "string" ? rawContent : ""; + let parsedFrontMatter: FrontMatter = {}; + + if ( + typeof rawFrontMatter === "string" && + rawFrontMatter.trim().length > 0 + ) { + try { + parsedFrontMatter = JSON.parse(rawFrontMatter) as FrontMatter; + } catch { + return fail(400, { error: "Invalid front matter format." }); + } + } + + for (const field of collection.fields) { + if (field.required && field.name !== "body" && field.name !== "slug") { + const val = parsedFrontMatter[field.name]; + if ( + val === undefined || + val === null || + (typeof val === "string" && val.trim().length === 0) + ) { + return fail(400, { + error: `${field.label ?? field.name} is required.`, + }); + } + if (field.list && Array.isArray(val) && val.length === 0) { + return fail(400, { + error: `${field.label ?? field.name} is required.`, + }); + } + } + } + + let _slug = params.slug; + if (params.slug === "new") { + const fmSlug = + typeof parsedFrontMatter.slug === "string" + ? parsedFrontMatter.slug.trim() + : ""; + if (fmSlug.length > 0) { + _slug = fmSlug; + } else if ( + typeof parsedFrontMatter.title === "string" && + parsedFrontMatter.title.trim().length > 0 + ) { + _slug = parsedFrontMatter.title + .toLowerCase() + .trim() + .replace(/[^\w\s-]/g, "") + .replace(/[\s_-]+/g, "-") + .replace(/^-+|-+$/g, ""); + } else { + _slug = Math.floor(Date.now() / 1000).toString(); + } + + try { + await createCollectionEntry( + collection, + _slug, + parsedFrontMatter, + body, + ctx, + folder, + ); + } catch (cause) { + return fail(500, { + error: cause instanceof Error ? cause.message : String(cause), + }); + } + await captureServerEvent( + locals.session.userId, + "collection_entry_created", + ); + throw redirect(303, collectionUrl); + } + + const fmSlug = + typeof parsedFrontMatter.slug === "string" + ? parsedFrontMatter.slug.trim() + : ""; + if (fmSlug.length > 0) { + _slug = fmSlug; + } + + try { + await updateCollectionEntry( + collection, + params.slug, + _slug, + parsedFrontMatter, + body, + ctx, + folder, + ); + } catch (cause) { + return fail(500, { + error: + cause instanceof Error + ? cause.message + : "Could not update the entry.", + }); + } + + await captureServerEvent( + locals.session.userId, + "collection_entry_updated", + ); + + if (_slug !== params.slug) { + const entryUrl = `/cms/${encodeURIComponent(collection.name)}/${encodeURIComponent(_slug)}?${appendFolder(query, folder)}`; + throw redirect(303, entryUrl); + } + + return { success: true, savedAt: new Date().toISOString() }; + } + + const schema = buildEditorSchema(collection); + const form = await superValidate(formData, zod4(schema)); + + if (!form.valid) { + return fail(400, { form }); + } + + const { + slug: _slug, + body, + additionalFrontMatter, + ...rawFieldValues + } = form.data as { + slug: string; + body: string; + additionalFrontMatter: string; + [key: string]: unknown; + }; + + let frontMatter: FrontMatter; + try { + frontMatter = applyAdditionalFrontMatter( + collection, + rawFieldValues, + parseAdditionalFrontMatter(additionalFrontMatter), + ); + } catch (cause) { + return setError( + form, + "", + cause instanceof Error ? cause.message : "Some fields are invalid.", + ); + } + + if (params.slug === "new") { + try { + await createCollectionEntry( + collection, + _slug, + frontMatter, + body, + ctx, + folder, + ); + } catch (cause) { + throw new Error(cause instanceof Error ? cause.message : String(cause)); + } + await captureServerEvent( + locals.session.userId, + "collection_entry_created", + ); + throw redirect(303, collectionUrl); + } + + try { + await updateCollectionEntry( + collection, + params.slug, + _slug, + frontMatter, + body, + ctx, + folder, + ); + } catch (cause) { + return setError( + form, + "", + cause instanceof Error ? cause.message : "Could not update the entry.", + ); + } + + await captureServerEvent(locals.session.userId, "collection_entry_updated"); + + // If the slug changed, redirect to the new URL + if (_slug !== params.slug) { + const entryUrl = `/cms/${encodeURIComponent(collection.name)}/${encodeURIComponent(_slug)}?${appendFolder(query, folder)}`; + throw redirect(303, entryUrl); + } + + return message(form, "Saved successfully."); + }, + + delete: async ({ locals, params, url }) => { + if (!locals.session) { + throw redirect(302, "/auth"); + } + + if (params.slug === "new") { + throw error(400, "Cannot delete an entry that hasn't been created yet."); + } + + const { collection, ctx, query } = await getConfiguredCollection( + locals.session.userId, + url, + params.collection, + ); + + const folder = normalizeFolder(url.searchParams.get("folder") ?? ""); + + try { + await deleteCollectionEntry(collection, params.slug, ctx, folder); + } catch (cause) { + throw error( + isGitHubStatus(cause, 404) ? 404 : 500, + cause instanceof Error ? cause.message : "Could not delete the entry.", + ); + } + + await captureServerEvent(locals.session.userId, "collection_entry_deleted"); + + const collectionUrl = `/cms/${encodeURIComponent(collection.name)}?${appendFolder(query, folder)}`; + throw redirect(303, collectionUrl); + }, + + move: async ({ locals, request, params, url }) => { + if (!locals.session) { + throw redirect(302, "/auth"); + } + + if (params.slug === "new") { + throw error(400, "Cannot move an entry that has not been created yet."); + } + + const { collection, ctx, query } = await getConfiguredCollection( + locals.session.userId, + url, + params.collection, + ); + + const folder = normalizeFolder(url.searchParams.get("folder") ?? ""); + const formData = await request.formData(); + const rawToFolder = + formData.get("destinationFolder") ?? formData.get("toFolder"); + const rawNewSlug = formData.get("newFilename") ?? formData.get("newSlug"); + + const toFolder = typeof rawToFolder === "string" ? rawToFolder.trim() : ""; + let newSlug = params.slug; + if (typeof rawNewSlug === "string" && rawNewSlug.trim().length > 0) { + newSlug = rawNewSlug.trim().replace(/\.md$/, ""); + } + + try { + await moveCollectionEntry( + collection, + params.slug, + folder, + toFolder, + ctx, + newSlug, + ); + } catch (cause) { + return fail(400, { + error: cause instanceof Error ? cause.message : "Could not move entry.", + }); + } + + await captureServerEvent(locals.session.userId, "collection_entry_moved", { + surface: "collection_editor", + }); + + const entryUrl = `/cms/${encodeURIComponent(collection.name)}/${encodeURIComponent(newSlug)}?${appendFolder(query, toFolder)}`; + throw redirect(303, entryUrl); + }, }; function appendFolder(query: string, folder: string) { - const params = new URLSearchParams(query); - if (folder) params.set("folder", folder); - return params.toString(); + const params = new URLSearchParams(query); + if (folder) params.set("folder", folder); + return params.toString(); } function buildEmptyFormData(collection: { - fields: { name: string; type: string; required?: boolean; list?: boolean }[]; + fields: { name: string; type: string; required?: boolean; list?: boolean }[]; }): Record { - // Default new-entry date as UTC — matches the ISO 8601 UTC storage format - // and the UTC-only semantics used for here. - const localNow = new Date().toISOString().replace(/\.\d{3}Z$/, "Z"); - - const data: Record = { - slug: Math.floor(Date.now() / 1000).toString(), - body: "", - }; - - for (const field of collection.fields) { - if (field.name === "body" || field.name === "slug") continue; - if (field.list) { - data[field.name] = []; - continue; - } - switch (field.type) { - case "checkbox": - data[field.name] = false; - break; - case "datetime": - data[field.name] = field.required ? localNow : ""; - break; - case "number": - data[field.name] = field.required ? 0 : ""; - break; - case "json": - data[field.name] = ""; - break; - default: - data[field.name] = ""; - } - } - - return data; + // Default new-entry date as UTC — matches the ISO 8601 UTC storage format + // and the UTC-only semantics used for here. + const localNow = new Date().toISOString().replace(/\.\d{3}Z$/, "Z"); + + const data: Record = { + slug: Math.floor(Date.now() / 1000).toString(), + body: "", + }; + + for (const field of collection.fields) { + if (field.name === "body" || field.name === "slug") continue; + if (field.list) { + data[field.name] = []; + continue; + } + switch (field.type) { + case "checkbox": + data[field.name] = false; + break; + case "datetime": + data[field.name] = field.required ? localNow : ""; + break; + case "number": + data[field.name] = field.required ? 0 : ""; + break; + case "json": + data[field.name] = ""; + break; + default: + data[field.name] = ""; + } + } + + return data; } function toDatetimeLocal(value: string): string { - const spaceUtcMatch = value.match(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})(?::\d{2})? UTC$/); - if (spaceUtcMatch) { - const [, y, m, d, h, min] = spaceUtcMatch; - const utcDate = new Date(`${y}-${m}-${d}T${h}:${min}:00Z`); - if (!Number.isNaN(utcDate.getTime())) { - const pad = (n: number) => String(n).padStart(2, "0"); - return `${y}-${m}-${d}T${pad(utcDate.getUTCHours())}:${pad(utcDate.getUTCMinutes())}`; - } - } - - const dateObj = new Date(value); - if (!Number.isNaN(dateObj.getTime())) { - const pad = (n: number) => String(n).padStart(2, "0"); - return `${dateObj.getUTCFullYear()}-${pad(dateObj.getUTCMonth() + 1)}-${pad(dateObj.getUTCDate())}T${pad(dateObj.getUTCHours())}:${pad(dateObj.getUTCMinutes())}`; - } - - return value.length >= 16 ? value.slice(0, 16) : value; + const spaceUtcMatch = value.match( + /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})(?::\d{2})? UTC$/, + ); + if (spaceUtcMatch) { + const [, y, m, d, h, min] = spaceUtcMatch; + const utcDate = new Date(`${y}-${m}-${d}T${h}:${min}:00Z`); + if (!Number.isNaN(utcDate.getTime())) { + const pad = (n: number) => String(n).padStart(2, "0"); + return `${y}-${m}-${d}T${pad(utcDate.getUTCHours())}:${pad(utcDate.getUTCMinutes())}`; + } + } + + const dateObj = new Date(value); + if (!Number.isNaN(dateObj.getTime())) { + const pad = (n: number) => String(n).padStart(2, "0"); + return `${dateObj.getUTCFullYear()}-${pad(dateObj.getUTCMonth() + 1)}-${pad(dateObj.getUTCDate())}T${pad(dateObj.getUTCHours())}:${pad(dateObj.getUTCMinutes())}`; + } + + return value.length >= 16 ? value.slice(0, 16) : value; } function flattenFrontMatter( - collection: { fields: { name: string; type: string; list?: boolean }[] }, - frontMatter: FrontMatter, + collection: { fields: { name: string; type: string; list?: boolean }[] }, + frontMatter: FrontMatter, ): Record { - const result: Record = {}; - for (const field of collection.fields) { - if (field.name === "body" || field.name === "slug") continue; - const value = frontMatter[field.name]; - if (value === undefined || value === null) { - if (field.list) { - result[field.name] = []; - } else if (field.type === "checkbox") { - result[field.name] = false; - } else { - result[field.name] = ""; - } - continue; - } - if (field.type === "datetime" && typeof value === "string") { - result[field.name] = toDatetimeLocal(value); - continue; - } - if (field.type === "json") { - if (typeof value === "string") { - result[field.name] = value; - } else { - try { - result[field.name] = JSON.stringify(value, null, 2); - } catch { - // eslint-disable-next-line @typescript-eslint/no-base-to-string - result[field.name] = String(value); - } - } - continue; - } - if (field.type === "number") { - result[field.name] = value; - continue; - } - if (field.list && Array.isArray(value)) { - result[field.name] = value; - continue; - } - if (field.list && typeof value === "string") { - result[field.name] = [value]; - continue; - } - if (field.type === "checkbox") { - result[field.name] = Boolean(value); - continue; - } - result[field.name] = value; - } - return result; + const result: Record = {}; + for (const field of collection.fields) { + if (field.name === "body" || field.name === "slug") continue; + const value = frontMatter[field.name]; + if (value === undefined || value === null) { + if (field.list) { + result[field.name] = []; + } else if (field.type === "checkbox") { + result[field.name] = false; + } else { + result[field.name] = ""; + } + continue; + } + if (field.type === "datetime" && typeof value === "string") { + result[field.name] = toDatetimeLocal(value); + continue; + } + if (field.type === "json") { + if (typeof value === "string") { + result[field.name] = value; + } else { + try { + result[field.name] = JSON.stringify(value, null, 2); + } catch { + // eslint-disable-next-line @typescript-eslint/no-base-to-string + result[field.name] = String(value); + } + } + continue; + } + if (field.type === "number") { + result[field.name] = value; + continue; + } + if (field.list && Array.isArray(value)) { + result[field.name] = value; + continue; + } + if (field.list && typeof value === "string") { + result[field.name] = [value]; + continue; + } + if (field.type === "checkbox") { + result[field.name] = Boolean(value); + continue; + } + result[field.name] = value; + } + return result; } diff --git a/src/routes/cms/[collection]/[slug]/+page.svelte b/src/routes/cms/[collection]/[slug]/+page.svelte index ec6d51b..1dc985d 100644 --- a/src/routes/cms/[collection]/[slug]/+page.svelte +++ b/src/routes/cms/[collection]/[slug]/+page.svelte @@ -1,9 +1,9 @@