doccupine 0.0.139 → 0.0.141
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -7
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +191 -0
- package/dist/index.d.ts +3 -7
- package/dist/index.js +5 -1895
- package/dist/lib/config-manager.d.ts +1 -0
- package/dist/lib/config-manager.js +63 -3
- package/dist/lib/generated-artifacts.d.ts +26 -0
- package/dist/lib/generated-artifacts.js +147 -0
- package/dist/lib/layout.js +30 -30
- package/dist/lib/metadata.js +58 -30
- package/dist/lib/openapi-types.d.ts +2 -2
- package/dist/lib/openapi.d.ts +6 -3
- package/dist/lib/openapi.js +330 -50
- package/dist/lib/output-safety.d.ts +15 -0
- package/dist/lib/output-safety.js +428 -0
- package/dist/lib/structures.js +11 -0
- package/dist/lib/utils.d.ts +18 -0
- package/dist/lib/utils.js +125 -0
- package/dist/mdx-to-nextjs-generator.d.ts +166 -0
- package/dist/mdx-to-nextjs-generator.js +2229 -0
- package/dist/templates/app/api/gate/route.d.ts +1 -1
- package/dist/templates/app/api/gate/route.js +18 -6
- package/dist/templates/app/api/mcp/route.d.ts +1 -1
- package/dist/templates/app/api/mcp/route.js +181 -111
- package/dist/templates/app/api/playground/route.d.ts +1 -1
- package/dist/templates/app/api/playground/route.js +45 -13
- package/dist/templates/app/api/rag/route.d.ts +1 -1
- package/dist/templates/app/api/rag/route.js +102 -25
- package/dist/templates/app/api/search/route.d.ts +1 -1
- package/dist/templates/app/api/search/route.js +5 -0
- package/dist/templates/app/robots.d.ts +1 -1
- package/dist/templates/app/robots.js +1 -26
- package/dist/templates/app/theme.d.ts +1 -1
- package/dist/templates/app/theme.js +31 -19
- package/dist/templates/components/Chat.d.ts +1 -1
- package/dist/templates/components/Chat.js +411 -104
- package/dist/templates/components/Docs.d.ts +1 -1
- package/dist/templates/components/Docs.js +56 -13
- package/dist/templates/components/SearchDocs.d.ts +1 -1
- package/dist/templates/components/SearchDocs.js +63 -11
- package/dist/templates/components/SearchModalContent.d.ts +1 -1
- package/dist/templates/components/SearchModalContent.js +191 -49
- package/dist/templates/components/SideBar.d.ts +1 -1
- package/dist/templates/components/SideBar.js +8 -2
- package/dist/templates/components/layout/Accordion.d.ts +1 -1
- package/dist/templates/components/layout/Accordion.js +26 -3
- package/dist/templates/components/layout/ApiPlayground.d.ts +1 -1
- package/dist/templates/components/layout/ApiPlayground.js +4 -7
- package/dist/templates/components/layout/Badge.d.ts +1 -1
- package/dist/templates/components/layout/Badge.js +1 -1
- package/dist/templates/components/layout/Button.d.ts +1 -1
- package/dist/templates/components/layout/Button.js +4 -4
- package/dist/templates/components/layout/Callout.d.ts +1 -1
- package/dist/templates/components/layout/Callout.js +6 -6
- package/dist/templates/components/layout/Card.d.ts +1 -1
- package/dist/templates/components/layout/Card.js +9 -4
- package/dist/templates/components/layout/CherryThemeProvider.d.ts +1 -1
- package/dist/templates/components/layout/CherryThemeProvider.js +63 -12
- package/dist/templates/components/layout/Code.d.ts +1 -1
- package/dist/templates/components/layout/Code.js +5 -5
- package/dist/templates/components/layout/CopyButton.d.ts +1 -1
- package/dist/templates/components/layout/CopyButton.js +1 -1
- package/dist/templates/components/layout/DemoTheme.d.ts +1 -1
- package/dist/templates/components/layout/DemoTheme.js +8 -28
- package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
- package/dist/templates/components/layout/DocsComponents.js +57 -18
- package/dist/templates/components/layout/GlobalStyles.d.ts +1 -1
- package/dist/templates/components/layout/GlobalStyles.js +15 -9
- package/dist/templates/components/layout/Prompt.d.ts +1 -1
- package/dist/templates/components/layout/Prompt.js +4 -7
- package/dist/templates/components/layout/Steps.d.ts +1 -1
- package/dist/templates/components/layout/Steps.js +7 -1
- package/dist/templates/components/layout/Tabs.d.ts +1 -1
- package/dist/templates/components/layout/Tabs.js +108 -19
- package/dist/templates/env.example.d.ts +1 -1
- package/dist/templates/env.example.js +11 -0
- package/dist/templates/eslint.config.d.ts +1 -1
- package/dist/templates/eslint.config.js +20 -0
- package/dist/templates/gitignore.d.ts +1 -1
- package/dist/templates/gitignore.js +4 -3
- package/dist/templates/lib/access.d.ts +1 -0
- package/dist/templates/lib/access.js +41 -0
- package/dist/templates/mdx/ai-assistant.mdx.d.ts +1 -1
- package/dist/templates/mdx/ai-assistant.mdx.js +17 -1
- package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
- package/dist/templates/mdx/api-playground.mdx.js +5 -3
- package/dist/templates/mdx/authentication.mdx.d.ts +1 -1
- package/dist/templates/mdx/authentication.mdx.js +5 -3
- package/dist/templates/mdx/commands.mdx.d.ts +1 -1
- package/dist/templates/mdx/commands.mdx.js +20 -6
- package/dist/templates/mdx/components.mdx.d.ts +1 -1
- package/dist/templates/mdx/components.mdx.js +3 -0
- package/dist/templates/mdx/deployment-and-hosting.mdx.d.ts +1 -1
- package/dist/templates/mdx/deployment-and-hosting.mdx.js +2 -2
- package/dist/templates/mdx/globals.mdx.d.ts +1 -1
- package/dist/templates/mdx/globals.mdx.js +14 -11
- package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
- package/dist/templates/mdx/model-context-protocol.mdx.js +22 -35
- package/dist/templates/mdx/platform/ai-assistant.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/ai-assistant.mdx.js +23 -0
- package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/api-playground.mdx.js +7 -0
- package/dist/templates/mdx/platform/authentication.mdx.d.ts +1 -0
- package/dist/templates/mdx/platform/authentication.mdx.js +63 -0
- package/dist/templates/mdx/platform/build-and-deploy.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/build-and-deploy.mdx.js +1 -1
- package/dist/templates/mdx/platform/import-from-github.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/import-from-github.mdx.js +2 -2
- package/dist/templates/mdx/platform/index.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/index.mdx.js +1 -0
- package/dist/templates/mdx/platform/mcp.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/mcp.mdx.js +2 -1
- package/dist/templates/mdx/platform/navigation-settings.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/navigation-settings.mdx.js +12 -1
- package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/publishing.mdx.js +43 -10
- package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/self-updating-docs.mdx.js +48 -9
- package/dist/templates/mdx/sections.mdx.d.ts +1 -1
- package/dist/templates/mdx/sections.mdx.js +4 -0
- package/dist/templates/mdx/space.mdx.d.ts +1 -0
- package/dist/templates/mdx/space.mdx.js +125 -0
- package/dist/templates/mdx/tabs.mdx.d.ts +1 -1
- package/dist/templates/mdx/tabs.mdx.js +4 -0
- package/dist/templates/next.config.js +20 -8
- package/dist/templates/package.js +3 -3
- package/dist/templates/prettierignore.d.ts +1 -1
- package/dist/templates/prettierignore.js +1 -0
- package/dist/templates/proxy.js +47 -19
- package/dist/templates/scripts/build-docs-index.d.ts +1 -1
- package/dist/templates/scripts/build-docs-index.js +1 -0
- package/dist/templates/services/mcp/docsContentStub.d.ts +1 -0
- package/dist/templates/services/mcp/docsContentStub.js +1 -0
- package/dist/templates/services/mcp/server.d.ts +1 -1
- package/dist/templates/services/mcp/server.js +140 -83
- package/dist/templates/services/mcp/tools.d.ts +1 -1
- package/dist/templates/services/mcp/tools.js +65 -137
- package/dist/templates/utils/playgroundAllowlist.d.ts +1 -1
- package/dist/templates/utils/playgroundAllowlist.js +13 -4
- package/dist/templates/utils/rateLimit.d.ts +1 -1
- package/dist/templates/utils/rateLimit.js +40 -3
- package/dist/templates/utils/requestBody.d.ts +1 -0
- package/dist/templates/utils/requestBody.js +56 -0
- package/dist/templates/utils/ssrfGuard.d.ts +1 -1
- package/dist/templates/utils/ssrfGuard.js +138 -33
- package/package.json +14 -9
- package/dist/lib/mdxToMarkdown.d.ts +0 -1
- package/dist/lib/mdxToMarkdown.js +0 -134
- package/dist/templates/mdx/image-and-embeds.mdx.d.ts +0 -1
- package/dist/templates/mdx/image-and-embeds.mdx.js +0 -118
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const ragRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { z } from \"zod\";\nimport { getLLMConfig, createChatModel } from \"@/services/llm\";\nimport {\n searchDocs,\n ensureDocsIndex,\n getIndexStatus,\n} from \"@/services/mcp/server\";\nimport { rateLimit } from \"@/utils/rateLimit\";\nimport { config } from \"@/utils/config\";\n\nconst messageSchema = z.object({\n role: z.enum([\"user\", \"assistant\"]),\n content: z.string().max(4000),\n});\n\nconst ragSchema = z.object({\n question: z.string().min(1).max(2000),\n history: z.array(messageSchema).max(20).optional(),\n refresh: z.boolean().optional(),\n});\n\nconst projectName = config.name || \"Doccupine\";\n\nconst systemContext = `You are AI Assistant, a documentation assistant for ${projectName}, Your name is ${projectName} AI Assistant.\n\n## Core Rules\n1. Answer ONLY from the provided context. Never fabricate information.\n2. If the answer isn't in the context, say so clearly and suggest relevant sections or pages the user might check.\n3. If the question is ambiguous, ask a brief clarifying question before answering.\n\n## Response Style\n- Be concise and direct. Lead with the answer, then provide details if needed.\n- Use code examples from the context when relevant.\n- Match the technical level of the user's question.\n\n## MDX/Code Formatting\nWhen including code blocks in your response:\n- Never nest fenced code blocks (triple backticks) inside other fenced code blocks.\n- If you need to show MDX source that itself contains code blocks, use indented code blocks or escape the inner backticks.\n- All output must be valid MDX that renders correctly.\n\n## Internal Links\nEach context chunk includes a \"URL:\" line with the pre-computed page URL. Use it directly when linking:\n- Format links as markdown: [Page Title](/slug/).\n- Never expose raw file paths like \"/app/.../page.tsx\" to the user.\n- Never include route group segments in parentheses, like \"(site)\", in any link - they are internal directory names and do not exist in real URLs. Use \"/code/\" not \"/(site)/code/\".\n- Do NOT add a \"Related Pages\" section at the end - sources are shown separately by the UI.\n\n## Greetings & Small Talk\nIf the user sends a greeting or non-documentation question, respond briefly and ask how you can help with the documentation.`;\n\n// LangChain + the MCP SDK require the Node.js runtime (not edge).\nexport const runtime = \"nodejs\";\n// Safety net for the streaming function (Vercel-only; ignored elsewhere).\n// The heartbeat below, not this value, is what prevents proxy 524 timeouts.\nexport const maxDuration = 60;\n\nexport async function POST(req: Request) {\n // Rate limit by IP\n const ip =\n req.headers.get(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ?? \"unknown\";\n const { allowed, retryAfter } = rateLimit(ip);\n if (!allowed) {\n return NextResponse.json(\n { error: \"Too many requests\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n // Validate the request up front so genuine client/config errors still return\n // real status codes before we commit to a 200 streaming response.\n let body: unknown;\n try {\n body = await req.json();\n } catch {\n return NextResponse.json({ error: \"Invalid JSON body\" }, { status: 400 });\n }\n\n const parsed = ragSchema.safeParse(body);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid input\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n const { question, history, refresh } = parsed.data;\n\n let llmConfig;\n try {\n llmConfig = getLLMConfig();\n } catch (error: unknown) {\n const message =\n error instanceof Error ? error.message : \"LLM configuration error\";\n return NextResponse.json({ error: message }, { status: 500 });\n }\n\n const encoder = new TextEncoder();\n let heartbeat: ReturnType<typeof setInterval> | null = null;\n let streamClosed = false;\n\n // Return the streaming response immediately and do ALL slow work (indexing,\n // search, model streaming) inside start(). This flushes headers + a first\n // byte right away so edge proxies never hit their time-to-first-byte timeout.\n const readableStream = new ReadableStream({\n async start(controller) {\n const safeEnqueue = (payload: string) => {\n if (streamClosed) return;\n try {\n controller.enqueue(encoder.encode(payload));\n } catch {\n // Stream already closed or cancelled - stop emitting.\n streamClosed = true;\n if (heartbeat) clearInterval(heartbeat);\n }\n };\n\n // Keep the connection alive while the index and model warm up.\n heartbeat = setInterval(() => safeEnqueue(`: keep-alive\\n\\n`), 15000);\n\n try {\n // First byte, before any slow work - satisfies the proxy TTFB window.\n safeEnqueue(`: connected\\n\\n`);\n\n // Ensure docs are indexed (loads precomputed embeddings when present).\n await ensureDocsIndex(Boolean(refresh));\n\n // Use MCP search_docs tool to find relevant documentation\n const searchResults = await searchDocs(question, 6);\n\n // Build context from search results\n const context = searchResults\n .map(({ chunk, score }) => {\n const slug = chunk.uri.replace(\"docs://\", \"\").replace(/^\\/+/, \"\");\n const url = slug ? `/${slug}/` : \"/\";\n return `File: ${chunk.path}\\nURL: ${url}\\nScore: ${score.toFixed(3)}\\n----\\n${chunk.text}`;\n })\n .join(\"\\n\\n================\\n\\n\");\n\n // Build metadata from MCP search results and send it before the answer.\n const indexStatus = getIndexStatus();\n const metadata = {\n sources: searchResults.map(({ chunk, score }) => ({\n id: chunk.id,\n path: chunk.path,\n uri: chunk.uri,\n score,\n })),\n chunkCount: indexStatus.chunkCount,\n };\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"metadata\", data: metadata })}\\n\\n`,\n );\n\n // Assemble the prompt, including conversation history for multi-turn.\n const prompt: {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n }[] = [\n {\n role: \"system\" as const,\n content: systemContext,\n },\n ];\n if (history && history.length > 0) {\n for (const msg of history) {\n prompt.push({\n role: msg.role,\n content: msg.content,\n });\n }\n }\n prompt.push({\n role: \"user\" as const,\n content: `Question: ${question}\\n\\nContext:\\n${context}`,\n });\n\n // Create chat model and stream the response.\n const llm = createChatModel(llmConfig);\n const stream = await llm.stream(prompt);\n for await (const chunk of stream) {\n const content = chunk?.content || \"\";\n if (content) {\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"content\", data: content })}\\n\\n`,\n );\n }\n }\n\n safeEnqueue(`data: ${JSON.stringify({ type: \"done\" })}\\n\\n`);\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : \"Stream error\";\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"error\", data: message })}\\n\\n`,\n );\n } finally {\n if (heartbeat) clearInterval(heartbeat);\n streamClosed = true;\n try {\n controller.close();\n } catch {\n // Already closed.\n }\n }\n },\n cancel() {\n streamClosed = true;\n if (heartbeat) clearInterval(heartbeat);\n },\n });\n\n return new Response(readableStream, {\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache, no-transform\",\n },\n });\n}\n\nexport async function GET() {\n const status = getIndexStatus();\n return NextResponse.json({\n ready: status.ready,\n chunks: status.chunkCount,\n reason: status.reason,\n });\n}\n";
|
|
1
|
+
export declare const ragRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { z } from \"zod\";\nimport { getLLMConfig, createChatModel } from \"@/services/llm\";\nimport {\n searchDocs,\n ensureDocsIndex,\n getIndexStatus,\n} from \"@/services/mcp/server\";\nimport { rateLimit } from \"@/utils/rateLimit\";\nimport { config } from \"@/utils/config\";\nimport { isSiteRequestAuthorized } from \"@/lib/access\";\nimport { timingSafeEqual } from \"@/lib/siteGate\";\nimport { readJsonBody, RequestTooLargeError } from \"@/utils/requestBody\";\n\nconst MAX_RAG_REQUEST_BYTES = 32 * 1024;\n\nconst messageSchema = z\n .object({\n role: z.enum([\"user\", \"assistant\"]),\n content: z.string().max(4000),\n })\n .strict();\n\nconst ragSchema = z\n .object({\n question: z.string().min(1).max(2000),\n history: z.array(messageSchema).max(20).optional(),\n })\n .strict();\n\nfunction bearerToken(req: Request): string | null {\n const authorization = req.headers.get(\"authorization\");\n return authorization?.startsWith(\"Bearer \")\n ? authorization.slice(\"Bearer \".length)\n : null;\n}\n\nasync function isRagRequestAuthorized(req: Request): Promise<boolean> {\n const siteAuthorized = await isSiteRequestAuthorized();\n if (process.env.SITE_PASSWORD && siteAuthorized) return true;\n\n const apiKey = process.env.RAG_API_KEY;\n if (apiKey) {\n const token = bearerToken(req);\n return token !== null && timingSafeEqual(token, apiKey);\n }\n return siteAuthorized;\n}\n\nconst projectName = config.name || \"Doccupine\";\n\nconst systemContext = `You are AI Assistant, a documentation assistant for ${projectName}, Your name is ${projectName} AI Assistant.\n\n## Core Rules\n1. Answer ONLY from the provided context. Never fabricate information.\n2. If the answer isn't in the context, say so clearly and suggest relevant sections or pages the user might check.\n3. If the question is ambiguous, ask a brief clarifying question before answering.\n\n## Response Style\n- Be concise and direct. Lead with the answer, then provide details if needed.\n- Use code examples from the context when relevant.\n- Match the technical level of the user's question.\n\n## MDX/Code Formatting\nWhen including code blocks in your response:\n- Never nest fenced code blocks (triple backticks) inside other fenced code blocks.\n- If you need to show MDX source that itself contains code blocks, use indented code blocks or escape the inner backticks.\n- All output must be valid MDX that renders correctly.\n\n## Internal Links\nEach context chunk includes a \"URL:\" line with the pre-computed page URL. Use it directly when linking:\n- Format links as markdown: [Page Title](/slug/).\n- Never expose raw file paths like \"/app/.../page.tsx\" to the user.\n- Never include route group segments in parentheses, like \"(site)\", in any link - they are internal directory names and do not exist in real URLs. Use \"/code/\" not \"/(site)/code/\".\n- Do NOT add a \"Related Pages\" section at the end - sources are shown separately by the UI.\n\n## Greetings & Small Talk\nIf the user sends a greeting or non-documentation question, respond briefly and ask how you can help with the documentation.`;\n\n// Maps provider/stream failures to fixed visitor-safe messages. Raw provider\n// errors can include API-key fragments, org ids, and billing URLs, so only\n// these strings ever reach the client; the full error goes to the server log.\nfunction friendlyLLMError(error: unknown): string {\n const raw = error instanceof Error ? error.message : String(error);\n if (/\\b401\\b|api.?key|authenticat|unauthorized/i.test(raw)) {\n return \"The assistant's model provider rejected its API key. If you are the site owner, check the server logs and your API key configuration.\";\n }\n if (/\\b429\\b|quota|rate.?limit|billing/i.test(raw)) {\n return \"The assistant's model provider is rate limiting requests right now. Please try again in a moment.\";\n }\n if (\n /timed?.?out|ETIMEDOUT|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(raw)\n ) {\n return \"The assistant could not reach its model provider. Please try again.\";\n }\n return \"The assistant hit an unexpected error. Please try again.\";\n}\n\n// LangChain + the MCP SDK require the Node.js runtime (not edge).\nexport const runtime = \"nodejs\";\n// Safety net for the streaming function (Vercel-only; ignored elsewhere).\n// The heartbeat below, not this value, is what prevents proxy 524 timeouts.\nexport const maxDuration = 60;\n\nexport async function POST(req: Request) {\n if (!(await isRagRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const { allowed, retryAfter } = rateLimit(req);\n if (!allowed) {\n return NextResponse.json(\n { error: \"Too many requests\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n // Validate the request up front so genuine client/config errors still return\n // real status codes before we commit to a 200 streaming response.\n let body: unknown;\n try {\n body = await readJsonBody(req, MAX_RAG_REQUEST_BYTES);\n } catch (error: unknown) {\n if (req.signal.aborted) throw error;\n if (error instanceof RequestTooLargeError) {\n return NextResponse.json(\n { error: \"Request body too large\" },\n { status: 413 },\n );\n }\n return NextResponse.json({ error: \"Invalid JSON body\" }, { status: 400 });\n }\n\n const parsed = ragSchema.safeParse(body);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid input\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n const { question, history } = parsed.data;\n\n let llmConfig;\n try {\n llmConfig = getLLMConfig();\n } catch (error: unknown) {\n // Setup details (provider names, env var names) stay in the server log.\n console.error(\"[doccupine] LLM configuration error:\", error);\n return NextResponse.json(\n {\n error:\n \"The AI assistant is not configured on this site. If you are the site owner, check the server logs.\",\n },\n { status: 500 },\n );\n }\n\n const encoder = new TextEncoder();\n let heartbeat: ReturnType<typeof setInterval> | null = null;\n let streamClosed = false;\n const workController = new AbortController();\n const abortWork = () => workController.abort(req.signal.reason);\n req.signal.addEventListener(\"abort\", abortWork, { once: true });\n if (req.signal.aborted) abortWork();\n const { signal } = workController;\n\n // Return the streaming response immediately and do ALL slow work (indexing,\n // search, model streaming) inside start(). This flushes headers + a first\n // byte right away so edge proxies never hit their time-to-first-byte timeout.\n const readableStream = new ReadableStream({\n async start(controller) {\n const safeEnqueue = (payload: string) => {\n if (streamClosed) return;\n try {\n controller.enqueue(encoder.encode(payload));\n } catch {\n // Stream already closed or cancelled - stop emitting.\n streamClosed = true;\n workController.abort();\n if (heartbeat) clearInterval(heartbeat);\n }\n };\n\n // Keep the connection alive while the index and model warm up.\n heartbeat = setInterval(() => safeEnqueue(`: keep-alive\\n\\n`), 15000);\n\n try {\n // First byte, before any slow work - satisfies the proxy TTFB window.\n safeEnqueue(`: connected\\n\\n`);\n\n // Ensure docs are indexed (loads precomputed embeddings when present).\n await ensureDocsIndex(false, signal);\n signal.throwIfAborted();\n\n // Use MCP search_docs tool to find relevant documentation\n const searchResults = await searchDocs(question, 6, signal);\n signal.throwIfAborted();\n\n // Build context from search results\n const context = searchResults\n .map(({ chunk, score }) => {\n const slug = chunk.uri.replace(\"docs://\", \"\").replace(/^\\/+/, \"\");\n const url = slug ? `/${slug}/` : \"/\";\n return `File: ${chunk.path}\\nURL: ${url}\\nScore: ${score.toFixed(3)}\\n----\\n${chunk.text}`;\n })\n .join(\"\\n\\n================\\n\\n\");\n\n // Build metadata from MCP search results and send it before the answer.\n const indexStatus = getIndexStatus();\n const metadata = {\n sources: searchResults.map(({ chunk, score }) => ({\n id: chunk.id,\n path: chunk.path,\n uri: chunk.uri,\n score,\n })),\n chunkCount: indexStatus.chunkCount,\n };\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"metadata\", data: metadata })}\\n\\n`,\n );\n\n // Assemble the prompt, including conversation history for multi-turn.\n const prompt: {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n }[] = [\n {\n role: \"system\" as const,\n content: systemContext,\n },\n ];\n if (history && history.length > 0) {\n for (const msg of history) {\n prompt.push({\n role: msg.role,\n content: msg.content,\n });\n }\n }\n prompt.push({\n role: \"user\" as const,\n content: `Question: ${question}\\n\\nContext:\\n${context}`,\n });\n\n // Create chat model and stream the response.\n const llm = createChatModel(llmConfig);\n const stream = await llm.stream(prompt, { signal });\n for await (const chunk of stream) {\n signal.throwIfAborted();\n const content = chunk?.content || \"\";\n if (content) {\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"content\", data: content })}\\n\\n`,\n );\n }\n }\n\n signal.throwIfAborted();\n safeEnqueue(`data: ${JSON.stringify({ type: \"done\" })}\\n\\n`);\n } catch (error: unknown) {\n if (signal.aborted) return;\n console.error(\"[doccupine] RAG stream error:\", error);\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"error\", data: friendlyLLMError(error) })}\\n\\n`,\n );\n } finally {\n if (heartbeat) clearInterval(heartbeat);\n streamClosed = true;\n req.signal.removeEventListener(\"abort\", abortWork);\n try {\n controller.close();\n } catch {\n // Already closed.\n }\n }\n },\n cancel() {\n streamClosed = true;\n workController.abort();\n if (heartbeat) clearInterval(heartbeat);\n },\n });\n\n return new Response(readableStream, {\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache, no-transform\",\n },\n });\n}\n\nexport async function GET(req: Request) {\n if (!(await isRagRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const status = getIndexStatus();\n return NextResponse.json({\n ready: status.ready,\n chunks: status.chunkCount,\n reason: status.reason,\n });\n}\n";
|
|
@@ -8,17 +8,44 @@ import {
|
|
|
8
8
|
} from "@/services/mcp/server";
|
|
9
9
|
import { rateLimit } from "@/utils/rateLimit";
|
|
10
10
|
import { config } from "@/utils/config";
|
|
11
|
+
import { isSiteRequestAuthorized } from "@/lib/access";
|
|
12
|
+
import { timingSafeEqual } from "@/lib/siteGate";
|
|
13
|
+
import { readJsonBody, RequestTooLargeError } from "@/utils/requestBody";
|
|
11
14
|
|
|
12
|
-
const
|
|
13
|
-
role: z.enum(["user", "assistant"]),
|
|
14
|
-
content: z.string().max(4000),
|
|
15
|
-
});
|
|
15
|
+
const MAX_RAG_REQUEST_BYTES = 32 * 1024;
|
|
16
16
|
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
})
|
|
17
|
+
const messageSchema = z
|
|
18
|
+
.object({
|
|
19
|
+
role: z.enum(["user", "assistant"]),
|
|
20
|
+
content: z.string().max(4000),
|
|
21
|
+
})
|
|
22
|
+
.strict();
|
|
23
|
+
|
|
24
|
+
const ragSchema = z
|
|
25
|
+
.object({
|
|
26
|
+
question: z.string().min(1).max(2000),
|
|
27
|
+
history: z.array(messageSchema).max(20).optional(),
|
|
28
|
+
})
|
|
29
|
+
.strict();
|
|
30
|
+
|
|
31
|
+
function bearerToken(req: Request): string | null {
|
|
32
|
+
const authorization = req.headers.get("authorization");
|
|
33
|
+
return authorization?.startsWith("Bearer ")
|
|
34
|
+
? authorization.slice("Bearer ".length)
|
|
35
|
+
: null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function isRagRequestAuthorized(req: Request): Promise<boolean> {
|
|
39
|
+
const siteAuthorized = await isSiteRequestAuthorized();
|
|
40
|
+
if (process.env.SITE_PASSWORD && siteAuthorized) return true;
|
|
41
|
+
|
|
42
|
+
const apiKey = process.env.RAG_API_KEY;
|
|
43
|
+
if (apiKey) {
|
|
44
|
+
const token = bearerToken(req);
|
|
45
|
+
return token !== null && timingSafeEqual(token, apiKey);
|
|
46
|
+
}
|
|
47
|
+
return siteAuthorized;
|
|
48
|
+
}
|
|
22
49
|
|
|
23
50
|
const projectName = config.name || "Doccupine";
|
|
24
51
|
|
|
@@ -50,6 +77,25 @@ Each context chunk includes a "URL:" line with the pre-computed page URL. Use it
|
|
|
50
77
|
## Greetings & Small Talk
|
|
51
78
|
If the user sends a greeting or non-documentation question, respond briefly and ask how you can help with the documentation.\`;
|
|
52
79
|
|
|
80
|
+
// Maps provider/stream failures to fixed visitor-safe messages. Raw provider
|
|
81
|
+
// errors can include API-key fragments, org ids, and billing URLs, so only
|
|
82
|
+
// these strings ever reach the client; the full error goes to the server log.
|
|
83
|
+
function friendlyLLMError(error: unknown): string {
|
|
84
|
+
const raw = error instanceof Error ? error.message : String(error);
|
|
85
|
+
if (/\\b401\\b|api.?key|authenticat|unauthorized/i.test(raw)) {
|
|
86
|
+
return "The assistant's model provider rejected its API key. If you are the site owner, check the server logs and your API key configuration.";
|
|
87
|
+
}
|
|
88
|
+
if (/\\b429\\b|quota|rate.?limit|billing/i.test(raw)) {
|
|
89
|
+
return "The assistant's model provider is rate limiting requests right now. Please try again in a moment.";
|
|
90
|
+
}
|
|
91
|
+
if (
|
|
92
|
+
/timed?.?out|ETIMEDOUT|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(raw)
|
|
93
|
+
) {
|
|
94
|
+
return "The assistant could not reach its model provider. Please try again.";
|
|
95
|
+
}
|
|
96
|
+
return "The assistant hit an unexpected error. Please try again.";
|
|
97
|
+
}
|
|
98
|
+
|
|
53
99
|
// LangChain + the MCP SDK require the Node.js runtime (not edge).
|
|
54
100
|
export const runtime = "nodejs";
|
|
55
101
|
// Safety net for the streaming function (Vercel-only; ignored elsewhere).
|
|
@@ -57,10 +103,11 @@ export const runtime = "nodejs";
|
|
|
57
103
|
export const maxDuration = 60;
|
|
58
104
|
|
|
59
105
|
export async function POST(req: Request) {
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
106
|
+
if (!(await isRagRequestAuthorized(req))) {
|
|
107
|
+
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const { allowed, retryAfter } = rateLimit(req);
|
|
64
111
|
if (!allowed) {
|
|
65
112
|
return NextResponse.json(
|
|
66
113
|
{ error: "Too many requests" },
|
|
@@ -72,8 +119,15 @@ export async function POST(req: Request) {
|
|
|
72
119
|
// real status codes before we commit to a 200 streaming response.
|
|
73
120
|
let body: unknown;
|
|
74
121
|
try {
|
|
75
|
-
body = await req
|
|
76
|
-
} catch {
|
|
122
|
+
body = await readJsonBody(req, MAX_RAG_REQUEST_BYTES);
|
|
123
|
+
} catch (error: unknown) {
|
|
124
|
+
if (req.signal.aborted) throw error;
|
|
125
|
+
if (error instanceof RequestTooLargeError) {
|
|
126
|
+
return NextResponse.json(
|
|
127
|
+
{ error: "Request body too large" },
|
|
128
|
+
{ status: 413 },
|
|
129
|
+
);
|
|
130
|
+
}
|
|
77
131
|
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
|
|
78
132
|
}
|
|
79
133
|
|
|
@@ -84,20 +138,31 @@ export async function POST(req: Request) {
|
|
|
84
138
|
{ status: 400 },
|
|
85
139
|
);
|
|
86
140
|
}
|
|
87
|
-
const { question, history
|
|
141
|
+
const { question, history } = parsed.data;
|
|
88
142
|
|
|
89
143
|
let llmConfig;
|
|
90
144
|
try {
|
|
91
145
|
llmConfig = getLLMConfig();
|
|
92
146
|
} catch (error: unknown) {
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
return NextResponse.json(
|
|
147
|
+
// Setup details (provider names, env var names) stay in the server log.
|
|
148
|
+
console.error("[doccupine] LLM configuration error:", error);
|
|
149
|
+
return NextResponse.json(
|
|
150
|
+
{
|
|
151
|
+
error:
|
|
152
|
+
"The AI assistant is not configured on this site. If you are the site owner, check the server logs.",
|
|
153
|
+
},
|
|
154
|
+
{ status: 500 },
|
|
155
|
+
);
|
|
96
156
|
}
|
|
97
157
|
|
|
98
158
|
const encoder = new TextEncoder();
|
|
99
159
|
let heartbeat: ReturnType<typeof setInterval> | null = null;
|
|
100
160
|
let streamClosed = false;
|
|
161
|
+
const workController = new AbortController();
|
|
162
|
+
const abortWork = () => workController.abort(req.signal.reason);
|
|
163
|
+
req.signal.addEventListener("abort", abortWork, { once: true });
|
|
164
|
+
if (req.signal.aborted) abortWork();
|
|
165
|
+
const { signal } = workController;
|
|
101
166
|
|
|
102
167
|
// Return the streaming response immediately and do ALL slow work (indexing,
|
|
103
168
|
// search, model streaming) inside start(). This flushes headers + a first
|
|
@@ -111,6 +176,7 @@ export async function POST(req: Request) {
|
|
|
111
176
|
} catch {
|
|
112
177
|
// Stream already closed or cancelled - stop emitting.
|
|
113
178
|
streamClosed = true;
|
|
179
|
+
workController.abort();
|
|
114
180
|
if (heartbeat) clearInterval(heartbeat);
|
|
115
181
|
}
|
|
116
182
|
};
|
|
@@ -123,10 +189,12 @@ export async function POST(req: Request) {
|
|
|
123
189
|
safeEnqueue(\`: connected\\n\\n\`);
|
|
124
190
|
|
|
125
191
|
// Ensure docs are indexed (loads precomputed embeddings when present).
|
|
126
|
-
await ensureDocsIndex(
|
|
192
|
+
await ensureDocsIndex(false, signal);
|
|
193
|
+
signal.throwIfAborted();
|
|
127
194
|
|
|
128
195
|
// Use MCP search_docs tool to find relevant documentation
|
|
129
|
-
const searchResults = await searchDocs(question, 6);
|
|
196
|
+
const searchResults = await searchDocs(question, 6, signal);
|
|
197
|
+
signal.throwIfAborted();
|
|
130
198
|
|
|
131
199
|
// Build context from search results
|
|
132
200
|
const context = searchResults
|
|
@@ -177,8 +245,9 @@ export async function POST(req: Request) {
|
|
|
177
245
|
|
|
178
246
|
// Create chat model and stream the response.
|
|
179
247
|
const llm = createChatModel(llmConfig);
|
|
180
|
-
const stream = await llm.stream(prompt);
|
|
248
|
+
const stream = await llm.stream(prompt, { signal });
|
|
181
249
|
for await (const chunk of stream) {
|
|
250
|
+
signal.throwIfAborted();
|
|
182
251
|
const content = chunk?.content || "";
|
|
183
252
|
if (content) {
|
|
184
253
|
safeEnqueue(
|
|
@@ -187,15 +256,18 @@ export async function POST(req: Request) {
|
|
|
187
256
|
}
|
|
188
257
|
}
|
|
189
258
|
|
|
259
|
+
signal.throwIfAborted();
|
|
190
260
|
safeEnqueue(\`data: \${JSON.stringify({ type: "done" })}\\n\\n\`);
|
|
191
261
|
} catch (error: unknown) {
|
|
192
|
-
|
|
262
|
+
if (signal.aborted) return;
|
|
263
|
+
console.error("[doccupine] RAG stream error:", error);
|
|
193
264
|
safeEnqueue(
|
|
194
|
-
\`data: \${JSON.stringify({ type: "error", data:
|
|
265
|
+
\`data: \${JSON.stringify({ type: "error", data: friendlyLLMError(error) })}\\n\\n\`,
|
|
195
266
|
);
|
|
196
267
|
} finally {
|
|
197
268
|
if (heartbeat) clearInterval(heartbeat);
|
|
198
269
|
streamClosed = true;
|
|
270
|
+
req.signal.removeEventListener("abort", abortWork);
|
|
199
271
|
try {
|
|
200
272
|
controller.close();
|
|
201
273
|
} catch {
|
|
@@ -205,6 +277,7 @@ export async function POST(req: Request) {
|
|
|
205
277
|
},
|
|
206
278
|
cancel() {
|
|
207
279
|
streamClosed = true;
|
|
280
|
+
workController.abort();
|
|
208
281
|
if (heartbeat) clearInterval(heartbeat);
|
|
209
282
|
},
|
|
210
283
|
});
|
|
@@ -217,7 +290,11 @@ export async function POST(req: Request) {
|
|
|
217
290
|
});
|
|
218
291
|
}
|
|
219
292
|
|
|
220
|
-
export async function GET() {
|
|
293
|
+
export async function GET(req: Request) {
|
|
294
|
+
if (!(await isRagRequestAuthorized(req))) {
|
|
295
|
+
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
296
|
+
}
|
|
297
|
+
|
|
221
298
|
const status = getIndexStatus();
|
|
222
299
|
return NextResponse.json({
|
|
223
300
|
ready: status.ready,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const searchRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { z } from \"zod\";\nimport { searchContent } from \"@/services/search\";\n\nconst searchSchema = z.object({\n q: z.string().min(1).max(200),\n limit: z.coerce.number().int().min(1).max(30).optional(),\n});\n\nexport async function GET(req: Request) {\n const url = new URL(req.url);\n const limitParam = url.searchParams.get(\"limit\");\n const parsed = searchSchema.safeParse({\n q: url.searchParams.get(\"q\"),\n ...(limitParam != null && { limit: limitParam }),\n });\n\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid query\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n\n const results = await searchContent(parsed.data.q, parsed.data.limit ?? 10);\n return NextResponse.json({ results });\n}\n";
|
|
1
|
+
export declare const searchRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { z } from \"zod\";\nimport { searchContent } from \"@/services/search\";\nimport { isSiteRequestAuthorized } from \"@/lib/access\";\n\nconst searchSchema = z.object({\n q: z.string().min(1).max(200),\n limit: z.coerce.number().int().min(1).max(30).optional(),\n});\n\nexport async function GET(req: Request) {\n if (!(await isSiteRequestAuthorized())) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const url = new URL(req.url);\n const limitParam = url.searchParams.get(\"limit\");\n const parsed = searchSchema.safeParse({\n q: url.searchParams.get(\"q\"),\n ...(limitParam != null && { limit: limitParam }),\n });\n\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid query\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n\n const results = await searchContent(parsed.data.q, parsed.data.limit ?? 10);\n return NextResponse.json({ results });\n}\n";
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export const searchRoutesTemplate = `import { NextResponse } from "next/server";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { searchContent } from "@/services/search";
|
|
4
|
+
import { isSiteRequestAuthorized } from "@/lib/access";
|
|
4
5
|
|
|
5
6
|
const searchSchema = z.object({
|
|
6
7
|
q: z.string().min(1).max(200),
|
|
@@ -8,6 +9,10 @@ const searchSchema = z.object({
|
|
|
8
9
|
});
|
|
9
10
|
|
|
10
11
|
export async function GET(req: Request) {
|
|
12
|
+
if (!(await isSiteRequestAuthorized())) {
|
|
13
|
+
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
14
|
+
}
|
|
15
|
+
|
|
11
16
|
const url = new URL(req.url);
|
|
12
17
|
const limitParam = url.searchParams.get("limit");
|
|
13
18
|
const parsed = searchSchema.safeParse({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const robotsTemplate: (
|
|
1
|
+
export declare const robotsTemplate = "import type { MetadataRoute } from \"next\";\nimport { config } from \"@/utils/config\";\n\nfunction resolveBaseUrl(): string | null {\n const raw = process.env.NEXT_PUBLIC_SITE_URL ?? config.url;\n if (!raw) return null;\n return raw.replace(/\\/$/, \"\");\n}\n\nexport default function robots(): MetadataRoute.Robots {\n // When the site is password protected, keep every crawler out entirely and\n // don't advertise the sitemap.\n if (process.env.SITE_PASSWORD) {\n return {\n rules: {\n userAgent: \"*\",\n disallow: \"/\",\n },\n };\n }\n\n const base = resolveBaseUrl();\n const rules: MetadataRoute.Robots = {\n rules: {\n userAgent: \"*\",\n allow: \"/\",\n },\n };\n if (base) {\n rules.sitemap = `${base}/sitemap.xml`;\n }\n return rules;\n}\n";
|
|
@@ -1,28 +1,4 @@
|
|
|
1
|
-
export const robotsTemplate =
|
|
2
|
-
if (!hasSiteUrl) {
|
|
3
|
-
return `import type { MetadataRoute } from "next";
|
|
4
|
-
|
|
5
|
-
export default function robots(): MetadataRoute.Robots {
|
|
6
|
-
// When the site is password protected, keep every crawler out entirely.
|
|
7
|
-
if (process.env.SITE_PASSWORD) {
|
|
8
|
-
return {
|
|
9
|
-
rules: {
|
|
10
|
-
userAgent: "*",
|
|
11
|
-
disallow: "/",
|
|
12
|
-
},
|
|
13
|
-
};
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
return {
|
|
17
|
-
rules: {
|
|
18
|
-
userAgent: "*",
|
|
19
|
-
allow: "/",
|
|
20
|
-
},
|
|
21
|
-
};
|
|
22
|
-
}
|
|
23
|
-
`;
|
|
24
|
-
}
|
|
25
|
-
return `import type { MetadataRoute } from "next";
|
|
1
|
+
export const robotsTemplate = `import type { MetadataRoute } from "next";
|
|
26
2
|
import { config } from "@/utils/config";
|
|
27
3
|
|
|
28
4
|
function resolveBaseUrl(): string | null {
|
|
@@ -56,4 +32,3 @@ export default function robots(): MetadataRoute.Robots {
|
|
|
56
32
|
return rules;
|
|
57
33
|
}
|
|
58
34
|
`;
|
|
59
|
-
};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export declare const SIDEBAR_WIDTH = 280;
|
|
2
2
|
export declare const CHAT_WIDTH = 420;
|
|
3
|
-
export declare const themeTemplate = "\"use client\";\nimport customThemeJson from \"@/theme.json\";\n\n// Users can only override the brand palette via theme.json \u2014 semantic tokens\n// (accent, surface, etc.) are derived in GlobalStyles from the brand colors\n// and are not directly overridable.\ntype CustomColors = Omit<\n Colors,\n \"accent\" | \"accentStrong\" | \"accentMuted\" | \"surface\"\n>;\n\ninterface CustomTheme {\n default?: Partial<CustomColors>;\n dark?: Partial<CustomColors>;\n}\n\nconst customTheme = customThemeJson as CustomTheme;\n\nconst breakpoints: Breakpoints = {\n xs: 0,\n sm: 576,\n md: 768,\n lg: 992,\n xl: 1200,\n xxl: 1440,\n xxxl: 1920,\n};\n\nexport function mq(minWidth: keyof Breakpoints) {\n return `@media screen and (min-width: ${breakpoints[minWidth]}px)`;\n}\n\nconst spacing: Spacing = {\n maxWidth: { xs: \"1280px\", xxxl: \"1440px\" },\n padding: { xs: \"20px\", lg: \"40px\" },\n radius: { xs: \"6px\", lg: \"12px\", xl: \"30px\" },\n gridGap: { xs: \"20px\", lg: \"40px\" },\n};\n\n// Resolved hex palettes for each mode. They feed the literal `theme` /\n// `themeDark` objects below (swapped by Cherry's ClientThemeProvider) and\n// GlobalStyles, which also emits them as CSS custom properties on :root and\n// :root.dark for plain-CSS consumers. Custom theme.json overrides are merged\n// here, so both consumers pick them up automatically.\nexport const colorsLight: CustomColors = {\n primaryLight: \"#d1d5db\",\n primary: \"#556272\",\n primaryDark: \"#374151\",\n secondaryLight: \"#c4b5fd\",\n secondary: \"#8b5cf6\",\n secondaryDark: \"#5b21b6\",\n tertiaryLight: \"#86efac\",\n tertiary: \"#22c55e\",\n tertiaryDark: \"#15803d\",\n grayLight: \"#e5e7eb\",\n gray: \"#9ca3af\",\n grayDark: \"#4b5563\",\n success: \"#84cc16\",\n error: \"#ef4444\",\n warning: \"#eab308\",\n info: \"#06b6d4\",\n dark: \"#000000\",\n light: \"#ffffff\",\n ...(customTheme.default\n ? (customTheme.default as Partial<CustomColors>)\n : {}),\n};\n\nexport const colorsDark: CustomColors = {\n primaryLight: \"#9ca3af\",\n primary: \"#6b7280\",\n primaryDark: \"#374151\",\n secondaryLight: \"#ddd6fe\",\n secondary: \"#a78bfa\",\n secondaryDark: \"#7c3aed\",\n tertiaryLight: \"#6ee7b7\",\n tertiary: \"#10b981\",\n tertiaryDark: \"#065f46\",\n grayLight: \"#1a1a1a\",\n gray: \"#454444\",\n grayDark: \"#808080\",\n success: \"#84cc16\",\n error: \"#ef4444\",\n warning: \"#eab308\",\n info: \"#06b6d4\",\n dark: \"#ffffff\",\n light: \"#000000\",\n ...(customTheme.dark ? (customTheme.dark as Partial<CustomColors>) : {}),\n};\n\nexport const shadowsLight: Shadows = {\n xs: \"0px 4px 4px 0px rgba(18, 18, 18, 0.04), 0px 1px 3px 0px rgba(39, 41, 45, 0.02)\",\n sm: \"0px 4px 4px 0px rgba(18, 18, 18, 0.08), 0px 1px 3px 0px rgba(39, 41, 45, 0.04)\",\n md: \"0px 8px 8px 0px rgba(18, 18, 18, 0.16), 0px 2px 3px 0px rgba(39, 41, 45, 0.06)\",\n lg: \"0px 16px 24px 0px rgba(18, 18, 18, 0.20), 0px 2px 3px 0px rgba(39, 41, 45, 0.08)\",\n xl: \"0px 24px 32px 0px rgba(18, 18, 18, 0.24), 0px 2px 3px 0px rgba(39, 41, 45, 0.12)\",\n};\n\nexport const shadowsDark: Shadows = {\n xs: \"0px 4px 4px 0px rgba(255, 255, 255, 0.04), 0px 1px 3px 0px rgba(255, 255, 255, 0.02)\",\n sm: \"0px 4px 4px 0px rgba(255, 255, 255, 0.08), 0px 1px 3px 0px rgba(255, 255, 255, 0.04)\",\n md: \"0px 8px 8px 0px rgba(255, 255, 255, 0.16), 0px 2px 3px 0px rgba(255, 255, 255, 0.06)\",\n lg: \"0px 16px 24px 0px rgba(255, 255, 255, 0.20), 0px 2px 3px 0px rgba(255, 255, 255, 0.08)\",\n xl: \"0px 24px 32px 0px rgba(255, 255, 255, 0.24), 0px 2px 3px 0px rgba(255, 255, 255, 0.12)\",\n};\n\nconst fonts: Fonts = {\n text: \"Inter\",\n head: \"Inter\",\n mono: \"Roboto Mono, monospace\",\n};\n\nconst fontSizes: FontSizes = {\n hero1: { xs: \"72px\", lg: \"128px\" },\n hero2: { xs: \"60px\", lg: \"96px\" },\n hero3: { xs: \"36px\", lg: \"72px\" },\n\n h1: { xs: \"40px\", lg: \"60px\" },\n h2: { xs: \"30px\", lg: \"36px\" },\n h3: { xs: \"28px\", lg: \"30px\" },\n h4: { xs: \"24px\", lg: \"26px\" },\n h5: { xs: \"18px\", lg: \"20px\" },\n h6: { xs: \"16px\", lg: \"18px\" },\n\n text: { xs: \"14px\", lg: \"16px\" },\n strong: { xs: \"14px\", lg: \"16px\" },\n small: { xs: \"12px\", lg: \"14px\" },\n\n blockquote: { xs: \"16px\", lg: \"18px\" },\n code: { xs: \"14px\", lg: \"16px\" },\n\n button: { xs: \"16px\", lg: \"16px\" },\n buttonBig: { xs: \"18px\", lg: \"18px\" },\n buttonSmall: { xs: \"14px\", lg: \"14px\" },\n\n input: { xs: \"16px\", lg: \"16px\" },\n inputBig: { xs: \"18px\", lg: \"18px\" },\n inputSmall: { xs: \"14px\", lg: \"14px\" },\n};\n\nconst lineHeights: LineHeights = {\n hero1: { xs: \"1.1\", lg: \"1.1\" },\n hero2: { xs: \"1.1\", lg: \"1.1\" },\n hero3: { xs: \"1.17\", lg: \"1.1\" },\n\n h1: { xs: \"1\", lg: \"1.07\" },\n h2: { xs: \"1.2\", lg: \"1.2\" },\n h3: { xs: \"1.3\", lg: \"1.5\" },\n h4: { xs: \"1.3\", lg: \"1.5\" },\n h5: { xs: \"1.6\", lg: \"1.5\" },\n h6: { xs: \"1.6\", lg: \"1.6\" },\n\n text: { xs: \"1.7\", lg: \"1.7\" },\n strong: { xs: \"1.7\", lg: \"1.7\" },\n small: { xs: \"1.7\", lg: \"1.7\" },\n\n blockquote: { xs: \"1.7\", lg: \"1.7\" },\n code: { xs: \"1.7\", lg: \"1.7\" },\n\n button: { xs: \"1\", lg: \"1\" },\n buttonBig: { xs: \"1\", lg: \"1\" },\n buttonSmall: { xs: \"1\", lg: \"1\" },\n\n input: { xs: \"1\", lg: \"1\" },\n inputBig: { xs: \"1\", lg: \"1\" },\n inputSmall: { xs: \"1\", lg: \"1\" },\n};\n\n// Builds the full Colors record for a mode: the resolved brand palette plus\n// the semantic tokens derived from it. Cherry's ClientThemeProvider swaps\n// whole theme objects on toggle, so components read literal values here \u2014\n// the CSS variables emitted by GlobalStyles stay in sync via the \"dark\"\n// class for plain-CSS consumers (e.g. Callout's / Code's :root.dark blocks).\n// Exported so DemoTheme can derive preset themes with the same rules.\nexport function buildColors(palette: CustomColors, isDark: boolean): Colors {\n const accent = isDark ? palette.primaryLight : palette.primaryDark;\n return {\n ...palette,\n accent,\n // accent shifted ~10% toward black (light mode) or white (dark mode).\n accentStrong: `color-mix(in srgb, ${accent} 90%, ${isDark ? \"white\" : \"black\"})`,\n accentMuted: isDark ? palette.grayDark : palette.primary,\n surface: isDark ? palette.dark : palette.light,\n };\n}\n\nexport const theme: Theme = {\n breakpoints,\n spacing,\n colors: buildColors(colorsLight, false),\n shadows: shadowsLight,\n fonts,\n fontSizes,\n lineHeights,\n isDark: false,\n};\n\nexport const themeDark: Theme = {\n breakpoints,\n spacing,\n colors: buildColors(colorsDark, true),\n shadows: shadowsDark,\n fonts,\n fontSizes,\n lineHeights,\n isDark: true,\n};\n\ninterface Breakpoints<TNumber = number> {\n xs: TNumber;\n sm: TNumber;\n md: TNumber;\n lg: TNumber;\n xl: TNumber;\n xxl: TNumber;\n xxxl: TNumber;\n}\n\ninterface Spacing<TString = string> {\n maxWidth: { xs: TString; xxxl: TString };\n padding: { xs: TString; lg: TString };\n radius: { xs: TString; lg: TString; xl: TString };\n gridGap: { xs: TString; lg: TString };\n}\n\n// Matches cherry-styled-components' Colors shape for the brand keys, plus a\n// handful of semantic tokens derived from the brand palette by buildColors.\n// The brand keys (primaryLight\u2026light) are customizable via theme.json; the\n// semantic keys (accent*, surface) are derived and not overridable \u2014 see\n// CustomColors above.\ninterface Colors<TString = string> {\n primaryLight: TString;\n primary: TString;\n primaryDark: TString;\n\n secondaryLight: TString;\n secondary: TString;\n secondaryDark: TString;\n\n tertiaryLight: TString;\n tertiary: TString;\n tertiaryDark: TString;\n\n grayLight: TString;\n gray: TString;\n grayDark: TString;\n\n success: TString;\n error: TString;\n warning: TString;\n info: TString;\n\n dark: TString;\n light: TString;\n\n /** High-contrast accent text. Was: isDark ? primaryLight : primaryDark. */\n accent: TString;\n /** Slightly stronger accent (lightened/darkened by ~10%). */\n accentStrong: TString;\n /** Muted body text. Was: isDark ? grayDark : primary. */\n accentMuted: TString;\n /** Elevated surface color, white-ish in both modes. Was: isDark ? dark : light. */\n surface: TString;\n}\n\ninterface Shadows<TString = string> {\n xs: TString;\n sm: TString;\n md: TString;\n lg: TString;\n xl: TString;\n}\n\ninterface Fonts<TString = string> {\n head: TString;\n text: TString;\n mono: TString;\n}\n\ninterface FontSizes<TString = string> {\n hero1: { xs: TString; lg: TString };\n hero2: { xs: TString; lg: TString };\n hero3: { xs: TString; lg: TString };\n\n h1: { xs: TString; lg: TString };\n h2: { xs: TString; lg: TString };\n h3: { xs: TString; lg: TString };\n h4: { xs: TString; lg: TString };\n h5: { xs: TString; lg: TString };\n h6: { xs: TString; lg: TString };\n\n text: { xs: TString; lg: TString };\n strong: { xs: TString; lg: TString };\n small: { xs: TString; lg: TString };\n\n blockquote: { xs: TString; lg: TString };\n code: { xs: TString; lg: TString };\n\n button: { xs: TString; lg: TString };\n buttonBig: { xs: TString; lg: TString };\n buttonSmall: { xs: TString; lg: TString };\n\n input: { xs: TString; lg: TString };\n inputBig: { xs: TString; lg: TString };\n inputSmall: { xs: TString; lg: TString };\n}\n\ninterface LineHeights<TString = string> {\n hero1: { xs: TString; lg: TString };\n hero2: { xs: TString; lg: TString };\n hero3: { xs: TString; lg: TString };\n\n h1: { xs: TString; lg: TString };\n h2: { xs: TString; lg: TString };\n h3: { xs: TString; lg: TString };\n h4: { xs: TString; lg: TString };\n h5: { xs: TString; lg: TString };\n h6: { xs: TString; lg: TString };\n\n text: { xs: TString; lg: TString };\n strong: { xs: TString; lg: TString };\n small: { xs: TString; lg: TString };\n\n blockquote: { xs: TString; lg: TString };\n code: { xs: TString; lg: TString };\n\n button: { xs: TString; lg: TString };\n buttonBig: { xs: TString; lg: TString };\n buttonSmall: { xs: TString; lg: TString };\n\n input: { xs: TString; lg: TString };\n inputBig: { xs: TString; lg: TString };\n inputSmall: { xs: TString; lg: TString };\n}\n\nexport interface Theme {\n breakpoints: Breakpoints;\n spacing: Spacing;\n colors: Colors;\n shadows: Shadows;\n fonts: Fonts;\n fontSizes: FontSizes;\n lineHeights: LineHeights;\n isDark: boolean;\n}\n";
|
|
3
|
+
export declare const themeTemplate = "\"use client\";\nimport customThemeJson from \"@/theme.json\";\n\n// Users can only override the brand palette via theme.json \u2014 semantic tokens\n// (accent, surface, etc.) are derived in GlobalStyles from the brand colors\n// and are not directly overridable.\ntype CustomColors = Omit<\n Colors,\n \"accent\" | \"accentStrong\" | \"accentMuted\" | \"surface\"\n>;\n\ninterface CustomTheme {\n default?: Partial<CustomColors>;\n dark?: Partial<CustomColors>;\n}\n\nconst customTheme = customThemeJson as CustomTheme;\n\nconst breakpoints: Breakpoints = {\n xs: 0,\n sm: 576,\n md: 768,\n lg: 992,\n xl: 1200,\n xxl: 1440,\n xxxl: 1920,\n};\n\nexport function mq(minWidth: keyof Breakpoints) {\n return `@media screen and (min-width: ${breakpoints[minWidth]}px)`;\n}\n\nconst spacing: Spacing = {\n maxWidth: { xs: \"1280px\", xxxl: \"1440px\" },\n padding: { xs: \"20px\", lg: \"40px\" },\n radius: { xs: \"6px\", lg: \"12px\", xl: \"30px\" },\n gridGap: { xs: \"20px\", lg: \"40px\" },\n};\n\n// Resolved hex palettes for each mode. GlobalStyles emits them as CSS custom\n// properties, one block per mode, and that is where every painted color\n// actually comes from \u2014 the theme objects below only reference those variables.\n// Custom theme.json overrides are merged here, so they flow through both.\nexport const colorsLight: CustomColors = {\n primaryLight: \"#d1d5db\",\n primary: \"#556272\",\n primaryDark: \"#374151\",\n secondaryLight: \"#c4b5fd\",\n secondary: \"#8b5cf6\",\n secondaryDark: \"#5b21b6\",\n tertiaryLight: \"#86efac\",\n tertiary: \"#22c55e\",\n tertiaryDark: \"#15803d\",\n grayLight: \"#e5e7eb\",\n gray: \"#9ca3af\",\n grayDark: \"#4b5563\",\n success: \"#84cc16\",\n error: \"#ef4444\",\n warning: \"#eab308\",\n info: \"#06b6d4\",\n dark: \"#000000\",\n light: \"#ffffff\",\n ...(customTheme.default\n ? (customTheme.default as Partial<CustomColors>)\n : {}),\n};\n\nexport const colorsDark: CustomColors = {\n primaryLight: \"#9ca3af\",\n primary: \"#6b7280\",\n primaryDark: \"#374151\",\n secondaryLight: \"#ddd6fe\",\n secondary: \"#a78bfa\",\n secondaryDark: \"#7c3aed\",\n tertiaryLight: \"#6ee7b7\",\n tertiary: \"#10b981\",\n tertiaryDark: \"#065f46\",\n grayLight: \"#1a1a1a\",\n gray: \"#454444\",\n grayDark: \"#808080\",\n success: \"#84cc16\",\n error: \"#ef4444\",\n warning: \"#eab308\",\n info: \"#06b6d4\",\n dark: \"#ffffff\",\n light: \"#000000\",\n ...(customTheme.dark ? (customTheme.dark as Partial<CustomColors>) : {}),\n};\n\nexport const shadowsLight: Shadows = {\n xs: \"0px 4px 4px 0px rgba(18, 18, 18, 0.04), 0px 1px 3px 0px rgba(39, 41, 45, 0.02)\",\n sm: \"0px 4px 4px 0px rgba(18, 18, 18, 0.08), 0px 1px 3px 0px rgba(39, 41, 45, 0.04)\",\n md: \"0px 8px 8px 0px rgba(18, 18, 18, 0.16), 0px 2px 3px 0px rgba(39, 41, 45, 0.06)\",\n lg: \"0px 16px 24px 0px rgba(18, 18, 18, 0.20), 0px 2px 3px 0px rgba(39, 41, 45, 0.08)\",\n xl: \"0px 24px 32px 0px rgba(18, 18, 18, 0.24), 0px 2px 3px 0px rgba(39, 41, 45, 0.12)\",\n};\n\nexport const shadowsDark: Shadows = {\n xs: \"0px 4px 4px 0px rgba(255, 255, 255, 0.04), 0px 1px 3px 0px rgba(255, 255, 255, 0.02)\",\n sm: \"0px 4px 4px 0px rgba(255, 255, 255, 0.08), 0px 1px 3px 0px rgba(255, 255, 255, 0.04)\",\n md: \"0px 8px 8px 0px rgba(255, 255, 255, 0.16), 0px 2px 3px 0px rgba(255, 255, 255, 0.06)\",\n lg: \"0px 16px 24px 0px rgba(255, 255, 255, 0.20), 0px 2px 3px 0px rgba(255, 255, 255, 0.08)\",\n xl: \"0px 24px 32px 0px rgba(255, 255, 255, 0.24), 0px 2px 3px 0px rgba(255, 255, 255, 0.12)\",\n};\n\nconst fonts: Fonts = {\n text: \"Inter\",\n head: \"Inter\",\n mono: \"Roboto Mono, monospace\",\n};\n\nconst fontSizes: FontSizes = {\n hero1: { xs: \"72px\", lg: \"128px\" },\n hero2: { xs: \"60px\", lg: \"96px\" },\n hero3: { xs: \"36px\", lg: \"72px\" },\n\n h1: { xs: \"40px\", lg: \"60px\" },\n h2: { xs: \"30px\", lg: \"36px\" },\n h3: { xs: \"28px\", lg: \"30px\" },\n h4: { xs: \"24px\", lg: \"26px\" },\n h5: { xs: \"18px\", lg: \"20px\" },\n h6: { xs: \"16px\", lg: \"18px\" },\n\n text: { xs: \"14px\", lg: \"16px\" },\n strong: { xs: \"14px\", lg: \"16px\" },\n small: { xs: \"12px\", lg: \"14px\" },\n\n blockquote: { xs: \"16px\", lg: \"18px\" },\n code: { xs: \"14px\", lg: \"16px\" },\n\n button: { xs: \"16px\", lg: \"16px\" },\n buttonBig: { xs: \"18px\", lg: \"18px\" },\n buttonSmall: { xs: \"14px\", lg: \"14px\" },\n\n input: { xs: \"16px\", lg: \"16px\" },\n inputBig: { xs: \"18px\", lg: \"18px\" },\n inputSmall: { xs: \"14px\", lg: \"14px\" },\n};\n\nconst lineHeights: LineHeights = {\n hero1: { xs: \"1.1\", lg: \"1.1\" },\n hero2: { xs: \"1.1\", lg: \"1.1\" },\n hero3: { xs: \"1.17\", lg: \"1.1\" },\n\n h1: { xs: \"1\", lg: \"1.07\" },\n h2: { xs: \"1.2\", lg: \"1.2\" },\n h3: { xs: \"1.3\", lg: \"1.5\" },\n h4: { xs: \"1.3\", lg: \"1.5\" },\n h5: { xs: \"1.6\", lg: \"1.5\" },\n h6: { xs: \"1.6\", lg: \"1.6\" },\n\n text: { xs: \"1.7\", lg: \"1.7\" },\n strong: { xs: \"1.7\", lg: \"1.7\" },\n small: { xs: \"1.7\", lg: \"1.7\" },\n\n blockquote: { xs: \"1.7\", lg: \"1.7\" },\n code: { xs: \"1.7\", lg: \"1.7\" },\n\n button: { xs: \"1\", lg: \"1\" },\n buttonBig: { xs: \"1\", lg: \"1\" },\n buttonSmall: { xs: \"1\", lg: \"1\" },\n\n input: { xs: \"1\", lg: \"1\" },\n inputBig: { xs: \"1\", lg: \"1\" },\n inputSmall: { xs: \"1\", lg: \"1\" },\n};\n\n// Builds the full Colors record for a mode: the resolved brand palette plus\n// the semantic tokens derived from it. Used here only as the key template for\n// the CSS-variable theme below; the resolved values themselves are emitted as\n// custom properties by GlobalStyles.\nexport function buildColors(palette: CustomColors, isDark: boolean): Colors {\n const accent = isDark ? palette.primaryLight : palette.primaryDark;\n return {\n ...palette,\n accent,\n // accent shifted ~10% toward black (light mode) or white (dark mode).\n accentStrong: `color-mix(in srgb, ${accent} 90%, ${isDark ? \"white\" : \"black\"})`,\n accentMuted: isDark ? palette.grayDark : palette.primary,\n surface: isDark ? palette.dark : palette.light,\n };\n}\n\n// Maps every key of a token record to the CSS custom property that holds its\n// value, keeping the record's exact shape. Passing the resolved light objects\n// as templates means a new token can never be forgotten here.\nfunction cssVarTokens<T extends object>(prefix: string, template: T): T {\n return Object.fromEntries(\n Object.keys(template).map((key) => [key, `var(--${prefix}-${key})`]),\n ) as T;\n}\n\n// Every painted color and shadow resolves through a CSS custom property rather\n// than a literal, so the CSS styled-components generates is identical in light\n// and dark mode. That is what makes a statically rendered page paint the right\n// theme on its first frame: the data-theme attribute the blocking script in the\n// root layout stamps on <html> before paint selects the variable block, and\n// nothing has to wait for hydration to swap a theme object. `theme` and\n// `themeDark` therefore differ only in `isDark`, which Cherry's\n// ClientThemeProvider reads to persist the choice, and which\n// ThemeModeAttribute mirrors back onto the attribute.\nconst colors = cssVarTokens(\"color\", buildColors(colorsLight, false));\nconst shadows = cssVarTokens(\"shadow\", shadowsLight);\n\nexport const theme: Theme = {\n breakpoints,\n spacing,\n colors,\n shadows,\n fonts,\n fontSizes,\n lineHeights,\n isDark: false,\n};\n\nexport const themeDark: Theme = {\n ...theme,\n isDark: true,\n};\n\ninterface Breakpoints<TNumber = number> {\n xs: TNumber;\n sm: TNumber;\n md: TNumber;\n lg: TNumber;\n xl: TNumber;\n xxl: TNumber;\n xxxl: TNumber;\n}\n\ninterface Spacing<TString = string> {\n maxWidth: { xs: TString; xxxl: TString };\n padding: { xs: TString; lg: TString };\n radius: { xs: TString; lg: TString; xl: TString };\n gridGap: { xs: TString; lg: TString };\n}\n\n// Matches cherry-styled-components' Colors shape for the brand keys, plus a\n// handful of semantic tokens derived from the brand palette by buildColors.\n// The brand keys (primaryLight\u2026light) are customizable via theme.json; the\n// semantic keys (accent*, surface) are derived and not overridable \u2014 see\n// CustomColors above.\ninterface Colors<TString = string> {\n primaryLight: TString;\n primary: TString;\n primaryDark: TString;\n\n secondaryLight: TString;\n secondary: TString;\n secondaryDark: TString;\n\n tertiaryLight: TString;\n tertiary: TString;\n tertiaryDark: TString;\n\n grayLight: TString;\n gray: TString;\n grayDark: TString;\n\n success: TString;\n error: TString;\n warning: TString;\n info: TString;\n\n dark: TString;\n light: TString;\n\n /** High-contrast accent text. Was: isDark ? primaryLight : primaryDark. */\n accent: TString;\n /** Slightly stronger accent (lightened/darkened by ~10%). */\n accentStrong: TString;\n /** Muted body text. Was: isDark ? grayDark : primary. */\n accentMuted: TString;\n /** Elevated surface color, white-ish in both modes. Was: isDark ? dark : light. */\n surface: TString;\n}\n\ninterface Shadows<TString = string> {\n xs: TString;\n sm: TString;\n md: TString;\n lg: TString;\n xl: TString;\n}\n\ninterface Fonts<TString = string> {\n head: TString;\n text: TString;\n mono: TString;\n}\n\ninterface FontSizes<TString = string> {\n hero1: { xs: TString; lg: TString };\n hero2: { xs: TString; lg: TString };\n hero3: { xs: TString; lg: TString };\n\n h1: { xs: TString; lg: TString };\n h2: { xs: TString; lg: TString };\n h3: { xs: TString; lg: TString };\n h4: { xs: TString; lg: TString };\n h5: { xs: TString; lg: TString };\n h6: { xs: TString; lg: TString };\n\n text: { xs: TString; lg: TString };\n strong: { xs: TString; lg: TString };\n small: { xs: TString; lg: TString };\n\n blockquote: { xs: TString; lg: TString };\n code: { xs: TString; lg: TString };\n\n button: { xs: TString; lg: TString };\n buttonBig: { xs: TString; lg: TString };\n buttonSmall: { xs: TString; lg: TString };\n\n input: { xs: TString; lg: TString };\n inputBig: { xs: TString; lg: TString };\n inputSmall: { xs: TString; lg: TString };\n}\n\ninterface LineHeights<TString = string> {\n hero1: { xs: TString; lg: TString };\n hero2: { xs: TString; lg: TString };\n hero3: { xs: TString; lg: TString };\n\n h1: { xs: TString; lg: TString };\n h2: { xs: TString; lg: TString };\n h3: { xs: TString; lg: TString };\n h4: { xs: TString; lg: TString };\n h5: { xs: TString; lg: TString };\n h6: { xs: TString; lg: TString };\n\n text: { xs: TString; lg: TString };\n strong: { xs: TString; lg: TString };\n small: { xs: TString; lg: TString };\n\n blockquote: { xs: TString; lg: TString };\n code: { xs: TString; lg: TString };\n\n button: { xs: TString; lg: TString };\n buttonBig: { xs: TString; lg: TString };\n buttonSmall: { xs: TString; lg: TString };\n\n input: { xs: TString; lg: TString };\n inputBig: { xs: TString; lg: TString };\n inputSmall: { xs: TString; lg: TString };\n}\n\nexport interface Theme {\n breakpoints: Breakpoints;\n spacing: Spacing;\n colors: Colors;\n shadows: Shadows;\n fonts: Fonts;\n fontSizes: FontSizes;\n lineHeights: LineHeights;\n isDark: boolean;\n}\n";
|
|
@@ -39,11 +39,10 @@ const spacing: Spacing = {
|
|
|
39
39
|
gridGap: { xs: "20px", lg: "40px" },
|
|
40
40
|
};
|
|
41
41
|
|
|
42
|
-
// Resolved hex palettes for each mode.
|
|
43
|
-
//
|
|
44
|
-
//
|
|
45
|
-
//
|
|
46
|
-
// here, so both consumers pick them up automatically.
|
|
42
|
+
// Resolved hex palettes for each mode. GlobalStyles emits them as CSS custom
|
|
43
|
+
// properties, one block per mode, and that is where every painted color
|
|
44
|
+
// actually comes from — the theme objects below only reference those variables.
|
|
45
|
+
// Custom theme.json overrides are merged here, so they flow through both.
|
|
47
46
|
export const colorsLight: CustomColors = {
|
|
48
47
|
primaryLight: "#d1d5db",
|
|
49
48
|
primary: "#556272",
|
|
@@ -169,11 +168,9 @@ const lineHeights: LineHeights = {
|
|
|
169
168
|
};
|
|
170
169
|
|
|
171
170
|
// Builds the full Colors record for a mode: the resolved brand palette plus
|
|
172
|
-
// the semantic tokens derived from it.
|
|
173
|
-
//
|
|
174
|
-
//
|
|
175
|
-
// class for plain-CSS consumers (e.g. Callout's / Code's :root.dark blocks).
|
|
176
|
-
// Exported so DemoTheme can derive preset themes with the same rules.
|
|
171
|
+
// the semantic tokens derived from it. Used here only as the key template for
|
|
172
|
+
// the CSS-variable theme below; the resolved values themselves are emitted as
|
|
173
|
+
// custom properties by GlobalStyles.
|
|
177
174
|
export function buildColors(palette: CustomColors, isDark: boolean): Colors {
|
|
178
175
|
const accent = isDark ? palette.primaryLight : palette.primaryDark;
|
|
179
176
|
return {
|
|
@@ -186,11 +183,32 @@ export function buildColors(palette: CustomColors, isDark: boolean): Colors {
|
|
|
186
183
|
};
|
|
187
184
|
}
|
|
188
185
|
|
|
186
|
+
// Maps every key of a token record to the CSS custom property that holds its
|
|
187
|
+
// value, keeping the record's exact shape. Passing the resolved light objects
|
|
188
|
+
// as templates means a new token can never be forgotten here.
|
|
189
|
+
function cssVarTokens<T extends object>(prefix: string, template: T): T {
|
|
190
|
+
return Object.fromEntries(
|
|
191
|
+
Object.keys(template).map((key) => [key, \`var(--\${prefix}-\${key})\`]),
|
|
192
|
+
) as T;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Every painted color and shadow resolves through a CSS custom property rather
|
|
196
|
+
// than a literal, so the CSS styled-components generates is identical in light
|
|
197
|
+
// and dark mode. That is what makes a statically rendered page paint the right
|
|
198
|
+
// theme on its first frame: the data-theme attribute the blocking script in the
|
|
199
|
+
// root layout stamps on <html> before paint selects the variable block, and
|
|
200
|
+
// nothing has to wait for hydration to swap a theme object. \`theme\` and
|
|
201
|
+
// \`themeDark\` therefore differ only in \`isDark\`, which Cherry's
|
|
202
|
+
// ClientThemeProvider reads to persist the choice, and which
|
|
203
|
+
// ThemeModeAttribute mirrors back onto the attribute.
|
|
204
|
+
const colors = cssVarTokens("color", buildColors(colorsLight, false));
|
|
205
|
+
const shadows = cssVarTokens("shadow", shadowsLight);
|
|
206
|
+
|
|
189
207
|
export const theme: Theme = {
|
|
190
208
|
breakpoints,
|
|
191
209
|
spacing,
|
|
192
|
-
colors
|
|
193
|
-
shadows
|
|
210
|
+
colors,
|
|
211
|
+
shadows,
|
|
194
212
|
fonts,
|
|
195
213
|
fontSizes,
|
|
196
214
|
lineHeights,
|
|
@@ -198,13 +216,7 @@ export const theme: Theme = {
|
|
|
198
216
|
};
|
|
199
217
|
|
|
200
218
|
export const themeDark: Theme = {
|
|
201
|
-
|
|
202
|
-
spacing,
|
|
203
|
-
colors: buildColors(colorsDark, true),
|
|
204
|
-
shadows: shadowsDark,
|
|
205
|
-
fonts,
|
|
206
|
-
fontSizes,
|
|
207
|
-
lineHeights,
|
|
219
|
+
...theme,
|
|
208
220
|
isDark: true,
|
|
209
221
|
};
|
|
210
222
|
|