From 6e2b1b95652083cc1593745c524e1c9df99a0869 Mon Sep 17 00:00:00 2001 From: Suraj Air Date: Tue, 17 Nov 2026 16:49:38 +0530 Subject: [PATCH 1/4] chore(sync): pro@aade91a Sync src/ from chaibuilder/pro (chore/align-core-rename) into chaibuilder/core. Source commits since last sync (.sync-ref was pro@55058eb): 895d7c58f fix(server): let actions win over builderActions and export plugin helpers 6bd4cc009 feat(tailwind)!: remove remaining Tailwind v3 support Files: 23 updated, 0 added, 2 deleted, 1 root file(s) copied ~ src/builder/core/components/canvas/IframeInitialContent.test.ts ~ src/builder/core/components/canvas/IframeInitialContent.ts ~ src/builder/core/components/canvas/static/chai-theme-helpers.ts ~ src/builder/core/components/canvas/static/head-tags.tsx ~ src/builder/core/components/canvas/static/static-canvas.tsx ~ src/builder/core/components/canvas/tailwind-preview-iframe.tsx ~ src/builder/core/components/canvas/tailwind-v4-canvas.test.ts ~ src/builder/core/utils/color-formatter.ts ~ src/builder/pages/chaibuilder-pages.tsx ~ src/nextjs/server.ts ~ src/render/get-tailwind-css.ts ~ src/server/chai-actions/actions-registery.ts ~ src/server/chai-builder/public/get-blocks-styles.test.ts ~ src/server/chai-builder/public/get-blocks-styles.ts ~ src/server/chai-builder/public/get-page-styles.test.ts ~ src/server/chai-builder/public/get-page-styles.ts ~ src/server/defaults/index.ts ~ src/server/defaults/resolve-config.test.ts ~ src/types/chaibuilder-editor-props.ts ~ src/types/common.ts ~ src/types/plugin.ts ~ src/utils/index.ts ~ src/utils/tailwind-css-compat.ts - src/utils/get-chai-builder-tailwind-config.ts - src/utils/tailwind-v3-compat.ts ~ .prettierignore Sync-Direction: pro->core Sync-Source: chaibuilder/pro@aade91a3dd05e38a9b3b269a0a17c1f603d0a9df Sync-Previous: chaibuilder/pro@55058ebe503eb924ba1b9a9829f0a15989989ede Sync-Manifest: sha256:16ece088df7b365f315d2f30dd07ebe8f7cca12ffc0e35448ddfe182e22a02a7 --- .prettierignore | 4 +- .sync-ref | 2 +- .../canvas/IframeInitialContent.test.ts | 57 +++------ .../components/canvas/IframeInitialContent.ts | 56 ++------- .../canvas/static/chai-theme-helpers.ts | 26 +---- .../components/canvas/static/head-tags.tsx | 62 +--------- .../canvas/static/static-canvas.tsx | 8 +- .../canvas/tailwind-preview-iframe.tsx | 61 ++-------- .../canvas/tailwind-v4-canvas.test.ts | 53 ++------- src/builder/core/utils/color-formatter.ts | 12 +- src/builder/pages/chaibuilder-pages.tsx | 10 +- src/nextjs/server.ts | 2 + src/render/get-tailwind-css.ts | 3 +- src/server/chai-actions/actions-registery.ts | 5 +- .../public/get-blocks-styles.test.ts | 56 ++++----- .../chai-builder/public/get-blocks-styles.ts | 3 +- .../public/get-page-styles.test.ts | 2 +- .../chai-builder/public/get-page-styles.ts | 8 +- src/server/defaults/index.ts | 4 +- src/server/defaults/resolve-config.test.ts | 15 +++ src/types/chaibuilder-editor-props.ts | 6 - src/types/common.ts | 1 - src/types/plugin.ts | 6 +- src/utils/get-chai-builder-tailwind-config.ts | 109 ------------------ src/utils/index.ts | 1 - src/utils/tailwind-css-compat.ts | 5 +- src/utils/tailwind-v3-compat.ts | 12 -- 27 files changed, 123 insertions(+), 466 deletions(-) delete mode 100644 src/utils/get-chai-builder-tailwind-config.ts delete mode 100644 src/utils/tailwind-v3-compat.ts diff --git a/.prettierignore b/.prettierignore index 06d04f6a8..16f2e8ff8 100644 --- a/.prettierignore +++ b/.prettierignore @@ -4,4 +4,6 @@ dist build coverage package-lock.json -yarn.lock \ No newline at end of file +yarn.lock +# Generated by scripts/api-report.mjs +api-report diff --git a/.sync-ref b/.sync-ref index d7530ca73..63f23a288 100644 --- a/.sync-ref +++ b/.sync-ref @@ -1 +1 @@ -chaibuilder/pro@55058ebe503eb924ba1b9a9829f0a15989989ede +chaibuilder/pro@aade91a3dd05e38a9b3b269a0a17c1f603d0a9df diff --git a/src/builder/core/components/canvas/IframeInitialContent.test.ts b/src/builder/core/components/canvas/IframeInitialContent.test.ts index c07ef179a..e33db2d23 100644 --- a/src/builder/core/components/canvas/IframeInitialContent.test.ts +++ b/src/builder/core/components/canvas/IframeInitialContent.test.ts @@ -1,47 +1,27 @@ import { describe, expect, it } from "vitest"; -import { getIframeInitialContent, TAILWIND_CDN_URLS, TAILWIND_THEME_STYLE_ID } from "./IframeInitialContent"; +import { getIframeInitialContent, TAILWIND_CDN_URL, TAILWIND_THEME_STYLE_ID } from "./IframeInitialContent"; describe("getIframeInitialContent", () => { - it("defaults to Tailwind v4 CDN", () => { + it("loads the Tailwind v4 browser build", () => { const html = getIframeInitialContent(); - expect(html).toContain(TAILWIND_CDN_URLS["4"]); - expect(html).toContain(`src="${TAILWIND_CDN_URLS["4"]}"`); + expect(TAILWIND_CDN_URL).toContain("@tailwindcss/browser@4"); + expect(html).toContain(`src="${TAILWIND_CDN_URL}"`); + expect(html).not.toContain("cdn.tailwindcss.com"); expect(html).not.toContain("__TAILWIND_CDN__"); expect(html).not.toContain("__HTML_DIR__"); }); - it("uses the v3 CDN when tailwindCSS is 3", () => { - const html = getIframeInitialContent({ tailwindCSS: "3" }); - - expect(html).toContain(TAILWIND_CDN_URLS["3"]); - expect(html).toContain("cdn.tailwindcss.com"); - expect(html).not.toContain(TAILWIND_CDN_URLS["4"]); - }); - it("sets html dir for rtl layouts", () => { - const html = getIframeInitialContent({ htmlDir: "rtl", tailwindCSS: "4" }); + const html = getIframeInitialContent({ htmlDir: "rtl" }); expect(html).toContain('dir="rtl"'); - expect(html).toContain(TAILWIND_CDN_URLS["4"]); - }); - - it("exposes distinct CDN URLs for v3 and v4", () => { - expect(TAILWIND_CDN_URLS["3"]).toContain("cdn.tailwindcss.com"); - expect(TAILWIND_CDN_URLS["4"]).toContain("@tailwindcss/browser"); - expect(TAILWIND_CDN_URLS["3"]).not.toBe(TAILWIND_CDN_URLS["4"]); - }); - - it("keeps the config-driven @apply base rule on v3", () => { - const html = getIframeInitialContent({ tailwindCSS: "3" }); - - expect(html).toContain("@apply border-border;"); - expect(html).not.toContain("__TAILWIND_STYLE__"); + expect(html).toContain(TAILWIND_CDN_URL); }); // The v4 browser build drops the whole sheet when one utility is unknown. - it("compiles standalone on v4 without theme-dependent utilities in base", () => { - const html = getIframeInitialContent({ tailwindCSS: "4" }); + it("compiles standalone without theme-dependent utilities in base", () => { + const html = getIframeInitialContent(); expect(html).toContain("@custom-variant dark (&:where(.dark, .dark *));"); expect(html).toContain("border-color: var(--color-border, currentColor);"); @@ -51,23 +31,20 @@ describe("getIframeInitialContent", () => { // Spelling out the import makes the browser resolve "tailwindcss" as a relative URL and 404; // the build injects it for us when the concatenated CSS has no @import of its own. - it("leaves the tailwindcss import to the v4 browser build", () => { - expect(getIframeInitialContent({ tailwindCSS: "4" })).not.toContain("@import"); + it("leaves the tailwindcss import to the browser build", () => { + expect(getIframeInitialContent()).not.toContain("@import"); }); - it("ships an empty theme placeholder on v4 for TailwindV4Theme to fill", () => { - const html = getIframeInitialContent({ tailwindCSS: "4" }); + it("ships an empty theme placeholder for TailwindV4Theme to fill", () => { + const html = getIframeInitialContent(); expect(html).toContain(``); - expect(getIframeInitialContent({ tailwindCSS: "3" })).not.toContain(TAILWIND_THEME_STYLE_ID); }); - it("ships the rte utilities on both versions", () => { - for (const tailwindCSS of ["3", "4"] as const) { - const html = getIframeInitialContent({ tailwindCSS }); + it("ships the rte utilities", () => { + const html = getIframeInitialContent(); - expect(html).toContain('`; - // The v4 browser build concatenates every `style[type="text/tailwindcss"]` into a single // compile. One unknown utility fails the whole sheet, so base styles here stay on plain CSS // vars; theme-dependent utilities come from the `@theme` block written into the placeholder // below. The typography and forms plugins the page CSS compiles with arrive pre-rewritten as // `@utility` / `@custom-variant` rules (the browser build cannot load npm plugins). No `@import "tailwindcss"` here on purpose: the build prepends it when no @import is // present, and spelling it out makes the browser fetch the bare specifier as a relative URL. -const TAILWIND_V4_STYLE = ``; -export const TAILWIND_CDN_URLS: Record = { - "3": "https://cdn.tailwindcss.com/3.4.17?plugins=forms@0.5.9,typography@0.5.15,aspect-ratio@0.4.2", - "4": "https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4", -}; - -const TAILWIND_STYLES: Record = { - "3": TAILWIND_V3_STYLE, - "4": TAILWIND_V4_STYLE, -}; +export const TAILWIND_CDN_URL = "https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"; -export const getIframeInitialContent = ({ - htmlDir = "ltr", - tailwindCSS = "4", -}: { - htmlDir?: "ltr" | "rtl" | string; - tailwindCSS?: TailwindCSSVersion; -} = {}): string => +export const getIframeInitialContent = ({ htmlDir = "ltr" }: { htmlDir?: "ltr" | "rtl" | string } = {}): string => IframeInitialContent.replace("__HTML_DIR__", htmlDir) - .replace("__TAILWIND_CDN__", TAILWIND_CDN_URLS[tailwindCSS]) - .replace("__TAILWIND_STYLE__", TAILWIND_STYLES[tailwindCSS]); + .replace("__TAILWIND_CDN__", TAILWIND_CDN_URL) + .replace("__TAILWIND_STYLE__", TAILWIND_STYLE); diff --git a/src/builder/core/components/canvas/static/chai-theme-helpers.ts b/src/builder/core/components/canvas/static/chai-theme-helpers.ts index e6281357c..53df7c2fd 100644 --- a/src/builder/core/components/canvas/static/chai-theme-helpers.ts +++ b/src/builder/core/components/canvas/static/chai-theme-helpers.ts @@ -2,20 +2,6 @@ import { flatten, get, keys, uniq, uniqBy } from "lodash-es"; import { resolveFont } from "~/registry/fonts"; import type { ChaiFontBySrc, ChaiFontByUrl } from "~/types"; import type { ChaiTheme, ChaiThemeOptions } from "~/types/chaibuilder-editor-props"; -import { V3_COMPAT_CSS } from "~/utils/tailwind-v3-compat"; - -/** - * Tailwind v3 values for the utilities v4 rescaled, so content authored under v3 renders - * unchanged: `shadow-sm`, `drop-shadow-sm`, `blur-sm`/`backdrop-blur-sm` and a bare `ring`'s - * width. Applied to both the page CSS (JS theme below) and the canvas (`@theme` in - * getChaiThemeCssTheme). The rest of the v3 deltas need CSS: see V3_COMPAT_CSS. - */ -export const V3_SCALE = { - shadowSm: "0 1px 2px 0 rgb(0 0 0 / 0.05)", - dropShadowSm: "0 1px 1px rgb(0 0 0 / 0.05)", - blurSm: "4px", - ringWidth: "3px", -}; export const getChaiThemeOptions = (chaiThemeOptions: ChaiThemeOptions) => { const theme = { @@ -41,11 +27,6 @@ export const getChaiThemeOptions = (chaiThemeOptions: ChaiThemeOptions) => { {}, ) : {}, - boxShadow: { sm: V3_SCALE.shadowSm }, - dropShadow: { sm: V3_SCALE.dropShadowSm }, - blur: { sm: V3_SCALE.blurSm }, - backdropBlur: { sm: V3_SCALE.blurSm }, - ringWidth: { DEFAULT: V3_SCALE.ringWidth }, }; return theme; }; @@ -74,10 +55,6 @@ export const getChaiThemeCssTheme = (chaiThemeOptions: ChaiThemeOptions): string ] : []), ...colorKeys.map((key) => `--color-${key}: hsl(var(--${key}));`), - `--shadow-sm: ${V3_SCALE.shadowSm};`, - `--drop-shadow-sm: ${V3_SCALE.dropShadowSm};`, - `--blur-sm: ${V3_SCALE.blurSm};`, - `--default-ring-width: ${V3_SCALE.ringWidth};`, ]; return `:root { @@ -106,8 +83,7 @@ export const getChaiThemeCssTheme = (chaiThemeOptions: ChaiThemeOptions): string color: hsl(var(--foreground)); background-color: hsl(var(--background)); } - } - ${V3_COMPAT_CSS}`; + }`; }; export function hexToHSL(hex: string) { diff --git a/src/builder/core/components/canvas/static/head-tags.tsx b/src/builder/core/components/canvas/static/head-tags.tsx index 542992a04..5c3a5e211 100644 --- a/src/builder/core/components/canvas/static/head-tags.tsx +++ b/src/builder/core/components/canvas/static/head-tags.tsx @@ -1,19 +1,11 @@ -import containerQueries from "@tailwindcss/container-queries"; -import forms from "@tailwindcss/forms"; -import typography from "@tailwindcss/typography"; import { compact, filter, get, has, map, uniq } from "lodash-es"; import { memo, useEffect, useMemo } from "react"; -import plugin from "tailwindcss/plugin"; import { getChaiThemeCssTheme, - getChaiThemeOptions, getThemeCustomFontFace, getThemeFontsUrls, } from "~/builder/core/components/canvas/static/chai-theme-helpers"; -import { - TAILWIND_THEME_STYLE_ID, - V3_SCREEN_HEIGHT_THEME, -} from "~/builder/core/components/canvas/IframeInitialContent"; +import { TAILWIND_THEME_STYLE_ID } from "~/builder/core/components/canvas/IframeInitialContent"; import { CssThemeVariables } from "~/builder/core/components/css-theme-var"; import { useFrame } from "~/builder/core/frame"; import { useBuilderProp } from "~/builder/hooks/use-builder-prop"; @@ -33,48 +25,6 @@ const useDarkModeEffect = (darkMode: boolean, iframeDoc: Document | undefined) = }, [darkMode, iframeDoc]); }; -const useTailwindConfig = (chaiTheme: any, chaiThemeOptions: any, iframeWin: Window | undefined, enabled: boolean) => { - useEffect(() => { - const win = iframeWin as any; - if (!enabled || !win || !win.tailwind) return; - const newConfig = { - darkMode: "class", - theme: { - extend: { - container: { - center: true, - padding: "1rem", - screens: { - "2xl": "1400px", - }, - }, - ...V3_SCREEN_HEIGHT_THEME, - ...getChaiThemeOptions(chaiThemeOptions), - }, - }, - - plugins: [ - typography, - forms, - containerQueries, - plugin(function ({ addBase, theme }: any) { - addBase({ - "h1,h2,h3,h4,h5,h6": { - fontFamily: theme("fontFamily.heading"), - }, - body: { - fontFamily: theme("fontFamily.body"), - color: theme("colors.foreground"), - backgroundColor: theme("colors.background"), - }, - }); - }), - ], - }; - Object.assign(win.tailwind.config, newConfig); - }, [chaiTheme, chaiThemeOptions, iframeWin, enabled]); -}; - /** * Writes the theme into the placeholder that ships with the iframe content rather than rendering * a style element. The v4 browser build only re-reads stylesheets on a "full" rebuild, and it @@ -131,7 +81,9 @@ const useThemeFonts = () => { heading: get(chaiTheme, "fontFamily.heading"), body: get(chaiTheme, "fontFamily.body"), }; - return uniq(compact([heading, body])).map(resolveFont).filter(Boolean) as ChaiFont[]; + return uniq(compact([heading, body])) + .map(resolveFont) + .filter(Boolean) as ChaiFont[]; }, [chaiTheme]); const fonts = useMemo( @@ -182,18 +134,16 @@ export const HeadTags = () => { const [chaiTheme] = useTheme(); const chaiThemeOptions = useThemeOptions(); const [darkMode] = useDarkMode(); - const { document: iframeDoc, window: iframeWin } = useFrame(); - const tailwindCSS = useBuilderProp<"3" | "4">("tailwindCSS", "4"); + const { document: iframeDoc } = useFrame(); const canvasStyles = useBuilderProp("canvasStyles", ""); const layoutCss = useMemo(() => getSiteContentWidthCss(chaiTheme), [chaiTheme]); useDarkModeEffect(darkMode, iframeDoc); - useTailwindConfig(chaiTheme, chaiThemeOptions, iframeWin, tailwindCSS === "3"); return ( <> - {tailwindCSS === "4" ? : null} + {/* Text child (not innerHTML): the canvas is client-rendered so this lands as textContent — no `` breakout if a host ever passes untrusted CSS, and selectors like `a > b` are intact. */} diff --git a/src/builder/core/components/canvas/static/static-canvas.tsx b/src/builder/core/components/canvas/static/static-canvas.tsx index 7b19ead07..032f71384 100644 --- a/src/builder/core/components/canvas/static/static-canvas.tsx +++ b/src/builder/core/components/canvas/static/static-canvas.tsx @@ -34,7 +34,6 @@ const StaticCanvas = () => { const [, setCanvasIframe] = useCanvasIframe(); const loadingCanvas = useBuilderProp("loading", false); const htmlDir = useBuilderProp("htmlDir", "ltr"); - const tailwindCSS = useBuilderProp<"3" | "4">("tailwindCSS", "4"); const { onDragOver, onDrop, onDragEnd } = useDragAndDrop(); const dropIndicator = useDropIndicator(); @@ -51,10 +50,7 @@ const StaticCanvas = () => { setDimension({ width: clientWidth, height: clientHeight }); }, [wrapperRef, width]); - const iframeContent: string = useMemo( - () => getIframeInitialContent({ htmlDir, tailwindCSS }), - [htmlDir, tailwindCSS], - ); + const iframeContent: string = useMemo(() => getIframeInitialContent({ htmlDir }), [htmlDir]); return ( @@ -115,7 +111,7 @@ const StaticCanvas = () => { id="placeholder" className={`pointer-events-none absolute z-[99999] max-w-full ${ dropIndicator.isEmpty - ? "bg-purple-500/10 outline-dashed outline-2 -outline-offset-4 outline-purple-500" + ? "bg-purple-500/10 outline-2 -outline-offset-4 outline-purple-500 outline-dashed" : "rounded-full bg-green-500" }`} style={{ diff --git a/src/builder/core/components/canvas/tailwind-preview-iframe.tsx b/src/builder/core/components/canvas/tailwind-preview-iframe.tsx index 36bd0aeec..55b747647 100644 --- a/src/builder/core/components/canvas/tailwind-preview-iframe.tsx +++ b/src/builder/core/components/canvas/tailwind-preview-iframe.tsx @@ -1,16 +1,7 @@ -import containerQueries from "@tailwindcss/container-queries"; -import forms from "@tailwindcss/forms"; -import typography from "@tailwindcss/typography"; import { compact, filter, get, has, uniq } from "lodash-es"; import React, { useEffect, useMemo } from "react"; -import plugin from "tailwindcss/plugin"; import { getIframeInitialContent } from "~/builder/core/components/canvas/IframeInitialContent"; -import { useBuilderProp } from "~/builder/hooks/use-builder-prop"; -import { - getChaiThemeOptions, - getThemeCustomFontFace, - getThemeFontsUrls, -} from "~/builder/core/components/canvas/static/chai-theme-helpers"; +import { getThemeCustomFontFace, getThemeFontsUrls } from "~/builder/core/components/canvas/static/chai-theme-helpers"; import { TailwindV4Theme } from "~/builder/core/components/canvas/static/head-tags"; import { CssThemeVariables } from "~/builder/core/components/css-theme-var"; import { ChaiFrame, useFrame } from "~/builder/core/frame"; @@ -24,56 +15,19 @@ const PreviewHeadTags = () => { const [chaiTheme] = useTheme(); const chaiThemeOptions = useThemeOptions(); const [darkMode] = useDarkMode(); - const { document: iframeDoc, window: iframeWin } = useFrame(); - const tailwindCSS = useBuilderProp<"3" | "4">("tailwindCSS", "4"); + const { document: iframeDoc } = useFrame(); useEffect(() => { if (darkMode) iframeDoc?.documentElement.classList.add("dark"); else iframeDoc?.documentElement.classList.remove("dark"); }, [darkMode, iframeDoc]); - useEffect(() => { - const win = iframeWin as any; - if (tailwindCSS !== "3" || !win || !win.tailwind) return; - const tailwindConfig = { - darkMode: "class", - theme: { - extend: { - container: { - center: true, - padding: "1rem", - screens: { - "2xl": "1400px", - }, - }, - ...getChaiThemeOptions(chaiThemeOptions), - }, - }, - plugins: [ - typography, - forms, - containerQueries, - plugin(function ({ addBase, theme }: any) { - addBase({ - "h1,h2,h3,h4,h5,h6": { - fontFamily: theme("fontFamily.heading"), - }, - body: { - fontFamily: theme("fontFamily.body"), - color: theme("colors.foreground"), - backgroundColor: theme("colors.background"), - }, - }); - }), - ], - }; - Object.assign(win.tailwind, { config: tailwindConfig }); - }, [chaiTheme, chaiThemeOptions, iframeWin, tailwindCSS]); - const pickedFonts = useMemo(() => { const heading = get(chaiTheme, "fontFamily.heading"); const body = get(chaiTheme, "fontFamily.body"); - return uniq(compact([heading, body])).map(resolveFont).filter(Boolean) as ChaiFont[]; + return uniq(compact([heading, body])) + .map(resolveFont) + .filter(Boolean) as ChaiFont[]; }, [chaiTheme]); const fontUrls = useMemo( @@ -88,7 +42,7 @@ const PreviewHeadTags = () => { return ( <> - {tailwindCSS === "4" ? : null} + {fontUrls.map((url) => ( ))} @@ -116,8 +70,7 @@ export const TailwindPreviewIframe = ({ title = "Preview", wrapperClassName = "", }: TailwindPreviewIframeProps) => { - const tailwindCSS = useBuilderProp<"3" | "4">("tailwindCSS", "4"); - const initialContent = useMemo(() => getIframeInitialContent({ htmlDir: "ltr", tailwindCSS }), [tailwindCSS]); + const initialContent = useMemo(() => getIframeInitialContent({ htmlDir: "ltr" }), []); const innerHtml = useInnerHtml(content); return ( diff --git a/src/builder/core/components/canvas/tailwind-v4-canvas.test.ts b/src/builder/core/components/canvas/tailwind-v4-canvas.test.ts index a7e4019b0..6f776e04c 100644 --- a/src/builder/core/components/canvas/tailwind-v4-canvas.test.ts +++ b/src/builder/core/components/canvas/tailwind-v4-canvas.test.ts @@ -30,7 +30,7 @@ describe("tailwind v4 canvas CSS", () => { colors: [{ group: "Base", items: { primary: "Primary", border: "Border", background: "Bg", foreground: "Fg" } }], } as never; - const css = `${readTailwindStyles(getIframeInitialContent({ tailwindCSS: "4" }))}\n${getChaiThemeCssTheme(themeOptions)}`; + const css = `${readTailwindStyles(getIframeInitialContent())}\n${getChaiThemeCssTheme(themeOptions)}`; const { compile } = (await import("tailwindcss")) as any; const compiler = await compile(css, { base: "/", loadStylesheet: loadTailwindStylesheet }); @@ -60,7 +60,7 @@ describe("tailwind v4 canvas CSS", () => { colors: [{ group: "Base", items: { border: "Border", primary: "Primary" } }], } as never; - const css = `${readTailwindStyles(getIframeInitialContent({ tailwindCSS: "4" }))}\n${getChaiThemeCssTheme(themeOptions)}`; + const css = `${readTailwindStyles(getIframeInitialContent())}\n${getChaiThemeCssTheme(themeOptions)}`; const { compile } = (await import("tailwindcss")) as any; const compiler = await compile(css, { base: "/", loadStylesheet: loadTailwindStylesheet }); @@ -70,48 +70,19 @@ describe("tailwind v4 canvas CSS", () => { expect(built).toContain("--color-primary: hsl(var(--primary));"); }); - // The canvas must render v3-authored content like the page CSS does (#4198). - it("keeps the v3 values of the utilities v4 rescaled", async () => { - const css = `${readTailwindStyles(getIframeInitialContent({ tailwindCSS: "4" }))}\n${getChaiThemeCssTheme({} as never)}`; + // Tailwind v4 only: the canvas theme carries no v3 value overrides, matching the page CSS. + it("compiles the rescaled utilities to Tailwind v4's own values", async () => { + const css = `${readTailwindStyles(getIframeInitialContent())}\n${getChaiThemeCssTheme({} as never)}`; const { compile } = (await import("tailwindcss")) as any; const compiler = await compile(css, { base: "/", loadStylesheet: loadTailwindStylesheet }); - const built = compiler.build(["shadow-sm", "drop-shadow-sm", "blur-sm", "backdrop-blur-sm", "ring"]); + const built = compiler.build(["shadow-sm", "blur-sm", "ring", "outline-none"]) as string; - expect(built).toContain("--shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);"); - expect(built).toContain("--drop-shadow-sm: 0 1px 1px rgb(0 0 0 / 0.05);"); - expect(built).toContain("--blur-sm: 4px;"); - expect(built).toContain("calc(3px + var(--tw-ring-offset-width))"); - }); - - it("keeps v3 outline-none and the bare ring color", async () => { - const css = `${readTailwindStyles(getIframeInitialContent({ tailwindCSS: "4" }))}\n${getChaiThemeCssTheme({} as never)}`; - - const { compile } = (await import("tailwindcss")) as any; - const compiler = await compile(css, { base: "/", loadStylesheet: loadTailwindStylesheet }); - // Unoptimized build: variants stay nested (`.focus\:outline-none { &:focus { … } }`); flatten them. - const built = (compiler.build(["outline-none", "focus:outline-none", "ring"]) as string).replace( - /\s*\{\s*&:focus\s*\{/g, - ":focus {", - ); - // Cascade result: the last declaration of `prop` across every rule for `selector`. - const last = (selector: string, prop: string) => { - const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - const bodies = Array.from(built.matchAll(new RegExp(`${escaped}\\s*\\{([^}]*)\\}`, "g")), (m) => m[1]); - const values = bodies.flatMap((body) => - Array.from(body.matchAll(new RegExp(`(?:^|[;\\s])${prop}:\\s*([^;]+);`, "g")), (m) => m[1].trim()), - ); - return values.at(-1); - }; - - for (const selector of [".outline-none", ".focus\\:outline-none:focus"]) { - expect(last(selector, "outline")).toBe("2px solid transparent"); - expect(last(selector, "outline-offset")).toBe("2px"); - expect(last(selector, "outline-style")).toBe("solid"); - expect(last(selector, "--tw-outline-style")).toBe("solid"); - } - expect(built).toContain("rgb(59 130 246 / 0.5)"); - expect(last(".ring", "--tw-ring-shadow")).not.toContain("currentcolor"); + expect(built).not.toContain("--shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);"); + expect(built).not.toContain("--blur-sm: 4px;"); + expect(built).not.toContain("rgb(59 130 246 / 0.5)"); + expect(built).toContain("calc(1px + var(--tw-ring-offset-width))"); + expect(built).toContain("outline-style: none"); }); // The page CSS compiles with the typography and forms plugins; the browser build cannot load @@ -120,7 +91,7 @@ describe("tailwind v4 canvas CSS", () => { const candidates = ["prose", "lg:prose-lg", "prose-slate", "prose-headings:underline", "max-w-none", "form-input"]; const { compile } = (await import("tailwindcss")) as any; - const canvasCss = `${readTailwindStyles(getIframeInitialContent({ tailwindCSS: "4" }))}\n${getChaiThemeCssTheme({} as never)}`; + const canvasCss = `${readTailwindStyles(getIframeInitialContent())}\n${getChaiThemeCssTheme({} as never)}`; const canvas = (await compile(canvasCss, { base: "/", loadStylesheet: loadTailwindStylesheet })).build(candidates); const plugins: Record = { diff --git a/src/builder/core/utils/color-formatter.ts b/src/builder/core/utils/color-formatter.ts index cffaaf00c..1765f9a97 100644 --- a/src/builder/core/utils/color-formatter.ts +++ b/src/builder/core/utils/color-formatter.ts @@ -10,22 +10,14 @@ export const formatNumber = (num?: number) => { export const formatHsl = (hsl: culori.Hsl) => { return `hsl(${formatNumber(hsl.h)} ${formatNumber(hsl.s * 100)}% ${formatNumber(hsl.l * 100)}%)`; }; -export const colorFormatter = ( - colorValue: string, - format: ColorFormat = "hsl", - tailwindVersion: "3" | "4" = "4", -): string => { +export const colorFormatter = (colorValue: string, format: ColorFormat = "hsl"): string => { try { const color = culori.parse(colorValue); if (!color) throw new Error("Invalid color input"); switch (format) { case "hsl": { - const hsl = culori.converter("hsl")(color); - if (tailwindVersion === "4") { - return formatHsl(hsl); - } - return `${formatNumber(hsl.h)} ${formatNumber(hsl.s * 100)}% ${formatNumber(hsl.l * 100)}%`; + return formatHsl(culori.converter("hsl")(color)); } case "rgb": return culori.formatRgb(color); diff --git a/src/builder/pages/chaibuilder-pages.tsx b/src/builder/pages/chaibuilder-pages.tsx index c8046febe..a965a763a 100644 --- a/src/builder/pages/chaibuilder-pages.tsx +++ b/src/builder/pages/chaibuilder-pages.tsx @@ -167,9 +167,12 @@ const ChaiBuilderInner = ({ ...props }: ChaiBuilderInnerProps) => { () => isLinked && currentPageId ? { - reason: t("This page shows {{label}} content, which can't be edited here. Duplicate it to edit your own copy.", { - label: upstreamLabel, - }), + reason: t( + "This page shows {{label}} content, which can't be edited here. Duplicate it to edit your own copy.", + { + label: upstreamLabel, + }, + ), action: , } : null, @@ -267,7 +270,6 @@ const ChaiBuilderInner = ({ ...props }: ChaiBuilderInnerProps) => { translations={props.translations || {}} locale={props.locale || "en"} htmlDir={props.htmlDir || "ltr"} - tailwindCSS={props.tailwindCSS ?? "4"} canvasStyles={props.canvasStyles} internalLinkHosts={props.internalLinkHosts} autoSave={!tabHidden && isEditing && !isLinked && (props.autoSave ?? true)} diff --git a/src/nextjs/server.ts b/src/nextjs/server.ts index 0171f45e2..10a686640 100644 --- a/src/nextjs/server.ts +++ b/src/nextjs/server.ts @@ -56,6 +56,8 @@ export { buildChaiBuilderConfig, getChaiBuilderConfigOnInit } from "~/server/bui export type { BuildChaiBuilderConfigOptions } from "~/server/build-config"; export { defineChaiServerPlugin, + mergeDefaultRoleGrants, + withActionPermission, getChaiRequestHeader, registerChaiActionHook, registerChaiPageVersionSource, diff --git a/src/render/get-tailwind-css.ts b/src/render/get-tailwind-css.ts index 5ad14b077..4297bb90b 100644 --- a/src/render/get-tailwind-css.ts +++ b/src/render/get-tailwind-css.ts @@ -1,4 +1,3 @@ -import twContainer from "@tailwindcss/container-queries"; import twForms from "@tailwindcss/forms"; import twTypography from "@tailwindcss/typography"; import { ChaiBlock } from "~/types/common"; @@ -42,7 +41,7 @@ async function getTailwindCSS(markupString: string[], safelist: string[] = [], i }, }, }, - plugins: [twForms, twTypography, twContainer, chaiBuilderPlugin], + plugins: [twForms, twTypography, chaiBuilderPlugin], corePlugins: { preflight: includeBaseStyles }, }, }); diff --git a/src/server/chai-actions/actions-registery.ts b/src/server/chai-actions/actions-registery.ts index 734324d84..800579660 100644 --- a/src/server/chai-actions/actions-registery.ts +++ b/src/server/chai-actions/actions-registery.ts @@ -42,7 +42,10 @@ export { ChaiActionsRegistry }; const chaiActionsRegistry = ChaiActionsRegistry.getInstance(); -/** @deprecated Use the default export / `ChaiActionsRegistry.getInstance()` instead */ +/** + * @deprecated Same object as `ChaiActionsRegistry` from `/nextjs/server` (the shared instance, + * not the class). Prefer `actions` in `buildChaiBuilderConfig` or a server plugin over runtime registration. + */ export const BuilderActionsRegistry = chaiActionsRegistry; /** The shared registered instance. To run an action, use {@link getChaiActionInstance}. */ diff --git a/src/server/chai-builder/public/get-blocks-styles.test.ts b/src/server/chai-builder/public/get-blocks-styles.test.ts index cc3b9f361..ee3bb06b7 100644 --- a/src/server/chai-builder/public/get-blocks-styles.test.ts +++ b/src/server/chai-builder/public/get-blocks-styles.test.ts @@ -88,43 +88,27 @@ describe("getBlocksStyles", () => { expect(b).not.toContain(".bg-fuchsia-600"); }); - // Content authored under Tailwind v3 must render unchanged on v4 (#4198). - it("keeps the v3 values of the utilities v4 rescaled", async () => { - const css = await getBlocksStyles([ - block("b1", "shadow-sm drop-shadow-sm blur-sm backdrop-blur-sm ring"), - ]); - const rule = (selector: string) => css.match(new RegExp(`\\${selector}\\s*\\{([^}]*)\\}`))?.[1] ?? ""; - - expect(rule(".shadow-sm")).toContain("0 1px 2px 0"); - expect(rule(".drop-shadow-sm")).toContain("drop-shadow(0 1px 1px rgb(0 0 0 / 0.05))"); - expect(rule(".blur-sm")).toContain("blur(4px)"); - expect(rule(".backdrop-blur-sm")).toContain("blur(4px)"); - expect(rule(".ring")).toContain("calc(3px + var(--tw-ring-offset-width))"); + // Container queries are core in Tailwind v4 (no @tailwindcss/container-queries plugin). + it("compiles container queries without a plugin", async () => { + const css = await getBlocksStyles([block("b1", "@container @md:flex @container/card @lg/card:grid")]); + + expect(css).toContain("container-type: inline-size"); + expect(css).toContain("container-name: card"); + expect(css).toMatch(/@container\s*\(width >= 28rem\)/); + expect(css).toMatch(/@container card\s*\(width >= 32rem\)/); }); - // v4's `outline-none` is `outline-style: none`; v3's is a transparent 2px outline (#4198). - it("keeps v3 outline-none and the bare ring color", async () => { - // The page CSS is unoptimized: variants stay nested (`.focus\:outline-none { &:focus { … } }`). - const css = (await getBlocksStyles([block("b1", "outline-none focus:outline-none ring")])).replace( - /\s*\{\s*&:focus\s*\{/g, - ":focus {", - ); - // Cascade result: the last declaration of `prop` across every rule for `selector`. - const last = (selector: string, prop: string) => { - const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - const bodies = Array.from(css.matchAll(new RegExp(`${escaped}\\s*\\{([^}]*)\\}`, "g")), (m) => m[1]); - const values = bodies.flatMap((body) => - Array.from(body.matchAll(new RegExp(`(?:^|[;\\s])${prop}:\\s*([^;]+);`, "g")), (m) => m[1].trim()), - ); - return values.at(-1); - }; - - for (const selector of [".outline-none", ".focus\\:outline-none:focus"]) { - expect(last(selector, "outline")).toBe("2px solid transparent"); - expect(last(selector, "outline-offset")).toBe("2px"); - expect(last(selector, "outline-style")).toBe("solid"); - expect(last(selector, "--tw-outline-style")).toBe("solid"); - } - expect(last(".ring", "--tw-ring-shadow")).toContain("var(--tw-ring-color, rgb(59 130 246 / 0.5))"); + // Tailwind v4 only: no v3 value overrides ride along with the page CSS. + it("compiles the rescaled utilities to Tailwind v4's own values", async () => { + const css = await getBlocksStyles([block("b1", "shadow-sm blur-sm ring outline-none")]); + const rule = (selector: string) => css.match(new RegExp(`\\${selector}\\s*\\{([^}]*)\\}`))?.[1] ?? ""; + + expect(css).not.toContain("0 1px 2px 0 rgb(0 0 0 / 0.05)"); + expect(css).not.toContain("rgb(59 130 246 / 0.5)"); + expect(rule(".blur-sm")).not.toContain("blur(4px)"); + expect(rule(".ring")).toContain("calc(1px + var(--tw-ring-offset-width))"); + expect(rule(".ring")).toContain("currentcolor"); + expect(rule(".outline-none")).toContain("outline-style: none"); + expect(rule(".outline-none")).not.toContain("2px solid transparent"); }); }); diff --git a/src/server/chai-builder/public/get-blocks-styles.ts b/src/server/chai-builder/public/get-blocks-styles.ts index 85e21dfb2..60d18950a 100644 --- a/src/server/chai-builder/public/get-blocks-styles.ts +++ b/src/server/chai-builder/public/get-blocks-styles.ts @@ -1,4 +1,3 @@ -import twContainer from "@tailwindcss/container-queries"; import twForms from "@tailwindcss/forms"; import twTypography from "@tailwindcss/typography"; import type { ChaiBlock } from "~/types"; @@ -37,7 +36,7 @@ const getPageTailwindConfig = () => ({ }, }, }, - plugins: [twForms, twTypography, twContainer], + plugins: [twForms, twTypography], corePlugins: { preflight: false }, }); diff --git a/src/server/chai-builder/public/get-page-styles.test.ts b/src/server/chai-builder/public/get-page-styles.test.ts index 3d0051eb3..fd0925428 100644 --- a/src/server/chai-builder/public/get-page-styles.test.ts +++ b/src/server/chai-builder/public/get-page-styles.test.ts @@ -125,7 +125,7 @@ describe("get-page-styles", () => { expect(cache.wraps).toEqual([ { - keyParts: [`page-styles-${TEST_APP_ID}-page-1-c4-m3-g-${fingerprint}`], + keyParts: [`page-styles-${TEST_APP_ID}-page-1-c5-m3-g-${fingerprint}`], tags: ["page-styles", "page-page-1"], }, ]); diff --git a/src/server/chai-builder/public/get-page-styles.ts b/src/server/chai-builder/public/get-page-styles.ts index 538dc673c..7cddbe46e 100644 --- a/src/server/chai-builder/public/get-page-styles.ts +++ b/src/server/chai-builder/public/get-page-styles.ts @@ -14,10 +14,10 @@ const pageStylesLogger = consola.withTag("ChaiPageStyles"); // in the Data Cache, which outlives deployments, so the key must change or an older deploy's output // keeps being served. v2: the min-width `@media` sort no longer depends on postcss (which is not // bundled into the v4 serverless runtime), so previously-cached *unsorted* CSS — the cause of -// breakpoint-forked menus rendering both variants — must be recomputed. v3: Tailwind v3 values -// for shadow-sm / drop-shadow-sm / blur-sm / backdrop-blur-sm / bare ring (V3_SCALE). v4: v3 -// `outline-none` and bare `ring` color (V3_COMPAT_CSS). -const PAGE_STYLES_COMPILER_VERSION = "4"; +// breakpoint-forked menus rendering both variants — must be recomputed. v3/v4: Tailwind v3 value +// overrides (since removed). v5: those overrides are gone; shadow-sm, drop-shadow-sm, blur-sm, +// backdrop-blur-sm, bare `ring` and `outline-none` compile to Tailwind v4's own values. +const PAGE_STYLES_COMPILER_VERSION = "5"; // Stable function reference for caching - defined once at module level export async function fetchPageStylesUncached(blocks: ChaiBlock[]): Promise { diff --git a/src/server/defaults/index.ts b/src/server/defaults/index.ts index bb99fbd5f..0714ebcde 100644 --- a/src/server/defaults/index.ts +++ b/src/server/defaults/index.ts @@ -47,10 +47,12 @@ export function resolveChaiBuilderConfig(rawInput: ChaiBuilderServerConfigInput) contextResolver: appContextResolver ?? afterPlugins.contextResolver, }; const ai = resolveAiConfig(input.ai); + // `builderActions` is the deprecated spelling of `actions`: it is merged first, so on a name + // clash the current key wins and a host mid-migration can pass either. const actions = { ...DEFAULT_CHAI_BUILDER_SERVER_CONFIG.actions, - ...input.actions, ...input.builderActions, + ...input.actions, }; const trash = mergeByKey(DEFAULT_CHAI_BUILDER_SERVER_CONFIG.trash, input.trash, (entry) => entry.key); const defaultFeatures = DEFAULT_CHAI_BUILDER_SERVER_CONFIG.features; diff --git a/src/server/defaults/resolve-config.test.ts b/src/server/defaults/resolve-config.test.ts index c0954141b..14172fbf5 100644 --- a/src/server/defaults/resolve-config.test.ts +++ b/src/server/defaults/resolve-config.test.ts @@ -119,6 +119,21 @@ describe("resolveChaiBuilderConfig", () => { expect(config.builderActions.custom).toBe(customAction); }); + it("lets `actions` win over the deprecated `builderActions` on a name clash", () => { + const current = { name: "current", execute: () => ({ ok: true }) }; + const legacy = { name: "legacy", execute: () => ({ ok: true }) }; + const legacyOnly = { name: "legacyOnly", execute: () => ({ ok: true }) }; + + const config = resolveChaiBuilderConfig({ + db: stubChaiDbSetup(), + actions: { CUSTOM: current as any }, + builderActions: { CUSTOM: legacy as any, LEGACY_ONLY: legacyOnly as any }, + }); + + expect(config.actions.CUSTOM).toBe(current); + expect(config.actions.LEGACY_ONLY).toBe(legacyOnly); + }); + it("derives feature flags from bare db config", () => { const config = resolveChaiBuilderConfig({ db: stubChaiDbSetup() }); diff --git a/src/types/chaibuilder-editor-props.ts b/src/types/chaibuilder-editor-props.ts index 493fcbbe9..2280978ca 100644 --- a/src/types/chaibuilder-editor-props.ts +++ b/src/types/chaibuilder-editor-props.ts @@ -229,12 +229,6 @@ export interface ChaiBuilderEditorProps { */ htmlDir?: "ltr" | "rtl"; - /** - * Tailwind CSS major version for the canvas iframe Play CDN. - * `"3"` → cdn.tailwindcss.com/3.x; `"4"` → @tailwindcss/browser@4. Default `"4"`. - */ - tailwindCSS?: "3" | "4"; - /** * Plain CSS injected into the canvas iframe `` (as a regular ` ) : null} - { it("initializes Chai db singleton from config", () => { const setup = stubChaiDbSetup(); - resetDbForTests(); + resetChaiDbForTests(); buildChaiBuilderConfig({ db: setup }); - expect(getDb()).toBe(setup.drizzle); + expect(getChaiDb()).toBe(setup.drizzle); }); it("requires db in resolve step", () => { diff --git a/src/server/build-config.ts b/src/server/build-config.ts index 474501896..c92340a67 100644 --- a/src/server/build-config.ts +++ b/src/server/build-config.ts @@ -1,14 +1,14 @@ import "~/server/only-server"; import { is, Table } from "drizzle-orm"; import { assertChaiTableMappingKeys, rebindChaiRelations } from "~/db/table-mapping"; -import { registerDb } from "~/db/core"; +import { registerChaiDb } from "~/db/core"; import { syncBlockDataProvidersToRegistry } from "~/server/defaults/block-data-providers"; import { setActiveChaiBuilderConfig } from "~/server/defaults/config-registry"; import { editionServerPlugins } from "~/edition/builtin-server-plugins"; import { EDITION_TABLE_NAMES } from "~/edition/table-names"; import { registerChaiRequestMiddleware } from "~/server/plugin-api/request-middleware"; import type { ChaiSchemaFragment } from "~/types/plugin"; -import { setChaiContextResolver } from "./chai-context-resolver"; +import { registerChaiContextResolver } from "./chai-context-resolver"; import { resolveChaiBuilderConfig, type ChaiBuilderServerConfigInput, @@ -22,6 +22,7 @@ const onInitByConfig = new WeakMap = }); const extended = { ...resolved, ...(options?.extend ?? {}) } as ResolvedChaiBuilderServerConfig & TExtra; extended.db = withPluginSchema(extended.db, extended.schemaFragments); - registerDb(extended.db); + registerChaiDb(extended.db); setActiveChaiBuilderConfig(extended); syncBlockDataProvidersToRegistry(extended.blockDataProviders); registerPluginRuntime(extended); @@ -107,7 +108,7 @@ function withPluginSchema( function registerPluginRuntime(config: Readonly): void { if (config.contextResolver) { // Last plugin to set it wins; a later `createChaiBuilder(config, { context })` wins over all. - setChaiContextResolver(config.contextResolver); + registerChaiContextResolver(config.contextResolver); } for (const { name, handler } of config.requestMiddlewares) { registerChaiRequestMiddleware(name, handler); diff --git a/src/server/chai-actions/action-result.test.ts b/src/server/chai-actions/action-result.test.ts index c02dc4442..2fbf49784 100644 --- a/src/server/chai-actions/action-result.test.ts +++ b/src/server/chai-actions/action-result.test.ts @@ -1,12 +1,12 @@ import { describe, expect, it } from "vitest"; import { ActionError } from "./action-error"; -import { isChaiActionFailure, isChaiActionSuccess, toActionError, toActionErrorPayload } from "./action-result"; +import { isChaiActionFailure, isChaiActionSuccess, toChaiActionError, toChaiActionErrorPayload } from "./action-result"; describe("action-result helpers", () => { it("serializes ActionError to payload", () => { const error = new ActionError("Slug already exists", "SLUG_ALREADY_USED", 409, undefined, { slug: "/home" }); - expect(toActionErrorPayload(error)).toEqual({ + expect(toChaiActionErrorPayload(error)).toEqual({ code: "SLUG_ALREADY_USED", message: "Slug already exists", status: 409, @@ -15,7 +15,7 @@ describe("action-result helpers", () => { }); it("wraps unknown errors as INTERNAL_ERROR", () => { - expect(toActionErrorPayload(new Error("boom"))).toEqual({ + expect(toChaiActionErrorPayload(new Error("boom"))).toEqual({ code: "INTERNAL_ERROR", message: "boom", status: 500, @@ -23,7 +23,7 @@ describe("action-result helpers", () => { }); it("normalizes arbitrary errors through toActionError", () => { - const error = toActionError("unexpected"); + const error = toChaiActionError("unexpected"); expect(error).toBeInstanceOf(ActionError); expect(error.code).toBe("INTERNAL_ERROR"); }); diff --git a/src/server/chai-actions/action-result.ts b/src/server/chai-actions/action-result.ts index 853544a78..58be0e17b 100644 --- a/src/server/chai-actions/action-result.ts +++ b/src/server/chai-actions/action-result.ts @@ -14,17 +14,13 @@ export type ChaiActionResult = ChaiActionSuccess | ChaiActionFailure; // AI_EDIT_PAGE is intentionally NOT listed: it streams AI SDK UIMessage SSE, // and pre-stream failures (credits, auth, validation) must return plain JSON // errors with real HTTP statuses so the client chat transport can surface them. -export const STREAMING_CHAI_ACTIONS = new Set([ - "AI_EDIT_BLOCK", - "AI_EDIT_LANG_PAGE", - "AI_GENERATE_IMAGE", -]); +export const STREAMING_CHAI_ACTIONS = new Set(["AI_EDIT_BLOCK", "AI_EDIT_LANG_PAGE", "AI_GENERATE_IMAGE"]); export function isStreamingChaiAction(action: string): boolean { return STREAMING_CHAI_ACTIONS.has(action); } -export function toActionErrorPayload(error: unknown): ChaiActionErrorPayload { +export function toChaiActionErrorPayload(error: unknown): ChaiActionErrorPayload { if (error instanceof ActionError) { return { code: error.code, @@ -62,12 +58,12 @@ export function toActionErrorPayload(error: unknown): ChaiActionErrorPayload { }; } -export function toActionError(error: unknown): ActionError { +export function toChaiActionError(error: unknown): ActionError { if (error instanceof ActionError) { return error; } - const payload = toActionErrorPayload(error); + const payload = toChaiActionErrorPayload(error); return new ActionError(payload.message, payload.code, payload.status); } diff --git a/src/server/chai-actions/actions-registery.ts b/src/server/chai-actions/actions-registery.ts index 800579660..9479b25f3 100644 --- a/src/server/chai-actions/actions-registery.ts +++ b/src/server/chai-actions/actions-registery.ts @@ -42,12 +42,6 @@ export { ChaiActionsRegistry }; const chaiActionsRegistry = ChaiActionsRegistry.getInstance(); -/** - * @deprecated Same object as `ChaiActionsRegistry` from `/nextjs/server` (the shared instance, - * not the class). Prefer `actions` in `buildChaiBuilderConfig` or a server plugin over runtime registration. - */ -export const BuilderActionsRegistry = chaiActionsRegistry; - /** The shared registered instance. To run an action, use {@link getChaiActionInstance}. */ export const getChaiAction = (action: string): ChaiAction | undefined => { const legacyOverride = chaiActionsRegistry.getAction(action); diff --git a/src/server/chai-actions/ai/ask-ai/ai-edit-block-action.ts b/src/server/chai-actions/ai/ask-ai/ai-edit-block-action.ts index e9971123a..f2b5bf972 100644 --- a/src/server/chai-actions/ai/ask-ai/ai-edit-block-action.ts +++ b/src/server/chai-actions/ai/ask-ai/ai-edit-block-action.ts @@ -2,13 +2,13 @@ import { ModelMessage } from "ai"; import { z } from "zod"; import { isBlockAvailableForPageType } from "~/builder/core/functions/block-helpers"; import { CHAI_BUILT_IN_DESIGN_TOKENS } from "~/constants/BUILTIN_TOKENS"; -import { getAllRegisteredChaiBlocks } from "~/registry"; +import { getRegisteredChaiBlocks } from "~/registry"; import { getResolvedPageType } from "~/server/defaults/config-registry"; import { throwAiChatError } from "~/server/chai-actions/ai/throw-ai-chat-error"; import { AIChatError, AIChatErrorCode } from "~/server/chai-actions/classes/chai-ai-chat-handler"; import { getAskAiSystemPrompt } from "~/server/chai-actions/classes/system-prompt"; import { stripDesignContextKeys } from "~/utils/design-context"; -import { ChaiAIActionData, ChaiBaseAIAction, CoreMessage } from "../../base-ai-action"; +import { ChaiAIActionData, ChaiBaseAiAction, CoreMessage } from "../../base-ai-action"; import { buildDataBindingPathsText, buildDataBindingPipesText } from "./ai-edit-page-prompt-context"; const designTokensSchema = z @@ -33,7 +33,7 @@ export type AIEditBlockStreamResponse = { /** * Action to handle AI_EDIT_BLOCK requests */ -export class AIEditBlockAction extends ChaiBaseAIAction { +export class AIEditBlockAction extends ChaiBaseAiAction { protected getValidationSchema() { return z.object({ messages: z.array(z.any()), @@ -106,7 +106,7 @@ export class AIEditBlockAction extends ChaiBaseAIAction !CORE_BLOCK_TYPES.has(b.type) && isBlockAvailableForPageType(b, pageTypeKey || "page"), ); diff --git a/src/server/chai-actions/ai/ask-ai/ai-edit-executors.ts b/src/server/chai-actions/ai/ask-ai/ai-edit-executors.ts index 6606fde20..551947aca 100644 --- a/src/server/chai-actions/ai/ask-ai/ai-edit-executors.ts +++ b/src/server/chai-actions/ai/ask-ai/ai-edit-executors.ts @@ -1,6 +1,6 @@ import { canDeleteBlock } from "~/builder/core/functions/block-helpers"; -import { generateUUID } from "~/builder/core/functions/common-functions"; -import { getAllRegisteredChaiBlocks, getRegisteredChaiBlock } from "~/registry"; +import { generateUuid } from "~/builder/core/functions/common-functions"; +import { getRegisteredChaiBlocks, getRegisteredChaiBlock } from "~/registry"; import { hasOnlyRegisteredChaiPipes, isValidBindingTemplate, parseBindingExpression } from "~/render/binding-pipes"; import type { ChaiBlock } from "~/types/common"; import { @@ -318,7 +318,7 @@ export const applyAddBlocks = async ( }; const validCustomBlockTypes = (): string[] => - Object.entries(getAllRegisteredChaiBlocks()) + Object.entries(getRegisteredChaiBlocks()) .map(([registryKey, block]) => block.type ?? registryKey) .filter((type): type is string => typeof type === "string" && type.length > 0) .sort(); @@ -345,7 +345,7 @@ export const applyAddCustomBlock = ( const sanitizedProps = sanitizeAiProps(props); const block: ChaiBlock = { - _id: generateUUID(), + _id: generateUuid(), _type: type, _parent: target.parentId, ...(options.resolveInternalLink diff --git a/src/server/chai-actions/ai/ask-ai/ai-edit-page-action.ts b/src/server/chai-actions/ai/ask-ai/ai-edit-page-action.ts index 81f5e8999..fb1b48ec3 100644 --- a/src/server/chai-actions/ai/ask-ai/ai-edit-page-action.ts +++ b/src/server/chai-actions/ai/ask-ai/ai-edit-page-action.ts @@ -4,7 +4,7 @@ import { AI_OMITTED_HTML_SENTINEL } from "~/constants/AI_TOOL_HISTORY"; import { throwAiChatError } from "~/server/chai-actions/ai/throw-ai-chat-error"; import { AIChatError, AIChatErrorCode } from "~/server/chai-actions/classes/chai-ai-chat-handler"; import { getEditPageToolsSystemPrompt } from "~/server/chai-actions/classes/system-prompt/edit-page-tools-system-prompt"; -import { ChaiAIActionData, ChaiBaseAIAction } from "../../base-ai-action"; +import { ChaiAIActionData, ChaiBaseAiAction } from "../../base-ai-action"; import { fillAiEditSystemPromptContext } from "./ai-edit-page-prompt-context"; import { buildAiEditPageTools } from "./ai-edit-page-tools"; @@ -76,7 +76,7 @@ const pruneHistoryToolInputs = (messages: UIMessage[]): UIMessage[] => { * context — the model works from the compact page outline in the system * prompt and reads block HTML on demand. */ -export class AIEditPageAction extends ChaiBaseAIAction { +export class AIEditPageAction extends ChaiBaseAiAction { protected getValidationSchema() { return z.object({ messages: z.array(z.any()).min(1), diff --git a/src/server/chai-actions/ai/ask-ai/ai-edit-page-prompt-context.ts b/src/server/chai-actions/ai/ask-ai/ai-edit-page-prompt-context.ts index 6996662c7..e02a82e6b 100644 --- a/src/server/chai-actions/ai/ask-ai/ai-edit-page-prompt-context.ts +++ b/src/server/chai-actions/ai/ask-ai/ai-edit-page-prompt-context.ts @@ -1,6 +1,6 @@ import { CHAI_BUILT_IN_DESIGN_TOKENS } from "~/constants/BUILTIN_TOKENS"; import { isBlockAvailableForPageType } from "~/builder/core/functions/block-helpers"; -import { getAllRegisteredChaiBlocks } from "~/registry"; +import { getRegisteredChaiBlocks } from "~/registry"; import { getRegisteredChaiPipes } from "~/registry/pipes"; import { serializePipeLiteral } from "~/render/binding-pipes"; import { getResolvedPageType } from "~/server/defaults/config-registry"; @@ -48,7 +48,7 @@ export const buildDesignTokensList = (designTokens: ChaiAIActionData["designToke .join("\n"); }; -type RegisteredCustomBlock = ReturnType[string]; +type RegisteredCustomBlock = ReturnType[string]; /** * True for a registry entry the AI treats as a custom block: not a core @@ -64,7 +64,7 @@ export const isCustomCatalogBlock = (registryKey: string, block: RegisteredCusto /** The custom blocks available on a page type, as `[registryKey, block]` in registry order. */ export const getCustomCatalogBlocks = (pageType?: string): [string, RegisteredCustomBlock][] => - Object.entries(getAllRegisteredChaiBlocks()).filter( + Object.entries(getRegisteredChaiBlocks()).filter( ([registryKey, block]) => isCustomCatalogBlock(registryKey, block) && isBlockAvailableForPageType(block, pageType || "page"), ); diff --git a/src/server/chai-actions/apps/app-store.ts b/src/server/chai-actions/apps/app-store.ts index e807f1f58..9b10c4ab0 100644 --- a/src/server/chai-actions/apps/app-store.ts +++ b/src/server/chai-actions/apps/app-store.ts @@ -1,5 +1,5 @@ import { eq } from "drizzle-orm"; -import { type DbResult, db, safeQuery, schema } from "~/server/chai-actions/db"; +import { type ChaiDbResult, db, safeQuery, schema } from "~/server/chai-actions/db"; /** * The one entry point for an app row keyed by id: every core read or write of `apps` / @@ -13,7 +13,7 @@ type AppRow = Record; type ReadOpts = { draft?: boolean }; /** The full row. `data: null` = not found. */ -export async function getAppRow(appId: string, { draft = true }: ReadOpts = {}): Promise> { +export async function getAppRow(appId: string, { draft = true }: ReadOpts = {}): Promise> { const table = draft ? schema.apps : schema.appsOnline; const query = draft ? db.query.apps : db.query.appsOnline; const result = await safeQuery(() => query.findFirst({ where: eq(table.id, appId) })); @@ -25,7 +25,7 @@ export async function getAppFields( appId: string, keys: readonly string[], { draft = true }: ReadOpts = {}, -): Promise> { +): Promise> { const table = draft ? schema.apps : schema.appsOnline; const query = draft ? db.query.apps : db.query.appsOnline; const columns = Object.fromEntries(keys.map((key) => [key, true])); @@ -34,6 +34,6 @@ export async function getAppFields( } /** Updates the draft row. */ -export async function updateAppFields(appId: string, patch: AppRow): Promise> { +export async function updateAppFields(appId: string, patch: AppRow): Promise> { return safeQuery(() => db.update(schema.apps).set(patch).where(eq(schema.apps.id, appId))); } diff --git a/src/server/chai-actions/base-action.ts b/src/server/chai-actions/base-action.ts index ee60ab7b7..114b5bbcf 100644 --- a/src/server/chai-actions/base-action.ts +++ b/src/server/chai-actions/base-action.ts @@ -9,13 +9,13 @@ import { ChaiAction, ChaiActionContext, ChaiRequiredPermission } from "./chai-ac export abstract class ChaiBaseAction implements ChaiAction { protected context: ChaiActionContext | null = null; /** - * Permission required to run this action. Enforced by `dispatchChaiAction`. + * Permission required to run this action. Enforced by `runChaiAction`. * Override in subclasses. Undefined = authenticated-only (no specific permission). */ public requiredPermission?: ChaiRequiredPermission; /** * Static superset of the keys {@link requiredPermission} may require. Set by - * `wp` / `withActionPermission` at registration; see `permission-keys.ts`. + * `wp` / `withChaiActionPermission` at registration; see `permission-keys.ts`. */ public declaredPermissionKeys?: string[]; /** diff --git a/src/server/chai-actions/base-ai-action.test.ts b/src/server/chai-actions/base-ai-action.test.ts index 9fab7bf36..57dc1ead9 100644 --- a/src/server/chai-actions/base-ai-action.test.ts +++ b/src/server/chai-actions/base-ai-action.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it } from "vitest"; import { captureConsola } from "~/tests/utils/capture-consola"; import { setGlobalDebugLevel } from "~/server/debug/debug-level"; -import { buildAiUsageMessageMetadata, ChaiBaseAIAction as BaseAIAction } from "./base-ai-action"; +import { buildAiUsageMessageMetadata, ChaiBaseAiAction as BaseAIAction } from "./base-ai-action"; describe("buildAiUsageMessageMetadata", () => { it("returns totalTokens from the finish part's totalUsage (cbpl#161)", () => { diff --git a/src/server/chai-actions/base-ai-action.ts b/src/server/chai-actions/base-ai-action.ts index 8be876b09..1e68ac38b 100644 --- a/src/server/chai-actions/base-ai-action.ts +++ b/src/server/chai-actions/base-ai-action.ts @@ -1,9 +1,14 @@ -import { generateImage as aiGenerateImage, generateText as aiGenerateText, streamText as aiStreamText, stepCountIs } from "ai"; +import { + generateImage as aiGenerateImage, + generateText as aiGenerateText, + streamText as aiStreamText, + stepCountIs, +} from "ai"; import { removeBraces } from "~/builder/core/utils/remove-braces"; import { shouldDebug } from "~/server/debug/debug-level"; import { sanitizeAiLogText, summarizeAiMessages } from "~/server/debug/debug-ai"; import { logAi, logAiPhaseStart, logAiStreamEvent, logAiToolCall, logAiVerbose } from "~/server/debug/debug-log"; -import { AIContext } from "~/types"; +import { ChaiAiContext } from "~/types"; import { ChaiDesignTokens } from "~/types/types"; import { ActionError } from "./action-error"; import { ensureAiProvider } from "./ai-providers"; @@ -11,15 +16,11 @@ import { ChaiBaseAction } from "./base-action"; import { getAiLogger, isAiCreditsEnabled, resolveImageModel, resolveLanguageModel } from "./lib"; import { isFeatureEnabled } from "~/server/defaults/config-registry"; import { getChaiCreditProvider } from "~/server/plugin-api/credit-provider"; -import { - resolveChaiAiPrompt, - resolveChaiAiTools, - type ChaiAiActionInfo, -} from "~/server/plugin-api/ai-customization"; +import { resolveChaiAiPrompt, resolveChaiAiTools, type ChaiAiActionInfo } from "~/server/plugin-api/ai-customization"; import type { CreditStatus } from "~/types/credits"; // Re-export for convenience -export type { ChaiAIGlobalConfig } from "~/types/ai-config"; +export type { ChaiAiGlobalConfig } from "~/types/ai-config"; /** `messageMetadata` callback for `toUIMessageStreamResponse` — puts the run's * token usage on the finished assistant message so the client can warn (cbpl#161). */ @@ -42,7 +43,7 @@ export type CoreMessage = { export type ChaiAIActionData = { messages: CoreMessage[]; model?: string; - context?: AIContext; + context?: ChaiAiContext; designTokens?: ChaiDesignTokens; images?: string[]; attachments?: { url?: string; mediaType?: string; filename?: string }[]; @@ -74,7 +75,7 @@ export type PromptVariant = { weight?: number; }; -export abstract class ChaiBaseAIAction extends ChaiBaseAction { +export abstract class ChaiBaseAiAction extends ChaiBaseAction { protected model?: string; protected prompts?: PromptVariant[]; @@ -128,10 +129,7 @@ export abstract class ChaiBaseAIAction extends ChaiBaseAction { return { ...(baseTools ?? {}), ...contributed }; } - private logTokenUsage( - usage?: { totalTokens?: number } | null, - totalUsage?: { totalTokens?: number } | null, - ): void { + private logTokenUsage(usage?: { totalTokens?: number } | null, totalUsage?: { totalTokens?: number } | null): void { if (!shouldDebug(2)) return; const tokens = totalUsage?.totalTokens ?? usage?.totalTokens; if (tokens !== undefined) { @@ -477,11 +475,7 @@ export abstract class ChaiBaseAIAction extends ChaiBaseAction { } /** Tools with no server execute() — results must be applied on the client. */ - private static readonly CLIENT_ONLY_AI_TOOLS = new Set([ - "remove_blocks", - "add_custom_block", - "bind_prop", - ]); + private static readonly CLIENT_ONLY_AI_TOOLS = new Set(["remove_blocks", "add_custom_block", "bind_prop"]); /** * Multiplexes AI SDK fullStream into a mixed wire format: @@ -524,10 +518,7 @@ export abstract class ChaiBaseAIAction extends ChaiBaseAction { } controller.enqueue(encoder.encode(part.text)); - } else if ( - part.type === "tool-call" && - ChaiBaseAIAction.CLIENT_ONLY_AI_TOOLS.has(part.toolName) - ) { + } else if (part.type === "tool-call" && ChaiBaseAiAction.CLIENT_ONLY_AI_TOOLS.has(part.toolName)) { logAiToolCall(part.toolName, sanitizeAiLogText(JSON.stringify(part.input))); controller.enqueue( encoder.encode( diff --git a/src/server/chai-actions/chai-builder-actions-handler.ts b/src/server/chai-actions/chai-builder-actions-handler.ts index a55ead2ff..5c7397968 100644 --- a/src/server/chai-actions/chai-builder-actions-handler.ts +++ b/src/server/chai-actions/chai-builder-actions-handler.ts @@ -1,14 +1,11 @@ import { runInContext } from "~/server/chai-builder/state"; -import { dispatchChaiAction } from "./dispatch-action"; +import { runChaiAction } from "./dispatch-action"; -export const initChaiActionHandler = (params: { apiKey: string; userId: string }) => { +export const createChaiActionHandler = (params: { apiKey: string; userId: string }) => { return async (actionData: { action: string; data?: unknown }) => { const { apiKey, userId } = params; const { action, data } = actionData; - return runInContext({ appId: apiKey, userId }, () => dispatchChaiAction(action, data)); + return runInContext({ appId: apiKey, userId }, () => runChaiAction(action, data)); }; }; - -/** @deprecated Use `initChaiActionHandler` instead */ -export const initChaiBuilderActionHandler = initChaiActionHandler; diff --git a/src/server/chai-actions/db.ts b/src/server/chai-actions/db.ts index d157ec296..6f0706129 100644 --- a/src/server/chai-actions/db.ts +++ b/src/server/chai-actions/db.ts @@ -1,16 +1,11 @@ -export type { - ChaiDbContext, - ChaiDbSetup, - DbInstance, - DbResult, -} from "~/db/core"; +export type { ChaiDbContext, ChaiDbSetup, ChaiDbInstance, ChaiDbResult } from "~/db/core"; export { db, - ensureDbReady, - getDb, - getDbDialect, - registerDb, - resetDbForTests, + ensureChaiDbReady, + getChaiDb, + getChaiDbDialect, + registerChaiDb, + resetChaiDbForTests, safeQuery, schema, } from "~/db/core"; diff --git a/src/server/chai-actions/dispatch-action.test.ts b/src/server/chai-actions/dispatch-action.test.ts index dc3ea697e..6cc52647c 100644 --- a/src/server/chai-actions/dispatch-action.test.ts +++ b/src/server/chai-actions/dispatch-action.test.ts @@ -5,8 +5,8 @@ import { runInContext } from "~/server/chai-builder/state"; import { resetActiveChaiBuilderConfigForTests } from "~/server/defaults/config-registry"; import { registerChaiPermissions, resetChaiPermissionsForTests } from "~/server/plugin-api/permission-registry"; import { ChaiBaseAction } from "./base-action"; -import { ChaiBaseAIAction } from "./base-ai-action"; -import { dispatchChaiAction, tryChaiAction } from "./dispatch-action"; +import { ChaiBaseAiAction } from "./base-ai-action"; +import { runChaiAction, tryChaiAction } from "./dispatch-action"; /** A member of the app, as the context resolver would report them. */ const member = (permissions: string[], role = "editor") => ({ @@ -36,19 +36,19 @@ describe("dispatchChaiAction", () => { }); it("throws when userId is missing for authenticated actions", async () => { - await expect(runInContext({ appId: "test-app" }, () => dispatchChaiAction("GET_DRAFT_PAGE", {}))).rejects.toThrow( + await expect(runInContext({ appId: "test-app" }, () => runChaiAction("GET_DRAFT_PAGE", {}))).rejects.toThrow( /initWithUser/, ); }); it("dispatches authenticated actions for a member", async () => { - const result = await runInContext(member(["*"], "admin"), () => dispatchChaiAction("CHECK_USER_ACCESS", {})); + const result = await runInContext(member(["*"], "admin"), () => runChaiAction("CHECK_USER_ACCESS", {})); expect(result).toMatchObject({ access: true, role: "admin" }); }); it("throws ACTION_NOT_FOUND for unknown actions", async () => { - await expect(runInContext(member(["*"]), () => dispatchChaiAction("UNKNOWN_ACTION", {}))).rejects.toMatchObject({ + await expect(runInContext(member(["*"]), () => runChaiAction("UNKNOWN_ACTION", {}))).rejects.toMatchObject({ code: "ACTION_NOT_FOUND", }); }); @@ -57,19 +57,19 @@ describe("dispatchChaiAction", () => { // as a member, and there is nobody left to ask. it("rejects an authenticated user the resolver granted no permissions", async () => { await expect( - runInContext({ appId: "test-app", userId: "user-1" }, () => dispatchChaiAction("CREATE_PAGE", {})), + runInContext({ appId: "test-app", userId: "user-1" }, () => runChaiAction("CREATE_PAGE", {})), ).rejects.toMatchObject({ code: "UNAUTHORIZED" }); }); it("reports the resolver's decision through CHECK_USER_ACCESS", async () => { - const result = await runInContext(member(["pages:read"]), () => dispatchChaiAction("CHECK_USER_ACCESS", {})); + const result = await runInContext(member(["pages:read"]), () => runChaiAction("CHECK_USER_ACCESS", {})); expect(result).toEqual({ access: true, role: "editor", permissions: ["pages:read"], userId: "user-1" }); }); it("defaults the role label when the resolver supplies permissions without one", async () => { const result = (await runInContext({ appId: "test-app", userId: "user-1", permissions: [] }, () => - dispatchChaiAction("CHECK_USER_ACCESS", {}), + runChaiAction("CHECK_USER_ACCESS", {}), )) as { role: string }; expect(result.role).toBe("custom"); @@ -78,7 +78,7 @@ describe("dispatchChaiAction", () => { it("runs a gated action the user is granted", async () => { registerGatedAction("GATED_READ", "pages:read"); - const result = await runInContext(member(["pages:read"]), () => dispatchChaiAction("GATED_READ", {})); + const result = await runInContext(member(["pages:read"]), () => runChaiAction("GATED_READ", {})); expect(result).toEqual({ ok: true }); }); @@ -86,25 +86,26 @@ describe("dispatchChaiAction", () => { it("denies a gated action the user is not granted", async () => { registerGatedAction("GATED_UPDATE", "pages:update"); - await expect( - runInContext(member(["pages:read"]), () => dispatchChaiAction("GATED_UPDATE", {})), - ).rejects.toMatchObject({ code: "FORBIDDEN" }); + await expect(runInContext(member(["pages:read"]), () => runChaiAction("GATED_UPDATE", {}))).rejects.toMatchObject({ + code: "FORBIDDEN", + }); }); // Array form: every listed key must be held (the SEO gate on UPDATE_PAGE). it("requires every key of a list-form permission", async () => { registerGatedAction("GATED_LIST", ["pages:update", "pages:edit_seo"]); - await expect( - runInContext(member(["pages:update"]), () => dispatchChaiAction("GATED_LIST", {})), - ).rejects.toMatchObject({ code: "FORBIDDEN", message: "Missing permission: pages:edit_seo" }); + await expect(runInContext(member(["pages:update"]), () => runChaiAction("GATED_LIST", {}))).rejects.toMatchObject({ + code: "FORBIDDEN", + message: "Missing permission: pages:edit_seo", + }); }); it("runs a list-form action when every key is held", async () => { registerGatedAction("GATED_LIST_OK", ["pages:update", "pages:edit_seo"]); const result = await runInContext(member(["pages:update", "pages:edit_seo"]), () => - dispatchChaiAction("GATED_LIST_OK", {}), + runChaiAction("GATED_LIST_OK", {}), ); expect(result).toEqual({ ok: true }); @@ -122,11 +123,11 @@ describe("dispatchChaiAction", () => { } buildChaiBuilderConfig({ db: stubChaiDbConfig(), actions: { GATED_DERIVED: new DerivedAction() } }); + await expect(runInContext(member(["pages:update"]), () => runChaiAction("GATED_DERIVED", {}))).resolves.toEqual({ + ok: true, + }); await expect( - runInContext(member(["pages:update"]), () => dispatchChaiAction("GATED_DERIVED", {})), - ).resolves.toEqual({ ok: true }); - await expect( - runInContext(member(["pages:update"]), () => dispatchChaiAction("GATED_DERIVED", { seo: {} })), + runInContext(member(["pages:update"]), () => runChaiAction("GATED_DERIVED", { seo: {} })), ).rejects.toMatchObject({ code: "FORBIDDEN" }); }); @@ -143,9 +144,9 @@ describe("dispatchChaiAction", () => { }); registerGatedAction("GATED_UPDATE", "pages:update"); - await expect( - runInContext(member(["pages:read"]), () => dispatchChaiAction("GATED_UPDATE", {})), - ).rejects.toMatchObject({ code: "FORBIDDEN" }); + await expect(runInContext(member(["pages:read"]), () => runChaiAction("GATED_UPDATE", {}))).rejects.toMatchObject({ + code: "FORBIDDEN", + }); }); }); @@ -160,7 +161,7 @@ describe("dispatchChaiAction — delegated permissions", () => { await expect( runInContext({ ...member(["*"], "admin"), delegatedPermissions: ["pages:read"] }, () => - dispatchChaiAction("GATED_UPDATE", {}), + runChaiAction("GATED_UPDATE", {}), ), ).rejects.toMatchObject({ code: "FORBIDDEN" }); }); @@ -169,7 +170,7 @@ describe("dispatchChaiAction — delegated permissions", () => { registerGatedAction("GATED_READ", "pages:read"); const result = await runInContext({ ...member(["*"], "admin"), delegatedPermissions: ["pages:read"] }, () => - dispatchChaiAction("GATED_READ", {}), + runChaiAction("GATED_READ", {}), ); expect(result).toEqual({ ok: true }); @@ -180,7 +181,7 @@ describe("dispatchChaiAction — delegated permissions", () => { await expect( runInContext({ ...member(["*"], "admin"), delegatedScopes: ["pages:read"] }, () => - dispatchChaiAction("GATED_UPDATE", {}), + runChaiAction("GATED_UPDATE", {}), ), ).rejects.toMatchObject({ code: "FORBIDDEN" }); }); @@ -190,7 +191,7 @@ describe("dispatchChaiAction — delegated permissions", () => { const result = await runInContext( { ...member(["*", "custom:thing"], "admin"), delegatedPermissions: ["custom:thing"] }, - () => dispatchChaiAction("GATED_CUSTOM", {}), + () => runChaiAction("GATED_CUSTOM", {}), ); expect(result).toEqual({ ok: true }); @@ -212,7 +213,7 @@ describe("dispatchChaiAction — delegated permissions", () => { registerChaiPermissions("test:widgets", ["widgets:read", "widgets:update"]); try { const result = await runInContext({ ...member(["*"], "admin"), delegatedPermissions: ["widgets:*"] }, () => - dispatchChaiAction("GATED_WIDGET", {}), + runChaiAction("GATED_WIDGET", {}), ); expect(result).toEqual({ ok: true }); @@ -225,13 +226,13 @@ describe("dispatchChaiAction — delegated permissions", () => { registerGatedAction("GATED_READ", "pages:read"); await expect( - runInContext({ ...member(["*"], "admin"), delegatedPermissions: [] }, () => dispatchChaiAction("GATED_READ", {})), + runInContext({ ...member(["*"], "admin"), delegatedPermissions: [] }, () => runChaiAction("GATED_READ", {})), ).rejects.toMatchObject({ code: "FORBIDDEN" }); }); it("reports the clamped permission set to the builder UI", async () => { const result = (await runInContext({ ...member(["*"], "admin"), delegatedPermissions: ["pages:read"] }, () => - dispatchChaiAction("CHECK_USER_ACCESS", {}), + runChaiAction("CHECK_USER_ACCESS", {}), )) as { permissions: string[] }; expect(result.permissions).toEqual(["pages:read"]); @@ -285,7 +286,7 @@ describe("dispatchChaiAction — surface", () => { registerEchoAction("ECHO_SURFACE"); const result = await runInContext({ ...member(["*"], "admin"), surface: "settings" }, () => - dispatchChaiAction("ECHO_SURFACE", {}), + runChaiAction("ECHO_SURFACE", {}), ); expect(result).toEqual({ surface: "settings" }); @@ -294,7 +295,7 @@ describe("dispatchChaiAction — surface", () => { it("leaves the surface null when the resolver did not state one", async () => { registerEchoAction("ECHO_SURFACE"); - const result = await runInContext(member(["*"], "admin"), () => dispatchChaiAction("ECHO_SURFACE", {})); + const result = await runInContext(member(["*"], "admin"), () => runChaiAction("ECHO_SURFACE", {})); expect(result).toEqual({ surface: null }); }); @@ -333,10 +334,10 @@ describe("dispatchChaiAction — concurrent requests", () => { buildChaiBuilderConfig({ db: stubChaiDbConfig(), actions: { SLOW: action } }); const first = runInContext({ ...member(["pages:read"]), userId: "user-a" }, () => - dispatchChaiAction("SLOW", { input: "a", wait: true }), + runChaiAction("SLOW", { input: "a", wait: true }), ); const second = await runInContext({ ...member(["pages:read", "pages:unpublish"]), userId: "user-b" }, () => - dispatchChaiAction("SLOW", { input: "b" }), + runChaiAction("SLOW", { input: "b" }), ); release(); @@ -361,7 +362,7 @@ describe("dispatchChaiAction — concurrent requests", () => { action.requiredPermission = "pages:update"; buildChaiBuilderConfig({ db: stubChaiDbConfig(), actions: { PLAIN: action } }); - await expect(runInContext(member(["pages:read"]), () => dispatchChaiAction("PLAIN", {}))).rejects.toMatchObject({ + await expect(runInContext(member(["pages:read"]), () => runChaiAction("PLAIN", {}))).rejects.toMatchObject({ code: "FORBIDDEN", }); }); @@ -369,7 +370,7 @@ describe("dispatchChaiAction — concurrent requests", () => { // `features.ai: false` turns builder AI off: a model-calling action must not run even for // a caller who holds `ai:*` and sends the request directly. it("refuses AI actions when features.ai is off, and runs them by default", async () => { - class ModelCallAction extends ChaiBaseAIAction { + class ModelCallAction extends ChaiBaseAiAction { async execute() { return { ok: true } as const; } @@ -378,12 +379,12 @@ describe("dispatchChaiAction — concurrent requests", () => { action.requiredPermission = "ai:use"; buildChaiBuilderConfig({ db: stubChaiDbConfig(), actions: { MODEL_CALL: action } }); - await expect(runInContext(member(["ai:*"]), () => dispatchChaiAction("MODEL_CALL", {}))).resolves.toEqual({ + await expect(runInContext(member(["ai:*"]), () => runChaiAction("MODEL_CALL", {}))).resolves.toEqual({ ok: true, }); buildChaiBuilderConfig({ db: stubChaiDbConfig(), features: { ai: false }, actions: { MODEL_CALL: action } }); - await expect(runInContext(member(["ai:*"]), () => dispatchChaiAction("MODEL_CALL", {}))).rejects.toMatchObject({ + await expect(runInContext(member(["ai:*"]), () => runChaiAction("MODEL_CALL", {}))).rejects.toMatchObject({ code: "AI_DISABLED", status: 403, }); diff --git a/src/server/chai-actions/dispatch-action.ts b/src/server/chai-actions/dispatch-action.ts index 0e724870e..c6c5f67a1 100644 --- a/src/server/chai-actions/dispatch-action.ts +++ b/src/server/chai-actions/dispatch-action.ts @@ -1,9 +1,9 @@ import { getInitializedState, getInitializedStateWithUser } from "~/server/chai-builder/state"; import { resolveEffectivePermissions } from "~/server/rbac/effective-permissions"; -import { hasPermission } from "~/server/rbac/permissions"; +import { hasChaiPermission } from "~/server/rbac/permissions"; import { ActionError } from "./action-error"; import { getActionAuthPolicy } from "./action-policies"; -import { type ChaiActionResult, toActionError, toActionErrorPayload } from "./action-result"; +import { type ChaiActionResult, toChaiActionError, toChaiActionErrorPayload } from "./action-result"; import { getChaiActionInstance } from "./actions-registery"; import type { ChaiAction, ChaiActionContext, ChaiUserAccess } from "./chai-action-interface"; @@ -36,13 +36,13 @@ export function resolveRequiredPermissions( function enforcePermission(action: ChaiAction, data: unknown, context: ChaiActionContext): void { const granted = context.userAccess?.permissions ?? null; for (const required of resolveRequiredPermissions(action, data, context)) { - if (!hasPermission(granted, required)) { + if (!hasChaiPermission(granted, required)) { throw new ActionError(`Missing permission: ${required}`, "FORBIDDEN", 403); } } } -export async function dispatchChaiAction(name: string, data: unknown): Promise { +export async function runChaiAction(name: string, data: unknown): Promise { try { const action = getChaiActionInstance(name); if (!action) { @@ -90,15 +90,15 @@ export async function dispatchChaiAction(name: string, data: unknown): Promise(name: string, data: unknown): Promise> { try { - const result = await dispatchChaiAction(name, data); + const result = await runChaiAction(name, data); return { ok: true, data: result as T }; } catch (error) { - return { ok: false, error: toActionErrorPayload(error) }; + return { ok: false, error: toChaiActionErrorPayload(error) }; } } diff --git a/src/server/chai-actions/export.ts b/src/server/chai-actions/export.ts index 4e51b8069..445a6d724 100644 --- a/src/server/chai-actions/export.ts +++ b/src/server/chai-actions/export.ts @@ -1,9 +1,9 @@ import { ActionError } from "./action-error"; -import ChaiActionsRegistry, { BuilderActionsRegistry } from "./actions-registery"; +import ChaiActionsRegistry from "./actions-registery"; import { ChaiBaseAction } from "./base-action"; -import { ChaiBaseAIAction } from "./base-ai-action"; +import { ChaiBaseAiAction } from "./base-ai-action"; import type { ChaiAction, ChaiActionContext, ChaiUserAccess } from "./chai-action-interface"; -export { LANGUAGES } from "~/constants/LANGUAGES"; +export { CHAI_LANGUAGES } from "~/constants/LANGUAGES"; export { type ChaiActionErrorPayload, type ChaiActionFailure, @@ -13,18 +13,17 @@ export { isChaiActionSuccess, isStreamingChaiAction, STREAMING_CHAI_ACTIONS, - toActionError, - toActionErrorPayload, + toChaiActionError, + toChaiActionErrorPayload, } from "./action-result"; -export { dispatchChaiAction, tryChaiAction } from "./dispatch-action"; +export { runChaiAction, tryChaiAction } from "./dispatch-action"; export { getActionAuthPolicy, type ChaiActionAuthPolicy } from "./action-policies"; -export { initChaiActionHandler, initChaiBuilderActionHandler } from "./chai-builder-actions-handler"; +export { createChaiActionHandler } from "./chai-builder-actions-handler"; export { ActionError, - BuilderActionsRegistry, ChaiActionsRegistry, ChaiBaseAction, - ChaiBaseAIAction, + ChaiBaseAiAction, type ChaiAction, type ChaiActionContext, type ChaiUserAccess, diff --git a/src/server/chai-actions/lib.ts b/src/server/chai-actions/lib.ts index 28d8e8d98..5dc2b09e5 100644 --- a/src/server/chai-actions/lib.ts +++ b/src/server/chai-actions/lib.ts @@ -1,6 +1,6 @@ import { ImageModel, LanguageModel } from "ai"; import { getConfigAI, getConfigFeatures } from "~/server/defaults/config-registry"; -import type { ResolvedChaiAIGlobalConfig } from "~/types"; +import type { ResolvedChaiAiGlobalConfig } from "~/types"; export const apiError = (code: string, error: unknown) => { console.error(error); @@ -12,7 +12,7 @@ export function isAiCreditsEnabled(): boolean { return (getConfigFeatures() as any).aiCredits === true; } -export function getAiLogger(): ResolvedChaiAIGlobalConfig["logging"]["logger"] { +export function getAiLogger(): ResolvedChaiAiGlobalConfig["logging"]["logger"] { return getConfigAI().logging.logger; } diff --git a/src/server/chai-actions/pages/create-page.ts b/src/server/chai-actions/pages/create-page.ts index 8ae78ecfe..f23630c2d 100644 --- a/src/server/chai-actions/pages/create-page.ts +++ b/src/server/chai-actions/pages/create-page.ts @@ -9,7 +9,7 @@ import { runChaiActionHooks } from "~/server/plugin-api/action-hooks"; import { ChaiBlock } from "~/types/common"; import { ActionError } from "../action-error"; import { CHAI_PERMISSIONS } from "~/constants/PERMISSIONS"; -import { hasPermission } from "~/server/rbac/permissions"; +import { hasChaiPermission } from "~/server/rbac/permissions"; import { ChaiBaseAction } from "../base-action"; import { getDefaultGlobalJsonLdIds } from "./default-global-jsonlds"; import { demoteExistingHomepage, findExistingHomepage } from "./demote-existing-homepage"; @@ -138,10 +138,7 @@ export class CreatePageAction extends ChaiBaseAction - db.insert(schema.appPages).values(pageData).returning(), - ); + const { data: result, error } = await safeQuery(() => db.insert(schema.appPages).values(pageData).returning()); if (error) { throw new ActionError("Failed to create page", "ERROR_CREATING_PAGE", 500, error); diff --git a/src/server/chai-actions/pages/delete-page.test.ts b/src/server/chai-actions/pages/delete-page.test.ts index a30a33d66..eab4e5373 100644 --- a/src/server/chai-actions/pages/delete-page.test.ts +++ b/src/server/chai-actions/pages/delete-page.test.ts @@ -1,6 +1,6 @@ import { eq, inArray } from "drizzle-orm"; import { describe, expect, it } from "vitest"; -import { registerDb } from "~/db/core"; +import { registerChaiDb } from "~/db/core"; import { schema } from "~/server/chai-actions/db"; import { pageSlugTag, slugTag } from "~/server/chai-builder/public/page-routing-cache"; import { fake } from "~/tests/setup/fakers"; @@ -70,7 +70,14 @@ describe("DeletePageAction", () => { ); const variant = await seed( "appPages", - fake.appPages({ slug: "/en/primary", lang: "en", primaryPage: primary.id, online: true, currentEditor: null, deletedAt }), + fake.appPages({ + slug: "/en/primary", + lang: "en", + primaryPage: primary.id, + online: true, + currentEditor: null, + deletedAt, + }), ); await seed("appPagesOnline", fake.appPagesOnline({ id: primary.id, slug: "/primary" })); await seed( @@ -144,7 +151,7 @@ describe("DeletePageAction", () => { } : Reflect.get(target, prop), }); - registerDb({ drizzle: pgLike as never, schema: testSchema, dialect: "pg" }); + registerChaiDb({ drizzle: pgLike as never, schema: testSchema, dialect: "pg" }); sqlite.exec("CREATE TRIGGER fail_trash BEFORE UPDATE ON app_pages BEGIN SELECT RAISE(ABORT, 'boom'); END"); try { await expect(action(DeletePageAction).run({ id: page.id })).rejects.toThrow(); diff --git a/src/server/chai-actions/pages/delete-page.ts b/src/server/chai-actions/pages/delete-page.ts index c21b3e8fd..d457f477b 100644 --- a/src/server/chai-actions/pages/delete-page.ts +++ b/src/server/chai-actions/pages/delete-page.ts @@ -2,7 +2,7 @@ import { and, eq, inArray, isNotNull } from "drizzle-orm"; import { z } from "zod"; import { ActionError } from "~/server/chai-actions/action-error"; import { ChaiBaseAction } from "~/server/chai-actions/base-action"; -import { db, type DbInstance, getDbDialect, safeQuery, schema } from "~/server/chai-actions/db"; +import { db, type ChaiDbInstance, getChaiDbDialect, safeQuery, schema } from "~/server/chai-actions/db"; import { apiError } from "~/server/chai-actions/lib"; import type { PageTreeNode } from "~/server/chai-actions/utils/page-tree-builder"; import { PageTreeBuilder } from "~/server/chai-actions/utils/page-tree-builder"; @@ -155,7 +155,7 @@ export class DeletePageAction extends ChaiBaseAction { + const writes = async (q: ChaiDbInstance) => { if (permanent) { await q.delete(schema.libraryTemplates).where(inArray(schema.libraryTemplates.pageId, reverseIds)); } @@ -174,7 +174,7 @@ export class DeletePageAction extends ChaiBaseAction - getDbDialect() === "pg" ? db.transaction((tx) => writes(tx as unknown as DbInstance)) : writes(db), + getChaiDbDialect() === "pg" ? db.transaction((tx) => writes(tx as unknown as ChaiDbInstance)) : writes(db), ); if (error) throw apiError("DELETE_FAILED", error); @@ -306,7 +306,7 @@ export class DeletePageAction extends ChaiBaseAction { let removedRows: Array<{ id: string; slug: string | null; primaryPage: string | null }> = []; - const writes = async (q: DbInstance) => { + const writes = async (q: ChaiDbInstance) => { // Lock the still-trashed rows first (Postgres): a concurrent restore of the same // rows waits here, and one that already committed leaves nothing to lock. Only // the locked set is touched below, so a stale restore cannot delete a row that @@ -315,7 +315,7 @@ export class DeletePageAction extends ChaiBaseAction row.id); if (trashedIds.length === 0) return; @@ -337,7 +337,7 @@ export class DeletePageAction extends ChaiBaseAction - getDbDialect() === "pg" ? db.transaction((tx) => writes(tx as unknown as DbInstance)) : writes(db), + getChaiDbDialect() === "pg" ? db.transaction((tx) => writes(tx as unknown as ChaiDbInstance)) : writes(db), ); if (error) throw apiError("RESTORE_FAILED", error); diff --git a/src/server/chai-actions/pages/duplicate-page.ts b/src/server/chai-actions/pages/duplicate-page.ts index 4f11c3008..e01a45bd1 100644 --- a/src/server/chai-actions/pages/duplicate-page.ts +++ b/src/server/chai-actions/pages/duplicate-page.ts @@ -2,7 +2,7 @@ import { and, eq, inArray, isNull } from "drizzle-orm"; import { z } from "zod"; import { ActionError } from "~/server/chai-actions/action-error"; import { ChaiBaseAction } from "~/server/chai-actions/base-action"; -import { db, type DbInstance, getDbDialect, safeQuery, schema } from "~/server/chai-actions/db"; +import { db, type ChaiDbInstance, getChaiDbDialect, safeQuery, schema } from "~/server/chai-actions/db"; import { routingTagsForMutation } from "~/server/chai-builder/public/page-routing-cache"; /** @@ -113,7 +113,7 @@ export class DuplicatePageAction extends ChaiBaseAction { + const writes = async (q: ChaiDbInstance) => { const [primary] = await q .insert(schema.appPages) .values({ ...copyOf(originalPage), name: data.name, ...(data.slug && { slug: data.slug }) }) @@ -139,7 +139,7 @@ export class DuplicatePageAction extends ChaiBaseAction - getDbDialect() === "pg" ? db.transaction((tx) => writes(tx as unknown as DbInstance)) : writes(db), + getChaiDbDialect() === "pg" ? db.transaction((tx) => writes(tx as unknown as ChaiDbInstance)) : writes(db), ); if (error) { throw error instanceof ActionError diff --git a/src/server/chai-actions/pages/seo-permission.test.ts b/src/server/chai-actions/pages/seo-permission.test.ts index 06f311ce5..ab4c37fb0 100644 --- a/src/server/chai-actions/pages/seo-permission.test.ts +++ b/src/server/chai-actions/pages/seo-permission.test.ts @@ -6,7 +6,7 @@ import { runInContext } from "~/server/chai-builder/state"; import { resetActiveChaiBuilderConfigForTests } from "~/server/defaults/config-registry"; import { stubChaiDbConfig } from "~/tests/setup/stub-chai-db"; import type { ChaiActionContext } from "~/types"; -import { dispatchChaiAction } from "~/server/chai-actions/dispatch-action"; +import { runChaiAction } from "~/server/chai-actions/dispatch-action"; import { touchesSeoFields, updatePagePermission } from "./seo-permission"; const context = { appId: "test-app", action: "UPDATE_PAGE" } as ChaiActionContext; @@ -20,9 +20,7 @@ function requiredFor(actionName: string, data: unknown): string[] { /** Runs the action and returns the ActionError code it failed with, if any. */ async function failureCode(permissions: string[], data: unknown): Promise { try { - await runInContext({ appId: "test-app", userId: "user-1", permissions }, () => - dispatchChaiAction("UPDATE_PAGE", data), - ); + await runInContext({ appId: "test-app", userId: "user-1", permissions }, () => runChaiAction("UPDATE_PAGE", data)); return undefined; } catch (error) { return (error as { code?: string }).code; @@ -89,7 +87,7 @@ describe("registered page actions", () => { it("refuses an SEO write from a pages:update-only session", async () => { await expect( runInContext({ appId: "test-app", userId: "user-1", permissions: ["pages:update"] }, () => - dispatchChaiAction("UPDATE_PAGE", { id: "p1", seo: { title: "hijacked" } }), + runChaiAction("UPDATE_PAGE", { id: "p1", seo: { title: "hijacked" } }), ), ).rejects.toMatchObject({ code: "FORBIDDEN", message: "Missing permission: pages:edit_seo" }); }); diff --git a/src/server/chai-actions/pages/seo-permission.ts b/src/server/chai-actions/pages/seo-permission.ts index 7c9e29c45..b189004b3 100644 --- a/src/server/chai-actions/pages/seo-permission.ts +++ b/src/server/chai-actions/pages/seo-permission.ts @@ -1,5 +1,5 @@ import { CHAI_PERMISSIONS } from "~/constants/PERMISSIONS"; -import { permissionResolver } from "~/server/chai-actions/permission-keys"; +import { defineChaiPermissionResolver } from "~/server/chai-actions/permission-keys"; import type { ChaiPermissionResolver } from "~/types/chai-action"; /** @@ -32,7 +32,7 @@ export function seoAwarePermission( baseline: string, extract: (data: unknown) => unknown = (data) => data, ): ChaiPermissionResolver { - return permissionResolver([baseline, CHAI_PERMISSIONS["pages:edit_seo"]], (data: unknown) => + return defineChaiPermissionResolver([baseline, CHAI_PERMISSIONS["pages:edit_seo"]], (data: unknown) => touchesSeoFields(extract(data)) ? [baseline, CHAI_PERMISSIONS["pages:edit_seo"]] : baseline, ); } diff --git a/src/server/chai-actions/pages/update-page.ts b/src/server/chai-actions/pages/update-page.ts index 98eb090e5..8da044302 100644 --- a/src/server/chai-actions/pages/update-page.ts +++ b/src/server/chai-actions/pages/update-page.ts @@ -3,7 +3,7 @@ import { isEmpty, keys, pick } from "lodash-es"; import { z } from "zod"; import { CHAI_PERMISSIONS } from "~/constants/PERMISSIONS"; import { db, safeQuery, schema } from "~/server/chai-actions/db"; -import { hasPermission } from "~/server/rbac/permissions"; +import { hasChaiPermission } from "~/server/rbac/permissions"; import { resolveEditSource } from "~/server/chai-actions/utils/edit-source"; import { PageTreeBuilder } from "~/server/chai-actions/utils/page-tree-builder"; import { isFeatureEnabled } from "~/server/defaults/config-registry"; @@ -183,7 +183,7 @@ export class UpdatePageAction extends ChaiBaseAction { describe("declaredPermissionKeysOf", () => { it("returns the key for the static string form", () => { - expect(declaredPermissionKeysOf("pages:update")).toEqual(["pages:update"]); + expect(getDeclaredChaiPermissionKeys("pages:update")).toEqual(["pages:update"]); }); it("returns the list for the list form, dropping empty keys", () => { - expect(declaredPermissionKeysOf(["pages:update", "", "pages:edit_seo"])).toEqual([ + expect(getDeclaredChaiPermissionKeys(["pages:update", "", "pages:edit_seo"])).toEqual([ "pages:update", "pages:edit_seo", ]); }); it("returns [] for an ungated action", () => { - expect(declaredPermissionKeysOf(undefined)).toEqual([]); - expect(declaredPermissionKeysOf(null)).toEqual([]); + expect(getDeclaredChaiPermissionKeys(undefined)).toEqual([]); + expect(getDeclaredChaiPermissionKeys(null)).toEqual([]); }); it("returns every key a tagged resolver may require", () => { - const resolver = permissionResolver(["pages:update", "pages:edit_seo"], (data: any) => + const resolver = defineChaiPermissionResolver(["pages:update", "pages:edit_seo"], (data: any) => data?.seo ? ["pages:update", "pages:edit_seo"] : "pages:update", ); - expect(declaredPermissionKeysOf(resolver)).toEqual(["pages:update", "pages:edit_seo"]); + expect(getDeclaredChaiPermissionKeys(resolver)).toEqual(["pages:update", "pages:edit_seo"]); // The resolver still resolves per payload — the declared list is the superset. expect(resolver({ id: "p1" }, context)).toBe("pages:update"); expect(resolver({ id: "p1", seo: {} }, context)).toEqual(["pages:update", "pages:edit_seo"]); }); it("hands back a copy, so a caller cannot mutate the declaration", () => { - const resolver = permissionResolver(["pages:update"], () => "pages:update"); - declaredPermissionKeysOf(resolver).push("pages:publish"); + const resolver = defineChaiPermissionResolver(["pages:update"], () => "pages:update"); + getDeclaredChaiPermissionKeys(resolver).push("pages:publish"); expect(resolver.declaredPermissionKeys).toEqual(["pages:update"]); }); // The whole point: a resolver the static audits cannot see is refused loudly at // registration instead of silently reading as ungated (#3881 merge sim, B2). it("refuses an untagged function form", () => { - expect(() => declaredPermissionKeysOf(() => "pages:update")).toThrow(/permissionResolver/); + expect(() => getDeclaredChaiPermissionKeys(() => "pages:update")).toThrow(/permissionResolver/); }); }); describe("withActionPermission", () => { it("records the static key", () => { - const action = withActionPermission(new NoopAction(), "pages:read"); + const action = withChaiActionPermission(new NoopAction(), "pages:read"); expect(action.requiredPermission).toBe("pages:read"); expect(action.declaredPermissionKeys).toEqual(["pages:read"]); }); it("records every key of a tagged resolver", () => { - const action = withActionPermission( + const action = withChaiActionPermission( new NoopAction(), - permissionResolver(["pages:update", "pages:edit_seo"], (data: any) => + defineChaiPermissionResolver(["pages:update", "pages:edit_seo"], (data: any) => data?.seo ? ["pages:update", "pages:edit_seo"] : "pages:update", ), ); @@ -73,7 +73,7 @@ describe("withActionPermission", () => { }); it("throws on an untagged function rather than registering an opaque gate", () => { - expect(() => withActionPermission(new NoopAction(), () => "pages:update")).toThrow(/permissionResolver/); + expect(() => withChaiActionPermission(new NoopAction(), () => "pages:update")).toThrow(/permissionResolver/); }); }); diff --git a/src/server/chai-actions/permission-keys.ts b/src/server/chai-actions/permission-keys.ts index 761f46e3e..8dc113986 100644 --- a/src/server/chai-actions/permission-keys.ts +++ b/src/server/chai-actions/permission-keys.ts @@ -3,10 +3,10 @@ import type { ChaiActionContext, ChaiPermissionResolver, ChaiRequiredPermission /** * Tags a payload-aware permission resolver with every key it may ever return, so * static audits (MCP tool-permission superset, role-reach test, docs) that cannot - * call the resolver can still see what it may demand. `wp` / `withActionPermission` + * call the resolver can still see what it may demand. `wp` / `withChaiActionPermission` * refuse an untagged function — use this instead of assigning the property by hand. */ -export function permissionResolver( +export function defineChaiPermissionResolver( declaredPermissionKeys: string[], resolve: (data: T, context: ChaiActionContext) => string | string[] | null | undefined, ): ChaiPermissionResolver { @@ -20,7 +20,7 @@ export function permissionResolver( * it — the superset, not the requirement for a given call. An ungated action * returns `[]`. */ -export function declaredPermissionKeysOf(permission: ChaiRequiredPermission | undefined | null): string[] { +export function getDeclaredChaiPermissionKeys(permission: ChaiRequiredPermission | undefined | null): string[] { if (!permission) return []; if (typeof permission === "string") return [permission]; if (Array.isArray(permission)) return permission.filter(Boolean); diff --git a/src/server/chai-actions/streaming-error-handlers.ts b/src/server/chai-actions/streaming-error-handlers.ts index 63f8fce34..b96c88b57 100644 --- a/src/server/chai-actions/streaming-error-handlers.ts +++ b/src/server/chai-actions/streaming-error-handlers.ts @@ -3,7 +3,7 @@ * Uses the --MSG= format that the client understands * Wrapped in --START-- and --END-- markers required by client stream processor */ -export function formatStreamingError(error: { code: string; message: string; statusCode: number }): string { +export function formatChaiStreamingError(error: { code: string; message: string; statusCode: number }): string { return `--START--\n--MSG=${error.message}--\n--END--`; } @@ -11,7 +11,7 @@ export function formatStreamingError(error: { code: string; message: string; sta * Create a streaming error response * Converts an error into a ReadableStream response that the client can process */ -export function createStreamingErrorResponse(errorCode: string, errorMessage: string): Response { +export function createChaiStreamingErrorResponse(errorCode: string, errorMessage: string): Response { const encoder = new TextEncoder(); const stream = new ReadableStream({ @@ -35,6 +35,6 @@ export function createStreamingErrorResponse(errorCode: string, errorMessage: st /** * Check if streaming response is missing the text stream */ -export function isMissingTextStream(response: any): boolean { +export function isChaiMissingTextStream(response: any): boolean { return response?._streamingResponse && response?._streamResult && !response._streamResult?.textStream; } diff --git a/src/server/chai-actions/utils/format-context-for-prompt.ts b/src/server/chai-actions/utils/format-context-for-prompt.ts index 8d2916f32..d7b447308 100644 --- a/src/server/chai-actions/utils/format-context-for-prompt.ts +++ b/src/server/chai-actions/utils/format-context-for-prompt.ts @@ -1,11 +1,11 @@ -import { AIContext } from "~/types"; +import { ChaiAiContext } from "~/types"; import { stripDesignContextKeys } from "~/utils/design-context"; /** * Format context data for AI prompt * Converts context object (site/page) into formatted string */ -export function formatContextForPrompt(rawContext?: AIContext): string { +export function formatContextForPrompt(rawContext?: ChaiAiContext): string { // The design-system keys are objects and not part of these prompts (see ~/utils/design-context). const context = stripDesignContextKeys(rawContext); let contextInfo = ""; @@ -32,7 +32,7 @@ if (import.meta.vitest) { describe("formatContextForPrompt", () => { describe("With full context", () => { it("should format both site and page context", () => { - const context: AIContext = { + const context: ChaiAiContext = { site: { name: "My Website", description: "A great website", @@ -58,7 +58,7 @@ if (import.meta.vitest) { }); it("should format site context with multiple fields", () => { - const context: AIContext = { + const context: ChaiAiContext = { site: { name: "E-commerce Store", tagline: "Best products online", @@ -78,7 +78,7 @@ if (import.meta.vitest) { }); it("should format page context with multiple fields", () => { - const context: AIContext = { + const context: ChaiAiContext = { page: { title: "Product Details", slug: "product-123", @@ -100,7 +100,7 @@ if (import.meta.vitest) { describe("With partial context", () => { it("should handle only site context", () => { - const context: AIContext = { + const context: ChaiAiContext = { site: { name: "Blog Site", author: "John Doe", @@ -116,7 +116,7 @@ if (import.meta.vitest) { }); it("should handle only page context", () => { - const context: AIContext = { + const context: ChaiAiContext = { page: { title: "About Us", type: "static", @@ -132,7 +132,7 @@ if (import.meta.vitest) { }); it("should handle empty site object", () => { - const context: AIContext = { + const context: ChaiAiContext = { site: {}, page: { title: "Contact", @@ -147,7 +147,7 @@ if (import.meta.vitest) { }); it("should handle empty page object", () => { - const context: AIContext = { + const context: ChaiAiContext = { site: { name: "Company Site", }, @@ -170,7 +170,7 @@ if (import.meta.vitest) { }); it("should return empty string when context is empty object", () => { - const context: AIContext = {}; + const context: ChaiAiContext = {}; const result = formatContextForPrompt(context); @@ -178,7 +178,7 @@ if (import.meta.vitest) { }); it("should return empty string when both site and page are undefined", () => { - const context: AIContext = { + const context: ChaiAiContext = { site: undefined, page: undefined, }; @@ -191,7 +191,7 @@ if (import.meta.vitest) { describe("Formatting details", () => { it("should separate fields with commas", () => { - const context: AIContext = { + const context: ChaiAiContext = { site: { field1: "value1", field2: "value2", @@ -205,7 +205,7 @@ if (import.meta.vitest) { }); it("should start with newline for site context", () => { - const context: AIContext = { + const context: ChaiAiContext = { site: { name: "Test", }, @@ -217,7 +217,7 @@ if (import.meta.vitest) { }); it("should start with newline for page context when no site", () => { - const context: AIContext = { + const context: ChaiAiContext = { page: { title: "Test", }, @@ -229,7 +229,7 @@ if (import.meta.vitest) { }); it("should have both contexts on separate lines", () => { - const context: AIContext = { + const context: ChaiAiContext = { site: { name: "Site", }, @@ -249,7 +249,7 @@ if (import.meta.vitest) { describe("Special characters and values", () => { it("should handle special characters in values", () => { - const context: AIContext = { + const context: ChaiAiContext = { site: { name: "Site & Company", description: "We're #1!", @@ -263,7 +263,7 @@ if (import.meta.vitest) { }); it("should handle numeric values", () => { - const context: AIContext = { + const context: ChaiAiContext = { page: { views: 1000, rating: 4.5, @@ -277,7 +277,7 @@ if (import.meta.vitest) { }); it("should handle boolean values", () => { - const context: AIContext = { + const context: ChaiAiContext = { page: { published: true, featured: false, @@ -291,7 +291,7 @@ if (import.meta.vitest) { }); it("should handle null values", () => { - const context: AIContext = { + const context: ChaiAiContext = { site: { name: "Test", logo: null, @@ -305,7 +305,7 @@ if (import.meta.vitest) { }); it("should handle empty string values", () => { - const context: AIContext = { + const context: ChaiAiContext = { page: { title: "Page", subtitle: "", @@ -319,7 +319,7 @@ if (import.meta.vitest) { }); it("should handle URLs and special paths", () => { - const context: AIContext = { + const context: ChaiAiContext = { site: { url: "https://example.com/path?query=value", api: "https://api.example.com/v1", @@ -335,8 +335,8 @@ if (import.meta.vitest) { describe("Design-system keys", () => { it("formats a context carrying a design system exactly like one without it", () => { - const plain: AIContext = { site: { siteContext: "Bakery", tone: "Warm" }, page: { pageContext: "Menu" } }; - const withDesign: AIContext = { + const plain: ChaiAiContext = { site: { siteContext: "Bakery", tone: "Warm" }, page: { pageContext: "Menu" } }; + const withDesign: ChaiAiContext = { site: { ...plain.site, designSystem: { northStar: "Flour and fire", enabled: true } }, page: { ...plain.page, designBrief: { mode: "persuade", thesis: "Bread first" } }, }; @@ -347,7 +347,7 @@ if (import.meta.vitest) { describe("Real-world scenarios", () => { it("should format e-commerce site context", () => { - const context: AIContext = { + const context: ChaiAiContext = { site: { name: "TechStore", category: "Electronics", @@ -370,7 +370,7 @@ if (import.meta.vitest) { }); it("should format blog site context", () => { - const context: AIContext = { + const context: ChaiAiContext = { site: { name: "Tech Blog", author: "Jane Smith", @@ -392,7 +392,7 @@ if (import.meta.vitest) { }); it("should format landing page context", () => { - const context: AIContext = { + const context: ChaiAiContext = { site: { name: "SaaS Product", industry: "Marketing", diff --git a/src/server/chai-actions/utils/log-ai-request.ts b/src/server/chai-actions/utils/log-ai-request.ts index d1069491d..6401bd7c5 100644 --- a/src/server/chai-actions/utils/log-ai-request.ts +++ b/src/server/chai-actions/utils/log-ai-request.ts @@ -2,12 +2,12 @@ import { AI_MODELS } from "~/builder/pages/panels/ai-panel/models"; import { db, safeQuery, schema } from "~/server/chai-actions/db"; import { getChaiCreditProvider } from "~/server/plugin-api/credit-provider"; import { getConfigAI } from "~/server/defaults/config-registry"; -import type { LogAiRequestParams } from "~/types/server-config"; +import type { ChaiLogAiRequestArgs } from "~/types/server-config"; const getModelMultiplier = (id: string) => { return AI_MODELS.find((model) => model.id === id)?.multiplier || 1; }; -export type { LogAiRequestParams } from "~/types/server-config"; +export type { ChaiLogAiRequestArgs } from "~/types/server-config"; /** * OPTIMIZED: Log AI request with pre-computed credit status @@ -23,7 +23,7 @@ export async function logAiRequest({ response, prompt, error, -}: LogAiRequestParams) { +}: ChaiLogAiRequestArgs) { const clientId = getConfigAI().logging.clientId; const totalDuration = startTime > 0 ? Math.floor(new Date().getTime() - startTime) : 0; diff --git a/src/server/chai-actions/website/update-theme.ts b/src/server/chai-actions/website/update-theme.ts index cfaab1b78..3723a28e3 100644 --- a/src/server/chai-actions/website/update-theme.ts +++ b/src/server/chai-actions/website/update-theme.ts @@ -1,5 +1,5 @@ import { z } from "zod"; -import { getAllRegisteredFonts } from "~/registry"; +import { getRegisteredChaiFonts } from "~/registry"; import { getAppFields, updateAppFields } from "~/server/chai-actions/apps/app-store"; import { runChaiActionHooks } from "~/server/plugin-api/action-hooks"; import type { ChaiTheme } from "~/types/chaibuilder-editor-props"; @@ -42,7 +42,7 @@ export class UpdateThemeAction extends ChaiBaseAction font.family); + const fonts = getRegisteredChaiFonts().map((font) => font.family); const unknownFonts = [parsed.data.fontFamily?.heading, parsed.data.fontFamily?.body].filter( (font): font is string => !!font && !fonts.includes(font), ); diff --git a/src/server/chai-actions/website/website-permissions.test.ts b/src/server/chai-actions/website/website-permissions.test.ts index 442aa7812..6b190b9c4 100644 --- a/src/server/chai-actions/website/website-permissions.test.ts +++ b/src/server/chai-actions/website/website-permissions.test.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it } from "vitest"; import { buildChaiBuilderConfig } from "~/server/build-config"; import { getChaiAction } from "~/server/chai-actions/actions-registery"; -import { dispatchChaiAction, resolveRequiredPermissions } from "~/server/chai-actions/dispatch-action"; +import { runChaiAction, resolveRequiredPermissions } from "~/server/chai-actions/dispatch-action"; import { runInContext } from "~/server/chai-builder/state"; import { resetActiveChaiBuilderConfigForTests } from "~/server/defaults/config-registry"; import { DEFAULT_ROLE_MAPS } from "~/server/rbac/default-roles"; @@ -17,7 +17,7 @@ const requiredFor = (actionName: string, data: unknown): string[] => /** True when dispatching got past the permission check (the stub db fails it later, which is fine). */ async function passesPermissionCheck(permissions: string[], action: string, data: unknown): Promise { try { - await runInContext({ appId: "test-app", userId: "user-1", permissions }, () => dispatchChaiAction(action, data)); + await runInContext({ appId: "test-app", userId: "user-1", permissions }, () => runChaiAction(action, data)); return true; } catch (error) { return (error as { code?: string }).code !== "FORBIDDEN"; diff --git a/src/server/chai-actions/website/website-permissions.ts b/src/server/chai-actions/website/website-permissions.ts index 4f372438c..8d8b3a468 100644 --- a/src/server/chai-actions/website/website-permissions.ts +++ b/src/server/chai-actions/website/website-permissions.ts @@ -1,6 +1,6 @@ import { uniq } from "lodash-es"; import { CHAI_PERMISSIONS } from "~/constants/PERMISSIONS"; -import { permissionResolver } from "~/server/chai-actions/permission-keys"; +import { defineChaiPermissionResolver } from "~/server/chai-actions/permission-keys"; /** PUBLISH_CHANGES ids that are not pages: the site-wide theme and design tokens. */ const SITE_STYLE_IDS = new Set(["THEME", "DESIGN_TOKENS"]); @@ -10,7 +10,7 @@ const SITE_STYLE_IDS = new Set(["THEME", "DESIGN_TOKENS"]); * key for both — publishing the site's look is one right). A mixed request needs both. An empty * id list asks for nothing here; the action itself refuses it. */ -export const publishChangesPermission = permissionResolver( +export const publishChangesPermission = defineChaiPermissionResolver( [CHAI_PERMISSIONS["pages:publish"], CHAI_PERMISSIONS["theme:publish"]], (data: { ids?: unknown } | null | undefined) => { const ids = Array.isArray(data?.ids) ? (data.ids as unknown[]) : []; @@ -28,7 +28,7 @@ export const publishChangesPermission = permissionResolver( * carries the theme, `design_tokens:edit` when it carries the design tokens — the keys their * panels are gated on — and `app:update` for a payload that carries neither. */ -export const updateWebsiteFieldsPermission = permissionResolver( +export const updateWebsiteFieldsPermission = defineChaiPermissionResolver( [CHAI_PERMISSIONS["theme:edit"], CHAI_PERMISSIONS["design_tokens:edit"], CHAI_PERMISSIONS["app:update"]], (data: { settings?: Record } | null | undefined) => { const settings = data?.settings ?? {}; diff --git a/src/server/chai-builder/authenticated.ts b/src/server/chai-builder/authenticated.ts index 9f013cc53..a1f6c4907 100644 --- a/src/server/chai-builder/authenticated.ts +++ b/src/server/chai-builder/authenticated.ts @@ -1,5 +1,5 @@ -import type { GetAssetInput, SearchImagesInput, UpdateAssetInput } from "~/types/media"; -import { dispatchChaiAction } from "~/server/chai-actions/dispatch-action"; +import type { ChaiGetAssetArgs, ChaiSearchImagesArgs, ChaiUpdateAssetArgs } from "~/types/media"; +import { runChaiAction } from "~/server/chai-actions/dispatch-action"; import type { DeleteLibraryItemActionData, GetLibraryItemActionData, @@ -14,38 +14,33 @@ import { TakeOfflineActionData } from "~/server/chai-actions/pages/take-offline" import { UpdatePageActionData } from "~/server/chai-actions/pages/update-page"; import { UpdatePageMetadataActionData } from "~/server/chai-actions/pages/update-page-metadata"; import type { - DeletePageRevisionActionData, - GetPageRevisionsActionData, - GetRevisionPageActionData, - RestorePageActionData, + ChaiDeletePageRevisionArgs, + ChaiGetPageRevisionsArgs, + ChaiGetRevisionPageArgs, + ChaiRestorePageArgs, } from "~/types/revisions"; -import type { - CreateRoleActionData, - DeleteRoleActionData, - GetRoleActionData, - UpdateRoleActionData, -} from "~/types/roles"; +import type { ChaiCreateRoleArgs, ChaiDeleteRoleArgs, ChaiGetRoleArgs, ChaiUpdateRoleArgs } from "~/types/roles"; import { GetTemplatesByTypeActionData } from "~/server/chai-actions/templates/get-templates-by-type"; import { MarkAsTemplateActionData } from "~/server/chai-actions/templates/mark-as-template"; import { UnmarkAsTemplateActionData } from "~/server/chai-actions/templates/unmark-as-template"; import type { - DeletePermanentlyData, - GetTrashedItemsData, - PermanentlyDeleteByDaysData, - RestoreTrashedItemData, - TrashEntityData, + ChaiDeleteTrashPermanentlyArgs, + ChaiGetTrashedItemsArgs, + ChaiDeleteTrashByDaysArgs, + ChaiRestoreTrashedItemArgs, + ChaiTrashEntityArgs, } from "~/types/trash"; export const runRegisteredAction = async (actionName: string, data: T): Promise => { - return dispatchChaiAction(actionName, data); + return runChaiAction(actionName, data); }; // Assets -export const getAsset = (data: GetAssetInput) => runRegisteredAction("GET_ASSET", data); +export const getAsset = (data: ChaiGetAssetArgs) => runRegisteredAction("GET_ASSET", data); export const getAssets = (data: { search?: string; page?: number; limit?: number } = {}) => runRegisteredAction("GET_ASSETS", data); -export const searchImages = (data: SearchImagesInput) => runRegisteredAction("SEARCH_IMAGES", data); -export const updateAsset = (data: UpdateAssetInput) => runRegisteredAction("UPDATE_ASSET", data); +export const searchImages = (data: ChaiSearchImagesArgs) => runRegisteredAction("SEARCH_IMAGES", data); +export const updateAsset = (data: ChaiUpdateAssetArgs) => runRegisteredAction("UPDATE_ASSET", data); // Pages export const createPage = (data: CreatePageActionData) => runRegisteredAction("CREATE_PAGE", data); @@ -76,24 +71,25 @@ export const markAsTemplate = (data: MarkAsTemplateActionData) => runRegisteredA export const unmarkAsTemplate = (data: UnmarkAsTemplateActionData) => runRegisteredAction("UNMARK_AS_TEMPLATE", data); // Trash -export const deleteTrashedItemPermanently = (data: DeletePermanentlyData) => +export const deleteTrashedItemPermanently = (data: ChaiDeleteTrashPermanentlyArgs) => runRegisteredAction("DELETE_PERMANENTLY", data); -export const getTrashedItems = (data: GetTrashedItemsData) => runRegisteredAction("GET_TRASHED_ITEMS", data); -export const permanentlyDeleteByDays = (data: PermanentlyDeleteByDaysData) => +export const getTrashedItems = (data: ChaiGetTrashedItemsArgs) => runRegisteredAction("GET_TRASHED_ITEMS", data); +export const permanentlyDeleteByDays = (data: ChaiDeleteTrashByDaysArgs) => runRegisteredAction("PERMANENTLY_DELETE_BY_DAYS", data); -export const restoreTrashedItem = (data: RestoreTrashedItemData) => runRegisteredAction("RESTORE_TRASHED_ITEM", data); -export const trashEntity = (data: TrashEntityData) => runRegisteredAction("TRASH_ENTITY", data); +export const restoreTrashedItem = (data: ChaiRestoreTrashedItemArgs) => + runRegisteredAction("RESTORE_TRASHED_ITEM", data); +export const trashEntity = (data: ChaiTrashEntityArgs) => runRegisteredAction("TRASH_ENTITY", data); // Roles export const getRoles = () => runRegisteredAction("GET_ROLES", {}); -export const getRole = (data: GetRoleActionData) => runRegisteredAction("GET_ROLE", data); -export const createRole = (data: CreateRoleActionData) => runRegisteredAction("CREATE_ROLE", data); -export const updateRole = (data: UpdateRoleActionData) => runRegisteredAction("UPDATE_ROLE", data); -export const deleteRole = (data: DeleteRoleActionData) => runRegisteredAction("DELETE_ROLE", data); +export const getRole = (data: ChaiGetRoleArgs) => runRegisteredAction("GET_ROLE", data); +export const createRole = (data: ChaiCreateRoleArgs) => runRegisteredAction("CREATE_ROLE", data); +export const updateRole = (data: ChaiUpdateRoleArgs) => runRegisteredAction("UPDATE_ROLE", data); +export const deleteRole = (data: ChaiDeleteRoleArgs) => runRegisteredAction("DELETE_ROLE", data); // Revisions -export const deletePageRevision = (data: DeletePageRevisionActionData) => +export const deletePageRevision = (data: ChaiDeletePageRevisionArgs) => runRegisteredAction("DELETE_PAGE_REVISION", data); -export const getPageRevisions = (data: GetPageRevisionsActionData) => runRegisteredAction("GET_PAGE_REVISIONS", data); -export const getRevisionPage = (data: GetRevisionPageActionData) => runRegisteredAction("GET_REVISION_PAGE", data); -export const restorePage = (data: RestorePageActionData) => runRegisteredAction("RESTORE_PAGE_REVISION", data); +export const getPageRevisions = (data: ChaiGetPageRevisionsArgs) => runRegisteredAction("GET_PAGE_REVISIONS", data); +export const getRevisionPage = (data: ChaiGetRevisionPageArgs) => runRegisteredAction("GET_REVISION_PAGE", data); +export const restorePage = (data: ChaiRestorePageArgs) => runRegisteredAction("RESTORE_PAGE_REVISION", data); diff --git a/src/server/chai-builder/handle-http-action.ts b/src/server/chai-builder/handle-http-action.ts index 3909da44e..2cc01fc5f 100644 --- a/src/server/chai-builder/handle-http-action.ts +++ b/src/server/chai-builder/handle-http-action.ts @@ -1,19 +1,19 @@ import { isStreamingChaiAction, - toActionErrorPayload, + toChaiActionErrorPayload, type ChaiActionFailure, type ChaiActionSuccess, } from "~/server/chai-actions/action-result"; -import { dispatchChaiAction } from "~/server/chai-actions/dispatch-action"; +import { runChaiAction } from "~/server/chai-actions/dispatch-action"; import { - createStreamingErrorResponse, - formatStreamingError, - isMissingTextStream, + createChaiStreamingErrorResponse, + formatChaiStreamingError, + isChaiMissingTextStream, } from "~/server/chai-actions/streaming-error-handlers"; import { applyChaiActionCacheEffects, DEFAULT_CATCH_ALL_ROUTE } from "~/server/chai-builder/action-cache-effects"; import { runChaiResponseDecorators } from "~/server/plugin-api/response-decorator"; -export type HttpChaiActionBody = { +export type ChaiHttpActionBody = { action: string; data?: unknown; }; @@ -34,15 +34,15 @@ function withExtras(body: T, extras: Record): } function httpActionErrorResponse(action: string, error: unknown, extras: Record): Response { - const payload = toActionErrorPayload(error); + const payload = toChaiActionErrorPayload(error); if (isStreamingChaiAction(action)) { - const errorMessage = formatStreamingError({ + const errorMessage = formatChaiStreamingError({ code: payload.code, message: payload.message, statusCode: payload.status, }); - return createStreamingErrorResponse(payload.code, errorMessage); + return createChaiStreamingErrorResponse(payload.code, errorMessage); } const body: ChaiActionFailure = { ok: false, error: payload }; @@ -55,7 +55,7 @@ function httpActionSuccessResponse(data: unknown, extras: Record { const { catchAllRoute = DEFAULT_CATCH_ALL_ROUTE } = options; @@ -65,7 +65,7 @@ export async function handleHttpAction( // overlaps with the action instead of adding to it. Never gates the action. const extrasPromise = runChaiResponseDecorators().catch(() => ({}) as Record); try { - const result = await dispatchChaiAction(action, data); + const result = await runChaiAction(action, data); if (result && typeof result === "object" && "_streamingResponse" in result && "_streamResult" in result) { const streamingResult = result as { @@ -91,7 +91,7 @@ export async function handleHttpAction( return streamingResult._streamResult.dataStream; } - if (isMissingTextStream(streamingResult)) { + if (isChaiMissingTextStream(streamingResult)) { return httpActionErrorResponse( action, { diff --git a/src/server/chai-builder/internal/init-by-hostname.ts b/src/server/chai-builder/internal/init-by-hostname.ts index 6018e86b9..d9843f877 100644 --- a/src/server/chai-builder/internal/init-by-hostname.ts +++ b/src/server/chai-builder/internal/init-by-hostname.ts @@ -1,9 +1,9 @@ -import { resolveAppIdByHostname } from "../public/resolve-app-id-by-hostname"; +import { resolveChaiAppIdByHostname } from "../public/resolve-app-id-by-hostname"; import { initState, loadSiteSettings, setDraftMode } from "./init"; export const initByHostname = async (hostname: string, draftMode: boolean): Promise<{ id: string }> => { setDraftMode(draftMode); - const appId = await resolveAppIdByHostname(hostname, { draft: draftMode }); + const appId = await resolveChaiAppIdByHostname(hostname, { draft: draftMode }); initState(appId, draftMode); await loadSiteSettings(draftMode); diff --git a/src/server/chai-builder/parse-multipart-action.test.ts b/src/server/chai-builder/parse-multipart-action.test.ts index 1104a2093..d2e2a0dc7 100644 --- a/src/server/chai-builder/parse-multipart-action.test.ts +++ b/src/server/chai-builder/parse-multipart-action.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import { ActionError } from "~/server/chai-actions/action-error"; -import { isMultipartActionRequest, parseMultipartActionBody } from "./parse-multipart-action"; +import { isChaiMultipartActionRequest, parseChaiMultipartActionBody } from "./parse-multipart-action"; const multipartRequest = (form: FormData) => new Request("https://example.com/admin/api", { method: "POST", body: form }); @@ -27,7 +27,7 @@ const createAssetForm = ({ describe("isMultipartActionRequest", () => { it("detects a multipart body", () => { - expect(isMultipartActionRequest(multipartRequest(createAssetForm()))).toBe(true); + expect(isChaiMultipartActionRequest(multipartRequest(createAssetForm()))).toBe(true); }); it("rejects a JSON body", () => { @@ -36,18 +36,18 @@ describe("isMultipartActionRequest", () => { headers: { "Content-Type": "application/json" }, body: "{}", }); - expect(isMultipartActionRequest(req)).toBe(false); + expect(isChaiMultipartActionRequest(req)).toBe(false); }); it("rejects a request with no content type", () => { - expect(isMultipartActionRequest(new Request("https://example.com/admin/api"))).toBe(false); + expect(isChaiMultipartActionRequest(new Request("https://example.com/admin/api"))).toBe(false); }); }); describe("parseMultipartActionBody", () => { it("returns the same {action, data} shape the JSON transport produces", async () => { const form = createAssetForm({ meta: JSON.stringify({ name: "photo.png", optimize: true }) }); - const body = await parseMultipartActionBody(multipartRequest(form)); + const body = await parseChaiMultipartActionBody(multipartRequest(form)); expect(body.action).toBe("CREATE_ASSET"); const data = body.data as Record; @@ -59,30 +59,30 @@ describe("parseMultipartActionBody", () => { }); it("falls back to the uploaded file's own name when meta has none", async () => { - const body = await parseMultipartActionBody(multipartRequest(createAssetForm())); + const body = await parseChaiMultipartActionBody(multipartRequest(createAssetForm())); expect((body.data as Record).name).toBe("photo.png"); }); it("prefers the meta name over the file name", async () => { const form = createAssetForm({ meta: JSON.stringify({ name: "renamed.png" }) }); - const body = await parseMultipartActionBody(multipartRequest(form)); + const body = await parseChaiMultipartActionBody(multipartRequest(form)); expect((body.data as Record).name).toBe("renamed.png"); }); it("ignores an empty meta name in favour of the file name", async () => { const form = createAssetForm({ meta: JSON.stringify({ name: "" }) }); - const body = await parseMultipartActionBody(multipartRequest(form)); + const body = await parseChaiMultipartActionBody(multipartRequest(form)); expect((body.data as Record).name).toBe("photo.png"); }); it("works without a meta part at all", async () => { - const body = await parseMultipartActionBody(multipartRequest(createAssetForm({ meta: null }))); + const body = await parseChaiMultipartActionBody(multipartRequest(createAssetForm({ meta: null }))); expect((body.data as Record).name).toBe("photo.png"); }); it("leaves mimeType undefined when the client reported no usable type", async () => { const form = createAssetForm({ file: new File(["bytes"], "photo.png") }); - const body = await parseMultipartActionBody(multipartRequest(form)); + const body = await parseChaiMultipartActionBody(multipartRequest(form)); // A typeless part arrives as application/octet-stream, which says nothing // about the format and must not be cross-checked against the extension. expect((body.data as Record).mimeType).toBeUndefined(); @@ -92,43 +92,43 @@ describe("parseMultipartActionBody", () => { const form = createAssetForm({ file: new File(["bytes"], "photo.png", { type: "application/octet-stream" }), }); - const body = await parseMultipartActionBody(multipartRequest(form)); + const body = await parseChaiMultipartActionBody(multipartRequest(form)); expect((body.data as Record).mimeType).toBeUndefined(); }); it("rejects a request with no action", async () => { - await expect(parseMultipartActionBody(multipartRequest(createAssetForm({ action: null })))).rejects.toThrow( + await expect(parseChaiMultipartActionBody(multipartRequest(createAssetForm({ action: null })))).rejects.toThrow( /Missing action/, ); }); it("rejects a request with no file", async () => { - await expect(parseMultipartActionBody(multipartRequest(createAssetForm({ file: null })))).rejects.toThrow( + await expect(parseChaiMultipartActionBody(multipartRequest(createAssetForm({ file: null })))).rejects.toThrow( /Missing file/, ); }); it("rejects a file part sent as a plain string", async () => { await expect( - parseMultipartActionBody(multipartRequest(createAssetForm({ file: "not-a-file" }))), + parseChaiMultipartActionBody(multipartRequest(createAssetForm({ file: "not-a-file" }))), ).rejects.toThrow(/Missing file/); }); it("rejects unparseable meta", async () => { await expect( - parseMultipartActionBody(multipartRequest(createAssetForm({ meta: "{not json" }))), + parseChaiMultipartActionBody(multipartRequest(createAssetForm({ meta: "{not json" }))), ).rejects.toThrow(/Invalid meta/); }); it("rejects meta that is not a JSON object", async () => { - await expect( - parseMultipartActionBody(multipartRequest(createAssetForm({ meta: '["a"]' }))), - ).rejects.toThrow(/Invalid meta/); + await expect(parseChaiMultipartActionBody(multipartRequest(createAssetForm({ meta: '["a"]' })))).rejects.toThrow( + /Invalid meta/, + ); }); it("reports a 400 ActionError so the route answers with the failure envelope", async () => { try { - await parseMultipartActionBody(multipartRequest(createAssetForm({ action: null }))); + await parseChaiMultipartActionBody(multipartRequest(createAssetForm({ action: null }))); throw new Error("expected parseMultipartActionBody to throw"); } catch (error) { expect(error).toBeInstanceOf(ActionError); @@ -139,7 +139,7 @@ describe("parseMultipartActionBody", () => { it("does not let a meta field overwrite the parsed file bytes", async () => { const form = createAssetForm({ meta: JSON.stringify({ file: "malicious-base64", name: "photo.png" }) }); - const body = await parseMultipartActionBody(multipartRequest(form)); + const body = await parseChaiMultipartActionBody(multipartRequest(form)); expect((body.data as Record).file).toBeInstanceOf(Uint8Array); }); }); diff --git a/src/server/chai-builder/parse-multipart-action.ts b/src/server/chai-builder/parse-multipart-action.ts index 31bb5a059..a384a46da 100644 --- a/src/server/chai-builder/parse-multipart-action.ts +++ b/src/server/chai-builder/parse-multipart-action.ts @@ -13,9 +13,9 @@ * - `file` — the file itself */ import { ActionError } from "~/server/chai-actions/action-error"; -import type { HttpChaiActionBody } from "~/server/chai-builder/handle-http-action"; +import type { ChaiHttpActionBody } from "~/server/chai-builder/handle-http-action"; -export const isMultipartActionRequest = (req: Request): boolean => +export const isChaiMultipartActionRequest = (req: Request): boolean => (req.headers.get("content-type") ?? "").toLowerCase().startsWith("multipart/form-data"); /** @@ -23,7 +23,7 @@ export const isMultipartActionRequest = (req: Request): boolean => * `data.file` comes out as bytes, and `data.mimeType` carries what the browser * reported — a hint the action layer validates rather than trusts. */ -export const parseMultipartActionBody = async (req: Request): Promise => { +export const parseChaiMultipartActionBody = async (req: Request): Promise => { let form: FormData; try { form = await req.formData(); diff --git a/src/server/chai-builder/public/get-blocks-styles.ts b/src/server/chai-builder/public/get-blocks-styles.ts index 60d18950a..681c276ec 100644 --- a/src/server/chai-builder/public/get-blocks-styles.ts +++ b/src/server/chai-builder/public/get-blocks-styles.ts @@ -1,7 +1,7 @@ import twForms from "@tailwindcss/forms"; import twTypography from "@tailwindcss/typography"; import type { ChaiBlock } from "~/types"; -import { getChaiBuilderTheme } from "~/utils"; +import { getChaiTailwindTheme } from "~/utils"; // Compat entry (not ~/tailwind): shared compile path used by the server styles pipeline for // v4 consumers of the published package. import { compileTailwindCss } from "~/utils/tailwind-css-compat"; @@ -11,7 +11,7 @@ const getPageTailwindConfig = () => ({ darkMode: "class", theme: { extend: { - ...getChaiBuilderTheme(), + ...getChaiTailwindTheme(), keyframes: { "accordion-down": { from: { diff --git a/src/server/chai-builder/public/get-site-settings.ts b/src/server/chai-builder/public/get-site-settings.ts index 5cc929957..6c2833454 100644 --- a/src/server/chai-builder/public/get-site-settings.ts +++ b/src/server/chai-builder/public/get-site-settings.ts @@ -1,11 +1,11 @@ import { getAppRow } from "~/server/chai-actions/apps/app-store"; import { getConfigSiteSettingsTransform } from "~/server/defaults/config-registry"; -import type { ChaiWebsiteSetting } from "~/types"; +import type { ChaiSiteSettings } from "~/types"; import { getInitializedState } from "../state"; import { withChaiCache } from "./cache-utils"; // Stable function reference for caching - defined once at module level -async function fetchSiteSettings(appId: string, draftMode: boolean): Promise { +async function fetchSiteSettings(appId: string, draftMode: boolean): Promise { const { data: settings, error } = await getAppRow(appId, { draft: draftMode }); if (error || !settings) { @@ -19,10 +19,10 @@ async function fetchSiteSettings(appId: string, draftMode: boolean): Promise => { +export const getSiteSettings = async (): Promise => { const state = getInitializedState(); return await withChaiCache( fetchSiteSettings, diff --git a/src/server/chai-builder/public/resolve-app-id-by-hostname.test.ts b/src/server/chai-builder/public/resolve-app-id-by-hostname.test.ts index ca777971e..f874cef5e 100644 --- a/src/server/chai-builder/public/resolve-app-id-by-hostname.test.ts +++ b/src/server/chai-builder/public/resolve-app-id-by-hostname.test.ts @@ -9,7 +9,7 @@ import { installMemoryPersistentCache } from "~/tests/setup/persistent-cache"; import { withRequestContext } from "~/tests/setup/request-context"; import { TEST_APP_ID } from "~/tests/setup/test-app"; import { getSiteDomains } from "./get-site-domains"; -import { resolveAppIdByHostname } from "./resolve-app-id-by-hostname"; +import { resolveChaiAppIdByHostname } from "./resolve-app-id-by-hostname"; // Where domains are stored belongs to whichever plugin registers the site domain resolver. These // tests install a Map-backed one, so they hold in every edition. @@ -44,8 +44,8 @@ describe("resolveAppIdByHostname", () => { useResolver(memoryResolver); const cache = installMemoryPersistentCache(); - await expect(resolveAppIdByHostname("www.example.com")).resolves.toBe(TEST_APP_ID); - await expect(resolveAppIdByHostname("www.example.com")).resolves.toBe(TEST_APP_ID); + await expect(resolveChaiAppIdByHostname("www.example.com")).resolves.toBe(TEST_APP_ID); + await expect(resolveChaiAppIdByHostname("www.example.com")).resolves.toBe(TEST_APP_ID); expect(lookups).toEqual(["example.com"]); expect(cache.wraps[0]).toEqual({ keyParts: ["hostname", "example.com"], tags: ["hostname-example.com"] }); }); @@ -53,14 +53,14 @@ describe("resolveAppIdByHostname", () => { it("supports the draft (request-cache) path", async () => { useResolver(memoryResolver); - await expect(resolveAppIdByHostname("my-site.chaibuilder.xyz", { draft: true })).resolves.toBe(TEST_APP_ID); + await expect(resolveChaiAppIdByHostname("my-site.chaibuilder.xyz", { draft: true })).resolves.toBe(TEST_APP_ID); }); it("throws when no site matches the hostname", async () => { useResolver(memoryResolver); installMemoryPersistentCache(); - await expect(resolveAppIdByHostname("unknown.example.com")).rejects.toThrow( + await expect(resolveChaiAppIdByHostname("unknown.example.com")).rejects.toThrow( "No site found for hostname: unknown.example.com", ); }); @@ -70,7 +70,7 @@ describe("resolveAppIdByHostname", () => { useResolver({ ...memoryResolver, appIdByHostname: () => Promise.reject(failure) }); installMemoryPersistentCache(); - await expect(resolveAppIdByHostname("example.com")).rejects.toMatchObject({ + await expect(resolveChaiAppIdByHostname("example.com")).rejects.toMatchObject({ message: "No site found for hostname: example.com", cause: failure, }); @@ -80,7 +80,7 @@ describe("resolveAppIdByHostname", () => { useResolver(undefined); installMemoryPersistentCache(); - await expect(resolveAppIdByHostname("example.com")).rejects.toThrow("No site found for hostname: example.com"); + await expect(resolveChaiAppIdByHostname("example.com")).rejects.toThrow("No site found for hostname: example.com"); }); }); diff --git a/src/server/chai-builder/public/resolve-app-id-by-hostname.ts b/src/server/chai-builder/public/resolve-app-id-by-hostname.ts index 0df885349..2e589cd84 100644 --- a/src/server/chai-builder/public/resolve-app-id-by-hostname.ts +++ b/src/server/chai-builder/public/resolve-app-id-by-hostname.ts @@ -30,7 +30,7 @@ export type ResolveAppIdByHostnameOptions = { * Hostnames are normalized via {@link getCleanHostname} before lookup, then handed to the site * domain resolver a plugin registered (`registerChaiSiteDomainResolver`). */ -export async function resolveAppIdByHostname( +export async function resolveChaiAppIdByHostname( hostname: string, options?: ResolveAppIdByHostnameOptions, ): Promise { diff --git a/src/server/chai-builder/public/warm-published-pages-cache.ts b/src/server/chai-builder/public/warm-published-pages-cache.ts index a82c3763c..57170ae51 100644 --- a/src/server/chai-builder/public/warm-published-pages-cache.ts +++ b/src/server/chai-builder/public/warm-published-pages-cache.ts @@ -5,7 +5,7 @@ import { CHAI_BUILT_IN_DESIGN_TOKENS } from "~/constants/BUILTIN_TOKENS"; import { db, safeQuery, schema } from "~/server/chai-actions/db"; import { runInContext } from "~/server/chai-builder/state"; import type { ChaiDesignTokens } from "~/types"; -import { applyDesignTokens } from "~/utils"; +import { applyChaiDesignTokens } from "~/utils"; import { getFullPage } from "./get-full-page"; import { getPageStylesCached } from "./get-page-styles"; import { getSiteSettings } from "./get-site-settings"; @@ -91,7 +91,7 @@ async function warmPageStylesForPageId(pageId: string): Promise { ...CHAI_BUILT_IN_DESIGN_TOKENS, ...(get(siteSettings, "designTokens", {}) as ChaiDesignTokens), }; - const pageBlocks = applyDesignTokens(page.blocks ?? [], designTokens); + const pageBlocks = applyChaiDesignTokens(page.blocks ?? [], designTokens); await getPageStylesCached(pageId, pageBlocks); return true; diff --git a/src/server/chai-context-resolver.ts b/src/server/chai-context-resolver.ts index bda20c9d9..e343680fe 100644 --- a/src/server/chai-context-resolver.ts +++ b/src/server/chai-context-resolver.ts @@ -13,19 +13,15 @@ import type { ChaiContextResolver, ChaiRequestContext } from "~/types/chaibuilde const _g = globalThis as typeof globalThis & { __chaiContextResolver?: ChaiContextResolver }; /** - * Registers the process-wide context resolver. The last call wins. - * - * @deprecated Prefer `createChaiBuilder(config, { context })`, which registers the resolver - * and hands back a `getChaiBuilder` bound to the config — so entry points import that instead - * of relying on a side-effect import that is easy to forget. This function keeps working and - * is what the factory calls internally. + * Registers the process-wide context resolver. The last call wins. Internal: hosts pass + * `context` to `createChaiBuilder(config, { context })`, which calls this. */ -export function setChaiContextResolver(resolver: ChaiContextResolver): void { +export function registerChaiContextResolver(resolver: ChaiContextResolver): void { _g.__chaiContextResolver = resolver; } /** Returns the registered resolver, or `null` if none has been set. */ -export function getChaiContextResolver(): ChaiContextResolver | null { +export function getRegisteredChaiContextResolver(): ChaiContextResolver | null { return _g.__chaiContextResolver ?? null; } @@ -38,7 +34,7 @@ export function resetChaiContextResolverForTests(): void { * Static, Next-free context used when no resolver is registered (e.g. scripts, * seeding). Reads identity from env only — never touches `next/headers`. */ -export function staticDefaultChaiContext(overrides?: Partial): ChaiRequestContext { +export function createStaticChaiContext(overrides?: Partial): ChaiRequestContext { return { appId: process.env.CHAIBUILDER_API_KEY ?? process.env.CHAIBUILDER_APP_KEY ?? "", siteUrl: process.env.SITE_URL ?? null, diff --git a/src/server/create-chai-builder.test.ts b/src/server/create-chai-builder.test.ts index 44adbcf68..b7a33dadb 100644 --- a/src/server/create-chai-builder.test.ts +++ b/src/server/create-chai-builder.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { buildChaiBuilderConfig } from "~/server/build-config"; -import { getChaiContextResolver, resetChaiContextResolverForTests } from "~/server/chai-context-resolver"; +import { getRegisteredChaiContextResolver, resetChaiContextResolverForTests } from "~/server/chai-context-resolver"; import { createChaiBuilder } from "~/server/create-chai-builder"; import { resetActiveChaiBuilderConfigForTests } from "~/server/defaults/config-registry"; import { resetChaiBuilderCoreForTests } from "~/server/get-chaibuilder"; @@ -37,7 +37,7 @@ describe("createChaiBuilder", () => { }); expect(boundConfig).toBe(config); - expect(getChaiContextResolver()).not.toBeNull(); + expect(getRegisteredChaiContextResolver()).not.toBeNull(); const cb = await getChaiBuilder(); expect(cb.config).toBe(config); @@ -70,7 +70,7 @@ describe("createChaiBuilder", () => { it("falls back to the static env context when no resolver is supplied", async () => { const { getChaiBuilder } = createChaiBuilder(makeConfig()); - expect(getChaiContextResolver()).toBeNull(); + expect(getRegisteredChaiContextResolver()).toBeNull(); const cb = await getChaiBuilder(); expect(cb.context).toMatchObject({ appId: "test-app-id", userId: null, draft: false }); }); @@ -86,6 +86,8 @@ describe("createChaiBuilder", () => { it("rejects a request passed without route props", async () => { const { getChaiBuilder } = createChaiBuilder(makeConfig(), { context: async () => ({ userId: "user-1" }) }); - await expect(getChaiBuilder(undefined, makeRequest())).rejects.toThrow("when passing a request, supply route props"); + await expect(getChaiBuilder(undefined, makeRequest())).rejects.toThrow( + "when passing a request, supply route props", + ); }); }); diff --git a/src/server/create-chai-builder.ts b/src/server/create-chai-builder.ts index 877073ae3..1ebe3b311 100644 --- a/src/server/create-chai-builder.ts +++ b/src/server/create-chai-builder.ts @@ -1,4 +1,4 @@ -import { setChaiContextResolver } from "~/server/chai-context-resolver"; +import { registerChaiContextResolver } from "~/server/chai-context-resolver"; import { getChaiBuilder } from "~/server/get-chaibuilder"; import type { ChaiBuilderInstance, @@ -75,7 +75,7 @@ export function createChaiBuilder< options?: CreateChaiBuilderOptions, ): ChaiBuilderHandle { if (options?.context) { - setChaiContextResolver(options.context as ChaiContextResolver); + registerChaiContextResolver(options.context as ChaiContextResolver); } return { diff --git a/src/server/defaults/builtin-chai-actions.ts b/src/server/defaults/builtin-chai-actions.ts index e9943bf0c..b4fba1f88 100644 --- a/src/server/defaults/builtin-chai-actions.ts +++ b/src/server/defaults/builtin-chai-actions.ts @@ -28,11 +28,8 @@ import { SearchPagesAction } from "~/server/chai-actions/pages/search-pages"; import { TakeOfflineAction } from "~/server/chai-actions/pages/take-offline"; import { UpdatePageAction } from "~/server/chai-actions/pages/update-page"; import { UpdatePageMetadataAction } from "~/server/chai-actions/pages/update-page-metadata"; -import { - CloneUpstreamPageAction, - ResetToUpstreamAction, -} from "~/server/chai-actions/pages/upstream-pages"; -import { declaredPermissionKeysOf } from "~/server/chai-actions/permission-keys"; +import { CloneUpstreamPageAction, ResetToUpstreamAction } from "~/server/chai-actions/pages/upstream-pages"; +import { getDeclaredChaiPermissionKeys } from "~/server/chai-actions/permission-keys"; import { updatePagePermission } from "~/server/chai-actions/pages/seo-permission"; import { GetTemplatesByTypeAction } from "~/server/chai-actions/templates/get-templates-by-type"; import { MarkAsTemplateAction } from "~/server/chai-actions/templates/mark-as-template"; @@ -53,11 +50,11 @@ import { /** * Assigns `requiredPermission` on an action instance and returns it. Also records * `declaredPermissionKeys` for guards that audit permissions without dispatching - * (a resolver must be tagged with `permissionResolver()`, or this throws). + * (a resolver must be tagged with `defineChaiPermissionResolver()`, or this throws). */ function wp>(action: T, permission: ChaiRequiredPermission): T { action.requiredPermission = permission; - action.declaredPermissionKeys = declaredPermissionKeysOf(permission); + action.declaredPermissionKeys = getDeclaredChaiPermissionKeys(permission); return action; } @@ -131,7 +128,7 @@ export const BUILTIN_CHAI_ACTIONS: Record> = { // than "unwrapped, requirement unknown". for (const action of Object.values(BUILTIN_CHAI_ACTIONS)) { if (!action.declaredPermissionKeys) { - action.declaredPermissionKeys = declaredPermissionKeysOf(action.requiredPermission); + action.declaredPermissionKeys = getDeclaredChaiPermissionKeys(action.requiredPermission); } } diff --git a/src/server/defaults/config-registry.ts b/src/server/defaults/config-registry.ts index 7710fb250..aa5bffeda 100644 --- a/src/server/defaults/config-registry.ts +++ b/src/server/defaults/config-registry.ts @@ -1,22 +1,22 @@ -import { resetDbForTests } from "~/server/chai-actions/db"; +import { resetChaiDbForTests } from "~/server/chai-actions/db"; import { normalizeHandlerRedirect } from "~/server/utils/redirect-path"; import type { ChaiPageType } from "~/types/actions"; import type { ChaiBlockDataProvider, - ChaiCollectionEntry, ChaiDynamicTemplateCandidate, ChaiPageNotFoundArgs, ChaiPageTypeEntry, ChaiRepeaterDataEntry, ChaiTrashEntry, } from "~/types/chaibuilder-config"; +import type { ChaiCollectionEntry } from "~/types/deprecated"; import { CORE_DEFAULT_CHAI_BUILDER_SERVER_CONFIG } from "./core-default-server-config"; import type { ChaiDefaultRoleGrants, ChaiMediaManagerConfig, ChaiRolesConfig, ChaiServerFeatures, - ResolvedChaiAIGlobalConfig, + ResolvedChaiAiGlobalConfig, ResolvedChaiBuilderServerConfig, } from "./types"; @@ -232,7 +232,7 @@ export function getConfigDefaultRoleGrants(): ChaiDefaultRoleGrants { return activeConfig.defaultRoleGrants; } -export function getConfigAI(): ResolvedChaiAIGlobalConfig { +export function getConfigAI(): ResolvedChaiAiGlobalConfig { return activeConfig.ai; } @@ -274,7 +274,7 @@ export function updateActiveActions(actions: ResolvedChaiBuilderServerConfig["ac }; } -export function updateActiveAiConfig(ai: ResolvedChaiAIGlobalConfig): void { +export function updateActiveAiConfig(ai: ResolvedChaiAiGlobalConfig): void { activeConfig = { ...activeConfig, ai }; } @@ -301,7 +301,7 @@ export function updateActiveBlockDataProviders( /** @internal Reset active config in unit tests. */ export function resetActiveChaiBuilderConfigForTests(overrides: Partial = {}): void { - resetDbForTests(); + resetChaiDbForTests(); activeConfig = { ...CORE_DEFAULT_CHAI_BUILDER_SERVER_CONFIG, actions: builtinActions, diff --git a/src/server/defaults/default-ai-config.ts b/src/server/defaults/default-ai-config.ts index 1ce072d06..7ca9d13b9 100644 --- a/src/server/defaults/default-ai-config.ts +++ b/src/server/defaults/default-ai-config.ts @@ -1,20 +1,20 @@ import type { ImageModel, LanguageModel } from "ai"; import { AI_MODELS, DEFAULT_MODEL_ID } from "~/builder/pages/panels/ai-panel/models"; -import type { LogAiRequestParams } from "~/types"; -import type { ResolvedChaiAIGlobalConfig } from "~/types/chaibuilder-config"; +import type { ChaiLogAiRequestArgs } from "~/types"; +import type { ResolvedChaiAiGlobalConfig } from "~/types/chaibuilder-config"; /** * Default AI request logger. Imported lazily (dynamic import) to break the circular * dependency: default-ai-config -> log-ai-request -> config-registry -> default-server-config * -> default-ai-config. Keeping this edge static makes module-init order fragile and can - * leave `DEFAULT_CHAI_BUILDER_SERVER_CONFIG.ai` undefined. + * leave `CHAI_DEFAULT_SERVER_CONFIG.ai` undefined. */ -const defaultAiLogger = async (params: LogAiRequestParams): Promise => { +const defaultAiLogger = async (params: ChaiLogAiRequestArgs): Promise => { const { logAiRequest } = await import("~/server/chai-actions/utils/log-ai-request"); return logAiRequest(params); }; -export const DEFAULT_AI_CONFIG: ResolvedChaiAIGlobalConfig = { +export const DEFAULT_AI_CONFIG: ResolvedChaiAiGlobalConfig = { models: AI_MODELS, defaultModelId: DEFAULT_MODEL_ID, actionModels: {}, diff --git a/src/server/defaults/default-server-config.ts b/src/server/defaults/default-server-config.ts index 64a40f999..ba93b20cc 100644 --- a/src/server/defaults/default-server-config.ts +++ b/src/server/defaults/default-server-config.ts @@ -4,7 +4,7 @@ import { CORE_DEFAULT_CHAI_BUILDER_SERVER_CONFIG } from "./core-default-server-c import type { ResolvedChaiBuilderServerConfig } from "./types"; /** Public server defaults, including the builtin chai actions. */ -export const DEFAULT_CHAI_BUILDER_SERVER_CONFIG: ResolvedChaiBuilderServerConfig = { +export const CHAI_DEFAULT_SERVER_CONFIG: ResolvedChaiBuilderServerConfig = { ...CORE_DEFAULT_CHAI_BUILDER_SERVER_CONFIG, actions: BUILTIN_CHAI_ACTIONS, builderActions: BUILTIN_CHAI_ACTIONS, diff --git a/src/server/defaults/index.ts b/src/server/defaults/index.ts index 0714ebcde..528a5c443 100644 --- a/src/server/defaults/index.ts +++ b/src/server/defaults/index.ts @@ -1,13 +1,13 @@ import "~/server/only-server"; import { DEFAULT_AI_CONFIG } from "./default-ai-config"; -import { DEFAULT_CHAI_BUILDER_SERVER_CONFIG } from "./default-server-config"; +import { CHAI_DEFAULT_SERVER_CONFIG } from "./default-server-config"; import { deepMerge, mergeByKey } from "./merge-config"; -import { resolveDbConfig } from "./resolve-db-config"; -import { ChaiBuilderServerConfigInput, ResolvedChaiAIGlobalConfig, ResolvedChaiBuilderServerConfig } from "./types"; +import { resolveChaiDbConfig } from "./resolve-db-config"; +import { ChaiBuilderServerConfigInput, ResolvedChaiAiGlobalConfig, ResolvedChaiBuilderServerConfig } from "./types"; -export { DEFAULT_CHAI_BUILDER_SERVER_CONFIG } from "./default-server-config"; +export { CHAI_DEFAULT_SERVER_CONFIG } from "./default-server-config"; -function resolveAiConfig(input?: ChaiBuilderServerConfigInput["ai"]): ResolvedChaiAIGlobalConfig { +function resolveAiConfig(input?: ChaiBuilderServerConfigInput["ai"]): ResolvedChaiAiGlobalConfig { if (!input) { return { ...DEFAULT_AI_CONFIG }; } @@ -50,13 +50,13 @@ export function resolveChaiBuilderConfig(rawInput: ChaiBuilderServerConfigInput) // `builderActions` is the deprecated spelling of `actions`: it is merged first, so on a name // clash the current key wins and a host mid-migration can pass either. const actions = { - ...DEFAULT_CHAI_BUILDER_SERVER_CONFIG.actions, + ...CHAI_DEFAULT_SERVER_CONFIG.actions, ...input.builderActions, ...input.actions, }; - const trash = mergeByKey(DEFAULT_CHAI_BUILDER_SERVER_CONFIG.trash, input.trash, (entry) => entry.key); - const defaultFeatures = DEFAULT_CHAI_BUILDER_SERVER_CONFIG.features; - const defaultMediaManager = DEFAULT_CHAI_BUILDER_SERVER_CONFIG.mediaManager; + const trash = mergeByKey(CHAI_DEFAULT_SERVER_CONFIG.trash, input.trash, (entry) => entry.key); + const defaultFeatures = CHAI_DEFAULT_SERVER_CONFIG.features; + const defaultMediaManager = CHAI_DEFAULT_SERVER_CONFIG.mediaManager; // deepMerge skips explicitly-undefined keys, so `{ copyPaste: undefined }` reads as "unset" // and falls through to the default rather than shipping undefined to the editor. Nested // plugin flags (`revisions: { enabled: true }`) keep the rest of their plugin's defaults. @@ -64,25 +64,24 @@ export function resolveChaiBuilderConfig(rawInput: ChaiBuilderServerConfigInput) // `repeaterData` is the deprecated spelling of `chaiCollections`. Both are // merged by id, deprecated first, so a host mid-migration can pass either. const chaiCollections = mergeByKey( - mergeByKey(DEFAULT_CHAI_BUILDER_SERVER_CONFIG.chaiCollections ?? [], input.repeaterData, (entry) => entry.id), + mergeByKey(CHAI_DEFAULT_SERVER_CONFIG.chaiCollections ?? [], input.repeaterData, (entry) => entry.id), input.chaiCollections, (entry) => entry.id, ); const resolved: ResolvedChaiBuilderServerConfig = { - debugLevel: input.debugLevel ?? DEFAULT_CHAI_BUILDER_SERVER_CONFIG.debugLevel, - globalDataProvider: input.globalDataProvider ?? DEFAULT_CHAI_BUILDER_SERVER_CONFIG.globalDataProvider, - onPageNotFound: input.onPageNotFound ?? DEFAULT_CHAI_BUILDER_SERVER_CONFIG.onPageNotFound, - resolveDynamicTemplateTie: - input.resolveDynamicTemplateTie ?? DEFAULT_CHAI_BUILDER_SERVER_CONFIG.resolveDynamicTemplateTie, - upstreamPageSource: input.upstreamPageSource ?? DEFAULT_CHAI_BUILDER_SERVER_CONFIG.upstreamPageSource, - pageTypes: mergeByKey(DEFAULT_CHAI_BUILDER_SERVER_CONFIG.pageTypes, input.pageTypes, (entry) => entry.key), - collections: mergeByKey(DEFAULT_CHAI_BUILDER_SERVER_CONFIG.collections, input.collections, (entry) => entry.id), + debugLevel: input.debugLevel ?? CHAI_DEFAULT_SERVER_CONFIG.debugLevel, + globalDataProvider: input.globalDataProvider ?? CHAI_DEFAULT_SERVER_CONFIG.globalDataProvider, + onPageNotFound: input.onPageNotFound ?? CHAI_DEFAULT_SERVER_CONFIG.onPageNotFound, + resolveDynamicTemplateTie: input.resolveDynamicTemplateTie ?? CHAI_DEFAULT_SERVER_CONFIG.resolveDynamicTemplateTie, + upstreamPageSource: input.upstreamPageSource ?? CHAI_DEFAULT_SERVER_CONFIG.upstreamPageSource, + pageTypes: mergeByKey(CHAI_DEFAULT_SERVER_CONFIG.pageTypes, input.pageTypes, (entry) => entry.key), + collections: mergeByKey(CHAI_DEFAULT_SERVER_CONFIG.collections, input.collections, (entry) => entry.id), chaiCollections, /** @deprecated mirror of `chaiCollections` for hosts still reading this key. */ repeaterData: chaiCollections, blockDataProviders: { - ...DEFAULT_CHAI_BUILDER_SERVER_CONFIG.blockDataProviders, + ...CHAI_DEFAULT_SERVER_CONFIG.blockDataProviders, ...input.blockDataProviders, }, trash, @@ -99,7 +98,7 @@ export function resolveChaiBuilderConfig(rawInput: ChaiBuilderServerConfigInput) roles: input.roles ?? undefined, ai, mediaManager: deepMerge(defaultMediaManager, input.mediaManager), - db: resolveDbConfig(input.db), + db: resolveChaiDbConfig(input.db), schemaFragments: input.schemaFragments ?? [], requestMiddlewares: input.requestMiddlewares ?? [], setupHooks: input.setupHooks ?? [], @@ -110,7 +109,7 @@ export function resolveChaiBuilderConfig(rawInput: ChaiBuilderServerConfigInput) return resolved; } -export { resolveDbConfig } from "./resolve-db-config"; +export { resolveChaiDbConfig } from "./resolve-db-config"; export type { ChaiBuilderServerConfigInput, ChaiMediaManagerConfig, @@ -118,7 +117,7 @@ export type { ChaiDbConfigInput, ChaiDbSetup, ChaiRolesConfig, - ResolvedChaiAIGlobalConfig, + ResolvedChaiAiGlobalConfig, ResolvedChaiBuilderServerConfig, ResolvedChaiDbConfig, } from "./types"; diff --git a/src/server/defaults/resolve-config.test.ts b/src/server/defaults/resolve-config.test.ts index 14172fbf5..18dfdb749 100644 --- a/src/server/defaults/resolve-config.test.ts +++ b/src/server/defaults/resolve-config.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import { defineChaiServerPlugin, setPluginFeatures, setPluginMediaManager } from "~/server/plugin-api"; -import { DEFAULT_CHAI_BUILDER_SERVER_CONFIG, resolveChaiBuilderConfig } from "./index"; +import { CHAI_DEFAULT_SERVER_CONFIG, resolveChaiBuilderConfig } from "./index"; import { stubChaiDbSetup } from "~/tests/setup/stub-chai-db"; /** @@ -33,7 +33,7 @@ describe("resolveChaiBuilderConfig", () => { expect(config.pageTypes.map((p) => p.key)).toEqual(["page", "global", "_folder"]); // Trash entities are plugin-owned; the bare core has none. expect(config.trash).toEqual([]); - expect(config.ai.logging.logger).toBe(DEFAULT_CHAI_BUILDER_SERVER_CONFIG.ai.logging.logger); + expect(config.ai.logging.logger).toBe(CHAI_DEFAULT_SERVER_CONFIG.ai.logging.logger); expect(config.ai.models.length).toBeGreaterThan(0); expect(config.debugLevel).toBe(0); expect(config.db).toBe(db); @@ -77,7 +77,7 @@ describe("resolveChaiBuilderConfig", () => { }); expect(config.ai.logging.clientId).toBe("client-1"); - expect(config.ai.logging.logger).toBe(DEFAULT_CHAI_BUILDER_SERVER_CONFIG.ai.logging.logger); + expect(config.ai.logging.logger).toBe(CHAI_DEFAULT_SERVER_CONFIG.ai.logging.logger); }); it("applies scalar overrides", () => { diff --git a/src/server/defaults/resolve-db-config.test.ts b/src/server/defaults/resolve-db-config.test.ts index 5624b04b5..99a5e7e65 100644 --- a/src/server/defaults/resolve-db-config.test.ts +++ b/src/server/defaults/resolve-db-config.test.ts @@ -1,19 +1,19 @@ import { describe, expect, it } from "vitest"; -import { resolveDbConfig } from "./resolve-db-config"; +import { resolveChaiDbConfig } from "./resolve-db-config"; import { stubChaiDbSetup } from "~/tests/setup/stub-chai-db"; import type { ChaiDbSetup } from "~/db/core"; describe("resolveDbConfig", () => { it("throws when input is undefined", () => { - expect(() => resolveDbConfig(undefined)).toThrow(/`db` is required/); + expect(() => resolveChaiDbConfig(undefined)).toThrow(/`db` is required/); }); it("throws when drizzle is missing", () => { - expect(() => resolveDbConfig({ schema: {} } as ChaiDbSetup)).toThrow(/`db` is required/); + expect(() => resolveChaiDbConfig({ schema: {} } as ChaiDbSetup)).toThrow(/`db` is required/); }); it("returns a valid ChaiDbSetup", () => { const setup = stubChaiDbSetup(); - expect(resolveDbConfig(setup)).toBe(setup); + expect(resolveChaiDbConfig(setup)).toBe(setup); }); }); diff --git a/src/server/defaults/resolve-db-config.ts b/src/server/defaults/resolve-db-config.ts index 768450b57..2e09d1d88 100644 --- a/src/server/defaults/resolve-db-config.ts +++ b/src/server/defaults/resolve-db-config.ts @@ -1,7 +1,7 @@ import type { ChaiDbSetup } from "./types"; /** Validates `db` from `buildChaiBuilderConfig`. */ -export function resolveDbConfig(input: ChaiDbSetup | undefined): ChaiDbSetup { +export function resolveChaiDbConfig(input: ChaiDbSetup | undefined): ChaiDbSetup { if (!input || typeof input !== "object") { throw new Error( "ChaiBuilder: `db` is required in `buildChaiBuilderConfig`. Pass `db: createPostgresDB(...)` (or libsql/d1/better-sqlite3).", diff --git a/src/server/defaults/serialize-ai-config.ts b/src/server/defaults/serialize-ai-config.ts index a129c86a8..6b40d2a61 100644 --- a/src/server/defaults/serialize-ai-config.ts +++ b/src/server/defaults/serialize-ai-config.ts @@ -1,5 +1,5 @@ import type { AIModel } from "~/builder/pages/panels/ai-panel/ai-models-context"; -import type { ResolvedChaiAIGlobalConfig } from "~/types/server-config"; +import type { ResolvedChaiAiGlobalConfig } from "~/types/server-config"; /** The AI config as the builder sees it: plain data only. */ export type SerializedAIConfig = { @@ -17,7 +17,7 @@ export type SerializedAIConfig = { * * `defaultModelId` is not included — the builder has no read site for it and picks its own default. */ -export function serializeAIConfigForClient(config: ResolvedChaiAIGlobalConfig): SerializedAIConfig { +export function serializeAIConfigForClient(config: ResolvedChaiAiGlobalConfig): SerializedAIConfig { return { models: config.models.map((model) => ({ id: model.id, diff --git a/src/server/defaults/types.ts b/src/server/defaults/types.ts index 23eb980eb..dc9e48ca0 100644 --- a/src/server/defaults/types.ts +++ b/src/server/defaults/types.ts @@ -7,8 +7,8 @@ export type { ChaiServerFeaturesInput, ChaiDefaultRoleGrants, ChaiRolesConfig, - LogAiRequestParams, - ResolvedChaiAIGlobalConfig, + ChaiLogAiRequestArgs, + ResolvedChaiAiGlobalConfig, ResolvedChaiBuilderServerConfig, ResolvedChaiDbConfig, } from "~/types/server-config"; diff --git a/src/server/get-chaibuilder.test.ts b/src/server/get-chaibuilder.test.ts index c0a5d332c..4c08849c0 100644 --- a/src/server/get-chaibuilder.test.ts +++ b/src/server/get-chaibuilder.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { buildChaiBuilderConfig } from "~/server/build-config"; -import { getDb } from "~/server/chai-actions/db"; -import { resetChaiContextResolverForTests, setChaiContextResolver } from "~/server/chai-context-resolver"; +import { getChaiDb } from "~/server/chai-actions/db"; +import { resetChaiContextResolverForTests, registerChaiContextResolver } from "~/server/chai-context-resolver"; import { resetActiveChaiBuilderConfigForTests } from "~/server/defaults/config-registry"; import { getOptionalRequestState } from "~/server/chai-builder/state"; import { registerChaiInstanceApi, resetChaiInstanceApisForTests } from "~/server/plugin-api/instance-api-registry"; @@ -38,11 +38,11 @@ describe("getChaiBuilder", () => { expect(Object.isFrozen(cb.context)).toBe(true); expect(typeof cb.getPage).toBe("function"); expect(typeof cb.runAction).toBe("function"); - expect(cb.db).toBe(getDb()); + expect(cb.db).toBe(getChaiDb()); expect(typeof cb.safeQuery).toBe("function"); const result = await cb.safeQuery(async ({ db, schema }) => { - expect(db).toBe(getDb()); + expect(db).toBe(getChaiDb()); expect(schema).toBe(cb.schema); return "ok"; }); @@ -77,7 +77,7 @@ describe("getChaiBuilder", () => { }); it("reflects draft resolved by the registered resolver", async () => { - setChaiContextResolver(async () => ({ draft: true })); + registerChaiContextResolver(async () => ({ draft: true })); const config = buildChaiBuilderConfig({ db: stubChaiDbConfig() }); const cb = await getChaiBuilder(config); @@ -113,7 +113,7 @@ describe("getChaiBuilder", () => { }); it("throws when request is passed without route props", async () => { - setChaiContextResolver(async () => ({ userId: "user-1" })); + registerChaiContextResolver(async () => ({ userId: "user-1" })); const config = buildChaiBuilderConfig({ db: stubChaiDbConfig() }); const request = new Request("https://example.com") as Request & { cookies: { get: () => undefined }; @@ -126,7 +126,7 @@ describe("getChaiBuilder", () => { }); it("merges the registered resolver result into the request context", async () => { - setChaiContextResolver(async () => ({ + registerChaiContextResolver(async () => ({ userId: "user-42", lang: "fr", })); @@ -166,7 +166,7 @@ describe("getChaiBuilder", () => { }); it("shares route-resolved context with later getChaiBuilder(config) calls in the same request", async () => { - setChaiContextResolver(async () => ({ + registerChaiContextResolver(async () => ({ appId: "hostname-resolved-app", siteUrl: "https://acme.example", })); diff --git a/src/server/get-chaibuilder.ts b/src/server/get-chaibuilder.ts index c57452b6c..a20afe315 100644 --- a/src/server/get-chaibuilder.ts +++ b/src/server/get-chaibuilder.ts @@ -1,6 +1,13 @@ import "~/server/only-server"; import { getChaiBuilderConfigOnInit } from "~/server/build-config"; -import { ensureDbReady, getDb, registerDb, safeQuery, schema, type ChaiDbContext } from "~/server/chai-actions/db"; +import { + ensureChaiDbReady, + getChaiDb, + registerChaiDb, + safeQuery, + schema, + type ChaiDbContext, +} from "~/server/chai-actions/db"; import { getOptionalRequestState, runInContext } from "~/server/chai-builder/state"; import { getDebugLevel, setGlobalDebugLevel } from "~/server/debug/debug-level"; import { logApiComplete, logInitPhase, logPhaseStart, logTraceStart } from "~/server/debug/debug-log"; @@ -172,7 +179,7 @@ function bindActionWithDebug( * * - `getChaiBuilder(config)` — uses shared per-request context when already resolved (e.g. by an * earlier `getChaiBuilder(config, routeProps)` in the same render); otherwise invokes the registered - * context resolver (see `setChaiContextResolver`), falling back to a static default when none is set. + * context resolver (see `registerChaiContextResolver`), falling back to a static default when none is set. * - `getChaiBuilder(config, { params, searchParams }, request?)` — same props shape as `page` / `layout` / * `generateMetadata`. Resolves context via the registered resolver and stores it for the rest of the request. * @@ -213,7 +220,7 @@ export async function getChaiBuilder( const builderStart = performance.now(); const ctx = await resolveSharedChaiContext(routeProps, request); - await ensureDbReady(); + await ensureChaiDbReady(); await _core.ensureSynced(); if (getDebugLevel() >= 1) { logInitPhase("getChaiBuilder", Math.round(performance.now() - builderStart)); @@ -235,8 +242,8 @@ function createContextualInstance(core: ChaiBuilderCore, context: ChaiRequestCon ); const runActionFn = async (name: string, input: I): Promise => { - const { dispatchChaiAction } = await import("~/server/chai-actions/dispatch-action"); - return dispatchChaiAction(name, input) as Promise; + const { runChaiAction } = await import("~/server/chai-actions/dispatch-action"); + return runChaiAction(name, input) as Promise; }; const tryActionFn = async (name: string, input: I) => { @@ -256,7 +263,7 @@ function createContextualInstance(core: ChaiBuilderCore, context: ChaiRequestCon (name: string, _input: unknown) => `tryAction:${name}`, ) as ChaiBuilderInstance["tryAction"]; - const db = getDb(); + const db = getChaiDb(); const dbCtx: ChaiDbContext = { db, schema }; // Plugin-contributed namespaces (registerChaiInstanceApi), each function @@ -394,7 +401,7 @@ function createContextualInstance(core: ChaiBuilderCore, context: ChaiRequestCon } function createCore(config: ResolvedChaiBuilderServerConfig): ChaiBuilderCore { - registerDb(config.db); + registerChaiDb(config.db); setActiveChaiBuilderConfig(config); setGlobalDebugLevel(config.debugLevel); diff --git a/src/server/mcp/actions.ts b/src/server/mcp/actions.ts index 46f4db2ed..3ce603db5 100644 --- a/src/server/mcp/actions.ts +++ b/src/server/mcp/actions.ts @@ -1,4 +1,4 @@ -import { dispatchChaiAction } from "~/server/chai-actions/dispatch-action"; +import { runChaiAction } from "~/server/chai-actions/dispatch-action"; import { applyChaiActionCacheEffects, type ChaiActionCacheOptions } from "~/server/chai-builder/action-cache-effects"; /** @@ -17,7 +17,7 @@ export async function runChaiMcpAction( input: unknown, options: ChaiActionCacheOptions = {}, ): Promise { - const result = (await dispatchChaiAction(name, input)) as TResult; + const result = (await runChaiAction(name, input)) as TResult; try { await applyChaiActionCacheEffects(name, result, options); } catch (error) { diff --git a/src/server/mcp/api.ts b/src/server/mcp/api.ts index 3c9199412..b26024dac 100644 --- a/src/server/mcp/api.ts +++ b/src/server/mcp/api.ts @@ -12,14 +12,15 @@ export { defineChaiMcpInstructionsSection, defineChaiMcpTool, defineChaiMcpToolMeta, - getChaiMcpInstructionsSections, - getChaiMcpTool, - getChaiMcpTools, + getRegisteredChaiMcpInstructions, + getRegisteredChaiMcpTool, + getRegisteredChaiMcpTools, registerChaiMcpInstructions, registerChaiMcpTool, registerChaiMcpTools, resetChaiMcpRegistryForTests, unregisterChaiMcpInstructions, + unregisterChaiMcpTool, unregisterChaiMcpTools, type ChaiMcpRegisterOptions, } from "./registry"; @@ -35,7 +36,7 @@ export { runWithChaiMcpToolContext, } from "./request-context"; -export { canInvokeChaiMcpTool, missingChaiMcpToolPermissions } from "./permissions"; +export { canInvokeChaiMcpTool, getMissingChaiMcpToolPermissions } from "./permissions"; export { createChaiMcpResponse, toSafeChaiMcpError } from "./response"; export { runChaiMcpAction } from "./actions"; export { renderChaiMcpInstructions } from "./instructions"; diff --git a/src/server/mcp/deprecated.ts b/src/server/mcp/deprecated.ts new file mode 100644 index 000000000..f757455c4 --- /dev/null +++ b/src/server/mcp/deprecated.ts @@ -0,0 +1,18 @@ +/** + * Deprecated names of `/mcp`, re-exported by `./index.ts`. + * + * chaipro makes no breaking changes: a renamed or retired export keeps working from its original + * import path, with a `@deprecated` notice that names its replacement. Never delete an entry here. + * See API-CONSISTENCY.md. + */ + +export { + /** @deprecated Use `getRegisteredChaiMcpInstructions` from `/mcp`. Kept for compatibility. */ + getRegisteredChaiMcpInstructions as getChaiMcpInstructionsSections, + /** @deprecated Use `getRegisteredChaiMcpTool` from `/mcp`. Kept for compatibility. */ + getRegisteredChaiMcpTool as getChaiMcpTool, + /** @deprecated Use `getRegisteredChaiMcpTools` from `/mcp`. Kept for compatibility. */ + getRegisteredChaiMcpTools as getChaiMcpTools, + /** @deprecated Use `getMissingChaiMcpToolPermissions` from `/mcp`. Kept for compatibility. */ + getMissingChaiMcpToolPermissions as missingChaiMcpToolPermissions, +} from "~/server/mcp/api"; diff --git a/src/server/mcp/handle-request.ts b/src/server/mcp/handle-request.ts index 3c438d6dc..696935b16 100644 --- a/src/server/mcp/handle-request.ts +++ b/src/server/mcp/handle-request.ts @@ -7,21 +7,16 @@ import { runInFreshContext } from "~/server/chai-builder/state"; import { mergeDelegationCeilings, resolveEffectivePermissions } from "~/server/rbac/effective-permissions"; import type { ChaiIncomingRequest, ChaiRequestContext } from "~/types/chaibuilder-config"; import type { ChaiBuilderInstance } from "~/types/chaibuilder-instance"; -import type { - ChaiMcpAuthFailureEvent, - ChaiMcpRequestContext, - ChaiMcpTool, - ChaiMcpToolCallEvent, - ChaiMcpToolMeta, - ChaiMcpToolOutcome, - ChaiMcpToolResult, -} from "~/types/mcp"; +import type { ChaiMcpRequestContext, ChaiMcpTool, ChaiMcpToolOutcome, ChaiMcpToolResult } from "~/types/mcp"; import { summarizeChaiMcpToolArgs } from "./audit"; import { renderChaiMcpInstructions } from "./instructions"; -import { canInvokeChaiMcpTool, missingChaiMcpToolPermissions } from "./permissions"; -import { getChaiMcpTools } from "./registry"; +import { canInvokeChaiMcpTool, getMissingChaiMcpToolPermissions } from "./permissions"; +import { getRegisteredChaiMcpTools } from "./registry"; import { runWithChaiMcpRequest, runWithChaiMcpToolContext } from "./request-context"; import { toSafeChaiMcpError } from "./response"; +import type { ChaiMcpHandlerOptions, ChaiMcpRouteHandlerOptions } from "./handler-types"; + +export type { ChaiMcpHandlerOptions, ChaiMcpRouteHandlerOptions, ChaiMcpServerInfo } from "./handler-types"; /** * MCP Streamable HTTP transport for ChaiBuilder. @@ -40,55 +35,6 @@ import { toSafeChaiMcpError } from "./response"; * leaking into another's. */ -export type ChaiMcpServerInfo = { - name: string; - version: string; - title?: string; -}; - -export type ChaiMcpHandlerOptions = { - serverInfo: ChaiMcpServerInfo; - /** - * `resource_metadata` for the 401 challenge (RFC 9728), so an OAuth-capable client can - * discover where to authenticate instead of giving up. - */ - resourceMetadataUrl?: string | ((request: Request) => string | undefined); - /** `realm` for the 401 challenge. Defaults to the request's own URL. */ - realm?: string; - /** - * Permission(s) required to use the MCP surface at all, checked before any tool is - * listed. A credential that should not drive an agent can be refused in one place - * rather than per tool. - */ - connectPermission?: string | string[]; - /** - * Ceiling for this transport, intersected with whatever the context resolver set. An - * app can mount a read-only MCP route without changing how its credentials are issued. - */ - delegatedPermissions?: string[]; - /** Largest `arguments` payload accepted for a single call. Default 2 MB. */ - maxArgsBytes?: number; - /** Largest request body accepted. Default 4 MB. */ - maxBodyBytes?: number; - /** - * Omit tools the caller lacks permission for from `tools/list`. On by default: an agent - * that cannot see a tool does not spend context on it or plan around it. Calls are - * re-checked regardless, so this is a context optimisation, never the security boundary. - */ - hideUngrantedTools?: boolean; - /** Last word on which tools this request may see, after the permission filter. */ - toolFilter?: (tool: ChaiMcpToolMeta, ctx: ChaiMcpRequestContext) => boolean; - /** Replace or wrap the rendered server instructions. */ - instructions?: string | ((rendered: string, ctx: ChaiMcpRequestContext) => string); - /** Audit sink. Receives every settled tool call; a failure in it never fails the call. */ - onToolCall?: (event: ChaiMcpToolCallEvent) => void | Promise; - onAuthFailure?: (event: ChaiMcpAuthFailureEvent) => void | Promise; - /** Passed to cache invalidation for layout-level revalidation. */ - catchAllRoute?: string[]; - /** Host extras carried onto every tool context and audit event (token label, …). */ - extra?: Record | ((request: Request) => Record); -}; - const DEFAULT_MAX_ARGS_BYTES = 2_000_000; const DEFAULT_MAX_BODY_BYTES = 4_000_000; @@ -258,7 +204,7 @@ export async function handleChaiMcpRequest( ? options.connectPermission : [options.connectPermission] : []; - const missingConnect = missingChaiMcpToolPermissions(permissions, { + const missingConnect = getMissingChaiMcpToolPermissions(permissions, { name: "connect", kind: "read", description: "", @@ -295,7 +241,7 @@ export async function handleChaiMcpRequest( // The derived context — surface stamped, ceiling applied — must not collapse into an // outer request state that lacks them, so it starts a store of its own. Every `cb.*` // call and every action dispatched from a tool then sees the MCP identity, which is - // what makes revisions attribute to `mcp` and the ceiling bind in `dispatchChaiAction`. + // what makes revisions attribute to `mcp` and the ceiling bind in `runChaiAction`. const derived: ChaiRequestContext = { ...resolved, surface: mcpContext.surface, @@ -314,7 +260,7 @@ export async function handleChaiMcpRequest( function visibleTools(ctx: ChaiMcpRequestContext, options: ChaiMcpHandlerOptions): ChaiMcpTool[] { const hide = options.hideUngrantedTools ?? true; - return getChaiMcpTools().filter((tool) => { + return getRegisteredChaiMcpTools().filter((tool) => { if (hide && !canInvokeChaiMcpTool(ctx.permissions, tool)) return false; return options.toolFilter ? options.toolFilter(tool, ctx) : true; }); @@ -434,14 +380,14 @@ async function callTool( if (!tool) { // Distinguish "never existed" from "you cannot see it" for the audit trail only; // the caller is told the same thing either way. - outcome = getChaiMcpTools().some((candidate) => candidate.name === name) ? "forbidden" : "not_found"; + outcome = getRegisteredChaiMcpTools().some((candidate) => candidate.name === name) ? "forbidden" : "not_found"; message = `Error: unknown tool "${name}".`; return finish({ content: [{ type: "text", text: message }], isError: true }); } // Re-checked even though the list was filtered: `hideUngrantedTools` is a context // optimisation, and this is the boundary. - const missing = missingChaiMcpToolPermissions(ctx.permissions, tool); + const missing = getMissingChaiMcpToolPermissions(ctx.permissions, tool); if (missing.length > 0) { return fail("forbidden", `Error: missing permission ${missing.join(", ")} for "${name}".`); } @@ -468,11 +414,6 @@ async function callTool( }); } -export type ChaiMcpRouteHandlerOptions = ChaiMcpHandlerOptions & { - /** Usually `(request) => getChaiBuilder({}, request)` — the host's own resolver. */ - getChaiBuilder: (request: ChaiIncomingRequest) => Promise> | ChaiBuilderInstance; -}; - /** * Route handlers for a framework that exports `GET`/`POST`/`DELETE` (Next.js App Router, * Hono, Remix). One line in the host; everything below it lives here. diff --git a/src/server/mcp/handler-types.ts b/src/server/mcp/handler-types.ts new file mode 100644 index 000000000..3ea25fb55 --- /dev/null +++ b/src/server/mcp/handler-types.ts @@ -0,0 +1,69 @@ +/** + * Option types of the MCP transport (`createChaiMcpRouteHandlers`, `handleChaiMcpRequest`). + * + * Kept apart from `./handle-request` — the only module that imports the optional + * `@modelcontextprotocol/sdk` peer — so `/nextjs/server` can export these types without its + * type graph reaching the SDK. + */ +import type { ChaiIncomingRequest } from "~/types/chaibuilder-config"; +import type { ChaiBuilderInstance } from "~/types/chaibuilder-instance"; +import type { + ChaiMcpAuthFailureEvent, + ChaiMcpRequestContext, + ChaiMcpToolCallEvent, + ChaiMcpToolMeta, +} from "~/types/mcp"; + +export type ChaiMcpServerInfo = { + name: string; + version: string; + title?: string; +}; + +export type ChaiMcpHandlerOptions = { + serverInfo: ChaiMcpServerInfo; + /** + * `resource_metadata` for the 401 challenge (RFC 9728), so an OAuth-capable client can + * discover where to authenticate instead of giving up. + */ + resourceMetadataUrl?: string | ((request: Request) => string | undefined); + /** `realm` for the 401 challenge. Defaults to the request's own URL. */ + realm?: string; + /** + * Permission(s) required to use the MCP surface at all, checked before any tool is + * listed. A credential that should not drive an agent can be refused in one place + * rather than per tool. + */ + connectPermission?: string | string[]; + /** + * Ceiling for this transport, intersected with whatever the context resolver set. An + * app can mount a read-only MCP route without changing how its credentials are issued. + */ + delegatedPermissions?: string[]; + /** Largest `arguments` payload accepted for a single call. Default 2 MB. */ + maxArgsBytes?: number; + /** Largest request body accepted. Default 4 MB. */ + maxBodyBytes?: number; + /** + * Omit tools the caller lacks permission for from `tools/list`. On by default: an agent + * that cannot see a tool does not spend context on it or plan around it. Calls are + * re-checked regardless, so this is a context optimisation, never the security boundary. + */ + hideUngrantedTools?: boolean; + /** Last word on which tools this request may see, after the permission filter. */ + toolFilter?: (tool: ChaiMcpToolMeta, ctx: ChaiMcpRequestContext) => boolean; + /** Replace or wrap the rendered server instructions. */ + instructions?: string | ((rendered: string, ctx: ChaiMcpRequestContext) => string); + /** Audit sink. Receives every settled tool call; a failure in it never fails the call. */ + onToolCall?: (event: ChaiMcpToolCallEvent) => void | Promise; + onAuthFailure?: (event: ChaiMcpAuthFailureEvent) => void | Promise; + /** Passed to cache invalidation for layout-level revalidation. */ + catchAllRoute?: string[]; + /** Host extras carried onto every tool context and audit event (token label, …). */ + extra?: Record | ((request: Request) => Record); +}; + +export type ChaiMcpRouteHandlerOptions = ChaiMcpHandlerOptions & { + /** Usually `(request) => getChaiBuilder({}, request)` — the host's own resolver. */ + getChaiBuilder: (request: ChaiIncomingRequest) => Promise> | ChaiBuilderInstance; +}; diff --git a/src/server/mcp/index.ts b/src/server/mcp/index.ts index 02de2ae57..2b2248da1 100644 --- a/src/server/mcp/index.ts +++ b/src/server/mcp/index.ts @@ -16,3 +16,6 @@ export { type ChaiMcpRouteHandlerOptions, type ChaiMcpServerInfo, } from "./handle-request"; + +// Deprecated names, kept for compatibility. See ./deprecated.ts. +export * from "./deprecated"; diff --git a/src/server/mcp/instructions.ts b/src/server/mcp/instructions.ts index db2342455..af9a63f88 100644 --- a/src/server/mcp/instructions.ts +++ b/src/server/mcp/instructions.ts @@ -1,6 +1,6 @@ import { getActiveChaiBuilderConfig } from "~/server/defaults/config-registry"; import type { ChaiMcpInstructionsContext, ChaiMcpToolMeta } from "~/types/mcp"; -import { getChaiMcpInstructionsSections, getChaiMcpTools } from "./registry"; +import { getRegisteredChaiMcpInstructions, getRegisteredChaiMcpTools } from "./registry"; /** `\b` treats `_` as a word character, so `page_edit` does not match `start_page_edit`. */ const mentions = (text: string, name: string): boolean => new RegExp(`\\b${name}\\b`).test(text); @@ -41,10 +41,10 @@ export function renderChaiMcpInstructions(tools: ChaiMcpToolMeta[]): string { const visible = new Set(tools.map((tool) => tool.name)); // Every registered name, not just the visible ones: a name is only worth filtering a // line for if it is a tool somewhere, and the hidden ones are exactly the point. - const registered = getChaiMcpTools().map((tool) => tool.name); + const registered = getRegisteredChaiMcpTools().map((tool) => tool.name); const rendered: string[] = []; - for (const section of getChaiMcpInstructionsSections()) { + for (const section of getRegisteredChaiMcpInstructions()) { if (section.requiresTools && !section.requiresTools.some((name) => visible.has(name))) continue; let body: string; diff --git a/src/server/mcp/permissions.test.ts b/src/server/mcp/permissions.test.ts index a8e5169e8..1068e602e 100644 --- a/src/server/mcp/permissions.test.ts +++ b/src/server/mcp/permissions.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import type { ChaiMcpToolMeta } from "~/types/mcp"; -import { canInvokeChaiMcpTool, missingChaiMcpToolPermissions } from "./permissions"; +import { canInvokeChaiMcpTool, getMissingChaiMcpToolPermissions } from "./permissions"; const meta = (permissions: string[]): ChaiMcpToolMeta => ({ name: "a_tool", @@ -31,7 +31,7 @@ describe("canInvokeChaiMcpTool", () => { }); it("names what is missing", () => { - expect(missingChaiMcpToolPermissions(["pages:read"], meta(["pages:read", "pages:publish"]))).toEqual([ + expect(getMissingChaiMcpToolPermissions(["pages:read"], meta(["pages:read", "pages:publish"]))).toEqual([ "pages:publish", ]); }); diff --git a/src/server/mcp/permissions.ts b/src/server/mcp/permissions.ts index 848ae690c..334e59f62 100644 --- a/src/server/mcp/permissions.ts +++ b/src/server/mcp/permissions.ts @@ -1,4 +1,4 @@ -import { hasPermission } from "~/server/rbac/permissions"; +import { hasChaiPermission } from "~/server/rbac/permissions"; import type { ChaiMcpToolMeta } from "~/types/mcp"; /** @@ -12,10 +12,10 @@ import type { ChaiMcpToolMeta } from "~/types/mcp"; */ export function canInvokeChaiMcpTool(permissions: string[], tool: ChaiMcpToolMeta | undefined): boolean { if (!tool) return false; - return tool.permissions.every((required) => hasPermission(permissions, required)); + return tool.permissions.every((required) => hasChaiPermission(permissions, required)); } /** The permissions a caller is missing for a tool, for a message that says what to fix. */ -export function missingChaiMcpToolPermissions(permissions: string[], tool: ChaiMcpToolMeta): string[] { - return tool.permissions.filter((required) => !hasPermission(permissions, required)); +export function getMissingChaiMcpToolPermissions(permissions: string[], tool: ChaiMcpToolMeta): string[] { + return tool.permissions.filter((required) => !hasChaiPermission(permissions, required)); } diff --git a/src/server/mcp/registry.test.ts b/src/server/mcp/registry.test.ts index e7aafeb84..2bbe21813 100644 --- a/src/server/mcp/registry.test.ts +++ b/src/server/mcp/registry.test.ts @@ -3,13 +3,14 @@ import { createChaiMcpResponse } from "./response"; import { defineChaiMcpInstructionsSection, defineChaiMcpTool, - getChaiMcpInstructionsSections, - getChaiMcpTool, - getChaiMcpTools, + getRegisteredChaiMcpInstructions, + getRegisteredChaiMcpTool, + getRegisteredChaiMcpTools, registerChaiMcpInstructions, registerChaiMcpTool, registerChaiMcpTools, resetChaiMcpRegistryForTests, + unregisterChaiMcpTool, unregisterChaiMcpTools, } from "./registry"; @@ -25,14 +26,26 @@ describe("MCP tool registry", () => { registerChaiMcpTools("chai:mcp", [tool("create_page"), tool("publish_page")]); registerChaiMcpTools("app", [tool("list_leads")]); - expect(getChaiMcpTools().map((t) => t.name)).toEqual(["create_page", "publish_page", "list_leads"]); + expect(getRegisteredChaiMcpTools().map((t) => t.name)).toEqual(["create_page", "publish_page", "list_leads"]); + }); + + it("unregisters one tool and gives back its override claim", () => { + registerChaiMcpTools("chai:mcp", [tool("create_page"), tool("publish_page")]); + registerChaiMcpTool("app", tool("publish_page"), { override: true }); + registerChaiMcpTool("app", tool("list_leads")); + + unregisterChaiMcpTool("app", "publish_page"); + expect(getRegisteredChaiMcpTools().map((t) => t.name)).toEqual(["create_page", "publish_page", "list_leads"]); + + unregisterChaiMcpTool("app", "list_leads"); + expect(getRegisteredChaiMcpTools().map((t) => t.name)).toEqual(["create_page", "publish_page"]); }); it("replaces an owner's previous set rather than appending to it", () => { registerChaiMcpTools("chai:mcp", [tool("create_page"), tool("publish_page")]); registerChaiMcpTools("chai:mcp", [tool("create_page")]); - expect(getChaiMcpTools().map((t) => t.name)).toEqual(["create_page"]); + expect(getRegisteredChaiMcpTools().map((t) => t.name)).toEqual(["create_page"]); }); it("keeps a first-registration position when an owner re-registers", () => { @@ -40,29 +53,29 @@ describe("MCP tool registry", () => { registerChaiMcpTools("app", [tool("list_leads")]); registerChaiMcpTools("chai:mcp", [tool("create_page"), tool("publish_page")]); - expect(getChaiMcpTools().map((t) => t.name)).toEqual(["create_page", "publish_page", "list_leads"]); + expect(getRegisteredChaiMcpTools().map((t) => t.name)).toEqual(["create_page", "publish_page", "list_leads"]); }); it("upserts a single tool without dropping the owner's others", () => { registerChaiMcpTools("app", [tool("a_tool"), tool("b_tool")]); registerChaiMcpTool("app", tool("a_tool", ["pages:read"])); - expect(getChaiMcpTools().map((t) => t.name)).toEqual(["b_tool", "a_tool"]); - expect(getChaiMcpTool("a_tool")?.permissions).toEqual(["pages:read"]); + expect(getRegisteredChaiMcpTools().map((t) => t.name)).toEqual(["b_tool", "a_tool"]); + expect(getRegisteredChaiMcpTool("a_tool")?.permissions).toEqual(["pages:read"]); }); it("refuses a name another owner already registered", () => { registerChaiMcpTools("chai:mcp", [tool("publish_page")]); expect(() => registerChaiMcpTools("app", [tool("publish_page")])).toThrow(/already owned by "chai:mcp"/); - expect(getChaiMcpTools()).toHaveLength(1); + expect(getRegisteredChaiMcpTools()).toHaveLength(1); }); it("lets an owner take over a name deliberately", () => { registerChaiMcpTools("chai:mcp", [tool("publish_page", ["pages:publish"])]); registerChaiMcpTools("app", [tool("publish_page", ["app:publish"])], { override: true }); - const tools = getChaiMcpTools(); + const tools = getRegisteredChaiMcpTools(); expect(tools).toHaveLength(1); expect(tools[0].permissions).toEqual(["app:publish"]); }); @@ -85,7 +98,7 @@ describe("MCP tool registry", () => { registerChaiMcpTools("app", [tool("list_leads")]); unregisterChaiMcpTools("app"); - expect(getChaiMcpTools().map((t) => t.name)).toEqual(["create_page"]); + expect(getRegisteredChaiMcpTools().map((t) => t.name)).toEqual(["create_page"]); }); }); @@ -100,7 +113,7 @@ describe("MCP instructions registry", () => { defineChaiMcpInstructionsSection({ id: "alpha", order: 30, body: "x" }), ]); - expect(getChaiMcpInstructionsSections().map((s) => s.id)).toEqual(["preamble", "alpha", "seo", "leads"]); + expect(getRegisteredChaiMcpInstructions().map((s) => s.id)).toEqual(["preamble", "alpha", "seo", "leads"]); }); it("refuses an id another owner already registered", () => { diff --git a/src/server/mcp/registry.ts b/src/server/mcp/registry.ts index 952480351..60657d65e 100644 --- a/src/server/mcp/registry.ts +++ b/src/server/mcp/registry.ts @@ -120,7 +120,7 @@ function registerTools(owner: string, tools: ChaiMcpTool[], claimed: Set if (!otherTools.some((other) => other.name === tool.name)) continue; // The other owner took this name deliberately, and re-registering the // original over it is routine — every setup-hook run re-registers a whole - // list — so it loses the name in `getChaiMcpTools` rather than throwing. + // list — so it loses the name in `getRegisteredChaiMcpTools` rather than throwing. if (overridesRegistry().get(otherOwner)?.has(tool.name)) continue; throw new Error( `ChaiBuilder MCP: "${owner}" registered the tool "${tool.name}", already owned by "${otherOwner}". Pass { override: true } to replace it deliberately.`, @@ -130,7 +130,7 @@ function registerTools(owner: string, tools: ChaiMcpTool[], claimed: Set registry.set(owner, [...tools]); // The claim is remembered per owner rather than inferred from registration - // order: `getChaiMcpTools` would otherwise hand the name to whichever owner + // order: `getRegisteredChaiMcpTools` would otherwise hand the name to whichever owner // sits later in the Map, which is the order owners FIRST registered in — so an // app whose setup hook ran before this plugin's would silently lose the name // it asked to override. A claim on a name no longer in the list is dropped. @@ -162,12 +162,24 @@ export function unregisterChaiMcpTools(owner: string): void { overridesRegistry().delete(owner); } +/** Removes one tool an owner registered, and the override claim it held on that name. */ +export function unregisterChaiMcpTool(owner: string, name: string): void { + const remaining = (toolsRegistry().get(owner) ?? []).filter((tool) => tool.name !== name); + const claimed = new Set(overridesRegistry().get(owner) ?? []); + claimed.delete(name); + if (remaining.length === 0) { + unregisterChaiMcpTools(owner); + return; + } + registerTools(owner, remaining, claimed); +} + /** * Every registered tool, in list order. An owner that registered a name with * `override` wins it, whichever of the owners registered first; the shadowed * tool is dropped rather than listed twice. */ -export function getChaiMcpTools(): ChaiMcpTool[] { +export function getRegisteredChaiMcpTools(): ChaiMcpTool[] { const overrides = overridesRegistry(); const byName = new Map(); const claimed = new Set(); @@ -183,8 +195,8 @@ export function getChaiMcpTools(): ChaiMcpTool[] { return [...byName.values()]; } -export function getChaiMcpTool(name: string): ChaiMcpTool | undefined { - return getChaiMcpTools().find((tool) => tool.name === name); +export function getRegisteredChaiMcpTool(name: string): ChaiMcpTool | undefined { + return getRegisteredChaiMcpTools().find((tool) => tool.name === name); } export function registerChaiMcpInstructions( @@ -223,7 +235,7 @@ export function unregisterChaiMcpInstructions(owner: string): void { } /** Registered sections, sorted by `order` then by id so the render is deterministic. */ -export function getChaiMcpInstructionsSections(): ChaiMcpInstructionsSection[] { +export function getRegisteredChaiMcpInstructions(): ChaiMcpInstructionsSection[] { const byId = new Map(); for (const sections of instructionsRegistry().values()) { for (const section of sections) byId.set(section.id, section); diff --git a/src/server/mcp/response.ts b/src/server/mcp/response.ts index c5c959336..25bf3458f 100644 --- a/src/server/mcp/response.ts +++ b/src/server/mcp/response.ts @@ -1,10 +1,11 @@ -import { toActionErrorPayload } from "~/server/chai-actions/action-result"; +import { toChaiActionErrorPayload } from "~/server/chai-actions/action-result"; import type { ChaiMcpToolResult } from "~/types/mcp"; /** * A tool result. MCP clients treat a result as success unless `isError` is set, and the * tools signal failure with an `Error:`-prefixed message, so that convention is * auto-flagged. An explicit `isError` always wins. + * @internal */ export function createChaiMcpResponse(text: string, opts?: { isError?: boolean }): ChaiMcpToolResult { const isError = opts?.isError ?? text.startsWith("Error:"); @@ -25,7 +26,7 @@ export function createChaiMcpResponse(text: string, opts?: { isError?: boolean } * error reaches the host through the audit hook. */ export function toSafeChaiMcpError(error: unknown, fallback = "The request could not be completed."): string { - const payload = toActionErrorPayload(error); + const payload = toChaiActionErrorPayload(error); if (payload.status >= 400 && payload.status < 500 && payload.message) { return `Error: ${payload.message}`; } diff --git a/src/server/plugin-api/index.ts b/src/server/plugin-api/index.ts index 4f08f413b..6a9105ab2 100644 --- a/src/server/plugin-api/index.ts +++ b/src/server/plugin-api/index.ts @@ -1,5 +1,5 @@ import "~/server/only-server"; -import { declaredPermissionKeysOf } from "~/server/chai-actions/permission-keys"; +import { getDeclaredChaiPermissionKeys } from "~/server/chai-actions/permission-keys"; import type { ChaiAction, ChaiRequiredPermission } from "~/types/chai-action"; import type { ChaiServerPlugin } from "~/types/plugin"; import type { @@ -47,14 +47,14 @@ export function setPluginMediaManager( /** * Assigns `requiredPermission` on an action instance and returns it (same as core's * `wp`). Also records `declaredPermissionKeys`; a payload-aware resolver must be - * built with `permissionResolver()` or this throws. + * built with `defineChaiPermissionResolver()` or this throws. */ -export function withActionPermission>( +export function withChaiActionPermission>( action: T, permission: ChaiRequiredPermission, ): T { action.requiredPermission = permission; - action.declaredPermissionKeys = declaredPermissionKeysOf(permission); + action.declaredPermissionKeys = getDeclaredChaiPermissionKeys(permission); return action; } @@ -67,7 +67,10 @@ export function withActionPermission>( * defaultRoleGrants: mergeDefaultRoleGrants(config.defaultRoleGrants, { editor: ["widgets:*"] }), * ``` */ -export function mergeDefaultRoleGrants(a: ChaiDefaultRoleGrants = {}, b: ChaiDefaultRoleGrants): ChaiDefaultRoleGrants { +export function mergeChaiDefaultRoleGrants( + a: ChaiDefaultRoleGrants = {}, + b: ChaiDefaultRoleGrants, +): ChaiDefaultRoleGrants { const out: ChaiDefaultRoleGrants = { ...a }; for (const [role, keys] of Object.entries(b)) { out[role] = [...new Set([...(out[role] ?? []), ...keys])]; diff --git a/src/server/plugin-api/permission-registry.ts b/src/server/plugin-api/permission-registry.ts index 919856ca6..e4489d605 100644 --- a/src/server/plugin-api/permission-registry.ts +++ b/src/server/plugin-api/permission-registry.ts @@ -4,7 +4,7 @@ * Plugins declare the keys they own by calling {@link registerChaiPermissions} * from their config reducer. Registration is keyed by owner, so re-running the * reducer (rebuilds, HMR) replaces rather than duplicates. The runtime RBAC - * catalog (`getPermissionCatalog`) is the union of the core catalog and every + * catalog (`getChaiPermissionCatalog`) is the union of the core catalog and every * registered set — there is no app-facing config key for this; the catalog * follows the plugins that are actually installed. */ diff --git a/src/server/plugin-api/plugin-api.test.ts b/src/server/plugin-api/plugin-api.test.ts index 73334efdd..cb5cd6660 100644 --- a/src/server/plugin-api/plugin-api.test.ts +++ b/src/server/plugin-api/plugin-api.test.ts @@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { buildChaiBuilderConfig } from "~/server/build-config"; import { getChaiAction } from "~/server/chai-actions/actions-registery"; import { schema } from "~/server/chai-actions/db"; -import { getChaiContextResolver, resetChaiContextResolverForTests } from "~/server/chai-context-resolver"; +import { getRegisteredChaiContextResolver, resetChaiContextResolverForTests } from "~/server/chai-context-resolver"; import { resolveChaiBuilderConfig } from "~/server/defaults"; import { resetActiveChaiBuilderConfigForTests } from "~/server/defaults/config-registry"; import { runInContext } from "~/server/chai-builder/state"; @@ -11,7 +11,7 @@ import { getChaiRequestHeader, getContributedChaiInstanceApis, getContributedChaiPermissions, - mergeDefaultRoleGrants, + mergeChaiDefaultRoleGrants, registerChaiInstanceApi, registerChaiPermissions, resetChaiInstanceApisForTests, @@ -106,11 +106,11 @@ describe("server plugins", () => { plugins: [ defineChaiServerPlugin((config) => ({ ...config, - defaultRoleGrants: mergeDefaultRoleGrants(config.defaultRoleGrants, { editor: ["first"] }), + defaultRoleGrants: mergeChaiDefaultRoleGrants(config.defaultRoleGrants, { editor: ["first"] }), })), defineChaiServerPlugin((config) => ({ ...config, - defaultRoleGrants: mergeDefaultRoleGrants(config.defaultRoleGrants, { + defaultRoleGrants: mergeChaiDefaultRoleGrants(config.defaultRoleGrants, { editor: [`after:${config.defaultRoleGrants?.editor?.join()}`], }), })), @@ -230,13 +230,13 @@ describe("server plugins", () => { plugins: [ defineChaiServerPlugin((config) => ({ ...config, - defaultRoleGrants: mergeDefaultRoleGrants(config.defaultRoleGrants, { + defaultRoleGrants: mergeChaiDefaultRoleGrants(config.defaultRoleGrants, { editor: ["widgets:read", "widgets:update"], }), })), defineChaiServerPlugin((config) => ({ ...config, - defaultRoleGrants: mergeDefaultRoleGrants(config.defaultRoleGrants, { + defaultRoleGrants: mergeChaiDefaultRoleGrants(config.defaultRoleGrants, { editor: ["gadgets:read", "widgets:read"], viewer: ["gadgets:read"], }), @@ -303,7 +303,7 @@ describe("server plugins", () => { ], }); - expect(getChaiContextResolver()).toBe(second); + expect(getRegisteredChaiContextResolver()).toBe(second); }); it("registers plugin request middleware and runs setup hooks with the resolved config", async () => { diff --git a/src/server/plugin-api/site-domains.ts b/src/server/plugin-api/site-domains.ts index 11fe6a8e3..cb5299c23 100644 --- a/src/server/plugin-api/site-domains.ts +++ b/src/server/plugin-api/site-domains.ts @@ -2,7 +2,7 @@ * Process-global site domain resolver. * * Where a site's domain and subdomain are stored belongs to the plugin that owns domains, not to - * core. Core's `resolveAppIdByHostname` and `getSiteDomains` keep their caching and errors and + * core. Core's `resolveChaiAppIdByHostname` and `getSiteDomains` keep their caching and errors and * ask the resolver registered here for the data. With no resolver registered, no hostname maps to * a site and no site has domains. * diff --git a/src/server/rbac/app-user-access.ts b/src/server/rbac/app-user-access.ts index b97775ae1..3bc3604c5 100644 --- a/src/server/rbac/app-user-access.ts +++ b/src/server/rbac/app-user-access.ts @@ -1,8 +1,8 @@ import { and, eq, isNull, or, sql } from "drizzle-orm"; import { db, safeQuery, schema } from "~/server/chai-actions/db"; -import { getGlobalRoles } from "./get-role-permissions"; -import { getPermissionCatalog } from "./permission-catalog"; -import { resolvePermissions } from "./resolve-permissions"; +import { getChaiGlobalRoles } from "./get-role-permissions"; +import { getChaiPermissionCatalog } from "./permission-catalog"; +import { resolveChaiPermissions } from "./resolve-permissions"; export type ChaiAppUserAccess = { /** Role name as stored on the membership row. */ @@ -32,9 +32,7 @@ export async function isChaiGlobalSuperAdmin(userId: string): Promise { db .select({ id: schema.appUsers.id }) .from(schema.appUsers) - .where( - and(isNull(schema.appUsers.app), eq(schema.appUsers.user, userId), eq(schema.appUsers.status, "active")), - ) + .where(and(isNull(schema.appUsers.app), eq(schema.appUsers.user, userId), eq(schema.appUsers.status, "active"))) .limit(1), ); @@ -94,17 +92,17 @@ export async function resolveChaiAppUserAccess({ if (!row) return null; const role = row.role || "user"; - const roleMap = await getGlobalRoles(); + const roleMap = await getChaiGlobalRoles(); return { role, - permissions: resolvePermissions({ + permissions: resolveChaiPermissions({ role, roleMap, - userOverride: row.permissions as Parameters[0]["userOverride"], + userOverride: row.permissions as Parameters[0]["userOverride"], // Runtime catalog, not the static list — plugin-contributed keys must // survive wildcard expansion. - catalog: getPermissionCatalog(), + catalog: getChaiPermissionCatalog(), }), }; } diff --git a/src/server/rbac/effective-permissions.ts b/src/server/rbac/effective-permissions.ts index d3d290703..1e971138f 100644 --- a/src/server/rbac/effective-permissions.ts +++ b/src/server/rbac/effective-permissions.ts @@ -1,5 +1,5 @@ -import { getPermissionCatalog } from "~/server/rbac/permission-catalog"; -import { intersectPermissions } from "~/server/rbac/permissions"; +import { getChaiPermissionCatalog } from "~/server/rbac/permission-catalog"; +import { intersectChaiPermissions } from "~/server/rbac/permissions"; /** Concrete (non-wildcard) permission keys — the only ones an intersection can match on. */ function concreteKeys(list: string[]): string[] { @@ -7,13 +7,13 @@ function concreteKeys(list: string[]): string[] { } /** - * `intersectPermissions` expands wildcards against a catalog, so anything outside that catalog + * `intersectChaiPermissions` expands wildcards against a catalog, so anything outside that catalog * (host-defined keys) would silently vanish from `["*"] ∩ [...]`. Base is the runtime catalog * (built-ins + plugin-registered keys), widened further with the concrete keys named by * either side so host keys never registered anywhere stay intersectable. */ export function delegationCatalog(granted: string[], delegated: string[]): string[] { - return [...new Set([...getPermissionCatalog(), ...concreteKeys(granted), ...concreteKeys(delegated)])]; + return [...new Set([...getChaiPermissionCatalog(), ...concreteKeys(granted), ...concreteKeys(delegated)])]; } /** @@ -27,7 +27,7 @@ export function delegationCatalog(granted: string[], delegated: string[]): strin export function resolveEffectivePermissions(granted: string[] | null, delegated: string[] | null): string[] { const permissions = granted ?? []; if (delegated === null) return permissions; - return intersectPermissions(permissions, delegated, delegationCatalog(permissions, delegated)); + return intersectChaiPermissions(permissions, delegated, delegationCatalog(permissions, delegated)); } /** Intersects two optional ceilings. `null` on either side means "no ceiling from that side". */ @@ -37,5 +37,5 @@ export function mergeDelegationCeilings( ): string[] | null { if (a === null || a === undefined) return b ?? null; if (b === null || b === undefined) return a; - return intersectPermissions(a, b, delegationCatalog(a, b)); + return intersectChaiPermissions(a, b, delegationCatalog(a, b)); } diff --git a/src/server/rbac/get-role-permissions.test.ts b/src/server/rbac/get-role-permissions.test.ts index 83583749e..6e1c65c14 100644 --- a/src/server/rbac/get-role-permissions.test.ts +++ b/src/server/rbac/get-role-permissions.test.ts @@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import type { ChaiRolesConfig } from "~/types/server-config"; import { withChaiConfig } from "~/tests/setup/chai-config"; import { DEFAULT_ROLE_MAPS } from "./default-roles"; -import { getGlobalRoles } from "./get-role-permissions"; +import { getChaiGlobalRoles } from "./get-role-permissions"; /** Sets the resolved `roles` value on the real active config. */ const setRoles = (roles: unknown) => withChaiConfig({ roles: roles as ChaiRolesConfig | undefined }); @@ -16,14 +16,14 @@ describe("getGlobalRoles", () => { it("returns DEFAULT_ROLE_MAPS when roles config is undefined", async () => { setRoles(undefined); - const result = await getGlobalRoles(); + const result = await getChaiGlobalRoles(); expect(result).toBe(DEFAULT_ROLE_MAPS); }); it("returns static roles map directly when provided in config", async () => { const staticRoles = { admin: { permissions: ["*"] }, viewer: { permissions: ["pages:read"] } }; setRoles(staticRoles); - const result = await getGlobalRoles(); + const result = await getChaiGlobalRoles(); expect(result).toBe(staticRoles); }); @@ -33,20 +33,20 @@ describe("getGlobalRoles", () => { const loader = vi.fn(async () => loaded); setRoles(loader); - const result = await getGlobalRoles(); + const result = await getChaiGlobalRoles(); expect(loader).toHaveBeenCalledOnce(); expect(result).toBe(loaded); }); it("falls back to defaults when the loader reports nothing stored (null)", async () => { setRoles(async () => null); - const result = await getGlobalRoles(); + const result = await getChaiGlobalRoles(); expect(result).toBe(DEFAULT_ROLE_MAPS); }); it("keeps a loader's empty map (fail closed on loader errors)", async () => { setRoles(async () => ({})); - const result = await getGlobalRoles(); + const result = await getChaiGlobalRoles(); expect(result).toEqual({}); }); @@ -55,8 +55,8 @@ describe("getGlobalRoles", () => { const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); setRoles({ source: "custom" }); - const first = await getGlobalRoles(); - await getGlobalRoles(); + const first = await getChaiGlobalRoles(); + await getChaiGlobalRoles(); expect(first).toBe(DEFAULT_ROLE_MAPS); // Warn-once flag is module state, so across this file it fires at most once. @@ -74,7 +74,7 @@ describe("getGlobalRoles + defaultRoleGrants (plugin-contributed)", () => { setRoles(undefined); setGrants({ editor: ["redirects:read", "redirects:create"] }); - const result = await getGlobalRoles(); + const result = await getChaiGlobalRoles(); expect(result.editor?.permissions).toEqual( expect.arrayContaining([...DEFAULT_ROLE_MAPS.editor!.permissions!, "redirects:read", "redirects:create"]), ); @@ -84,7 +84,7 @@ describe("getGlobalRoles + defaultRoleGrants (plugin-contributed)", () => { setRoles(async () => null); setGrants({ viewer: ["revisions:read"] }); - const result = await getGlobalRoles(); + const result = await getChaiGlobalRoles(); expect(result.viewer?.permissions).toContain("revisions:read"); }); @@ -93,7 +93,7 @@ describe("getGlobalRoles + defaultRoleGrants (plugin-contributed)", () => { setRoles(staticRoles); setGrants({ editor: ["redirects:read"] }); - const result = await getGlobalRoles(); + const result = await getChaiGlobalRoles(); expect(result).toBe(staticRoles); expect(result.editor?.permissions).not.toContain("redirects:read"); }); @@ -102,7 +102,7 @@ describe("getGlobalRoles + defaultRoleGrants (plugin-contributed)", () => { setRoles(async () => ({ editor: { permissions: ["pages:read"] } })); setGrants({ editor: ["redirects:read"] }); - const result = await getGlobalRoles(); + const result = await getChaiGlobalRoles(); expect(result.editor?.permissions).toEqual(["pages:read"]); }); @@ -110,7 +110,7 @@ describe("getGlobalRoles + defaultRoleGrants (plugin-contributed)", () => { setRoles(undefined); setGrants({ admin: ["redirects:read"] }); - const result = await getGlobalRoles(); + const result = await getChaiGlobalRoles(); expect(result.admin?.permissions).toEqual(["*"]); }); @@ -118,7 +118,7 @@ describe("getGlobalRoles + defaultRoleGrants (plugin-contributed)", () => { setRoles(undefined); setGrants({ ghost: ["redirects:read"] }); - const result = await getGlobalRoles(); + const result = await getChaiGlobalRoles(); expect(result.ghost).toBeUndefined(); }); @@ -126,7 +126,7 @@ describe("getGlobalRoles + defaultRoleGrants (plugin-contributed)", () => { setRoles(undefined); setGrants({ editor: ["redirects:read"] }); - await getGlobalRoles(); + await getChaiGlobalRoles(); expect(DEFAULT_ROLE_MAPS.editor?.permissions).not.toContain("redirects:read"); }); }); diff --git a/src/server/rbac/get-role-permissions.ts b/src/server/rbac/get-role-permissions.ts index 45ff9c20e..f1aa451e3 100644 --- a/src/server/rbac/get-role-permissions.ts +++ b/src/server/rbac/get-role-permissions.ts @@ -9,10 +9,7 @@ import type { ChaiRolesAndPermissions } from "./resolve-permissions"; * those sources own their grants (adopting a plugin there is a config edit or * a migration, like 20260715_150000_redirects_permissions). */ -function applyDefaultRoleGrants( - base: ChaiRolesAndPermissions, - grants: ChaiDefaultRoleGrants, -): ChaiRolesAndPermissions { +function applyDefaultRoleGrants(base: ChaiRolesAndPermissions, grants: ChaiDefaultRoleGrants): ChaiRolesAndPermissions { const entries = Object.entries(grants); if (entries.length === 0) return base; @@ -43,7 +40,7 @@ let warnedMissingRolesEngine = false; * returning `null` ("nothing stored") falls back to the defaults, preventing * lockout on fresh installs. */ -export async function getGlobalRoles(): Promise { +export async function getChaiGlobalRoles(): Promise { const configRoles = getConfigRoles(); if (!configRoles) return defaultsWithGrants(); diff --git a/src/server/rbac/permission-catalog.ts b/src/server/rbac/permission-catalog.ts index f3694c0eb..2adfecf07 100644 --- a/src/server/rbac/permission-catalog.ts +++ b/src/server/rbac/permission-catalog.ts @@ -10,6 +10,6 @@ import { CHAI_PERMISSION_LIST } from "./permissions"; * Lives apart from `permissions.ts` so the pure matching helpers stay free of * registry dependencies (they are public API). */ -export function getPermissionCatalog(): string[] { +export function getChaiPermissionCatalog(): string[] { return [...new Set([...CHAI_PERMISSION_LIST, ...getContributedChaiPermissions()])]; } diff --git a/src/server/rbac/permissions.test.ts b/src/server/rbac/permissions.test.ts index 87027c85d..52c1b96c9 100644 --- a/src/server/rbac/permissions.test.ts +++ b/src/server/rbac/permissions.test.ts @@ -1,64 +1,64 @@ import { describe, expect, it } from "vitest"; -import { expandGrantMap, hasPermission, intersectPermissions } from "./permissions"; +import { expandChaiGrantMap, hasChaiPermission, intersectChaiPermissions } from "./permissions"; describe("hasPermission", () => { it("returns true when no required permission", () => { - expect(hasPermission(null, "")).toBe(true); + expect(hasChaiPermission(null, "")).toBe(true); }); it("returns false when granted is empty", () => { - expect(hasPermission([], "pages:read")).toBe(false); - expect(hasPermission(null, "pages:read")).toBe(false); + expect(hasChaiPermission([], "pages:read")).toBe(false); + expect(hasChaiPermission(null, "pages:read")).toBe(false); }); it("matches exact permission", () => { - expect(hasPermission(["pages:read", "pages:create"], "pages:read")).toBe(true); + expect(hasChaiPermission(["pages:read", "pages:create"], "pages:read")).toBe(true); }); it("returns false when exact permission missing", () => { - expect(hasPermission(["pages:create"], "pages:read")).toBe(false); + expect(hasChaiPermission(["pages:create"], "pages:read")).toBe(false); }); it("matches wildcard-all *", () => { - expect(hasPermission(["*"], "pages:read")).toBe(true); - expect(hasPermission(["*"], "users:remove")).toBe(true); + expect(hasChaiPermission(["*"], "pages:read")).toBe(true); + expect(hasChaiPermission(["*"], "users:remove")).toBe(true); }); it("lets a retired key a stored role still grants satisfy its replacement", () => { - expect(hasPermission(["app:publish_theme"], "theme:publish")).toBe(true); - expect(hasPermission(["design_tokens:publish"], "theme:publish")).toBe(true); - expect(hasPermission(["app:*"], "theme:publish")).toBe(true); - expect(hasPermission(["app:publish_theme"], "theme:edit")).toBe(false); - expect(hasPermission(["theme:publish"], "app:publish_theme")).toBe(false); + expect(hasChaiPermission(["app:publish_theme"], "theme:publish")).toBe(true); + expect(hasChaiPermission(["design_tokens:publish"], "theme:publish")).toBe(true); + expect(hasChaiPermission(["app:*"], "theme:publish")).toBe(true); + expect(hasChaiPermission(["app:publish_theme"], "theme:edit")).toBe(false); + expect(hasChaiPermission(["theme:publish"], "app:publish_theme")).toBe(false); }); it("matches entity wildcard pages:*", () => { - expect(hasPermission(["pages:*"], "pages:read")).toBe(true); - expect(hasPermission(["pages:*"], "pages:delete")).toBe(true); - expect(hasPermission(["pages:*"], "assets:read")).toBe(false); + expect(hasChaiPermission(["pages:*"], "pages:read")).toBe(true); + expect(hasChaiPermission(["pages:*"], "pages:delete")).toBe(true); + expect(hasChaiPermission(["pages:*"], "assets:read")).toBe(false); }); }); describe("expandGrantMap", () => { it("returns empty array for null/undefined", () => { - expect(expandGrantMap(null)).toEqual([]); - expect(expandGrantMap(undefined)).toEqual([]); + expect(expandChaiGrantMap(null)).toEqual([]); + expect(expandChaiGrantMap(undefined)).toEqual([]); }); it("expands * to full catalog", () => { - const result = expandGrantMap({ "*": true }, ["pages:read", "pages:create", "assets:read"]); + const result = expandChaiGrantMap({ "*": true }, ["pages:read", "pages:create", "assets:read"]); expect(result).toEqual(expect.arrayContaining(["pages:read", "pages:create", "assets:read"])); }); it("expands entity:* to entity ops only", () => { - const result = expandGrantMap({ "pages:*": true }, ["pages:read", "pages:create", "assets:read"]); + const result = expandChaiGrantMap({ "pages:*": true }, ["pages:read", "pages:create", "assets:read"]); expect(result).toContain("pages:read"); expect(result).toContain("pages:create"); expect(result).not.toContain("assets:read"); }); it("grants explicit keys", () => { - const result = expandGrantMap({ "pages:read": true, "assets:read": true }, [ + const result = expandChaiGrantMap({ "pages:read": true, "assets:read": true }, [ "pages:read", "pages:create", "assets:read", @@ -68,13 +68,17 @@ describe("expandGrantMap", () => { }); it("revoke false wins over wildcard grant", () => { - const result = expandGrantMap({ "*": true, "pages:delete": false }, ["pages:read", "pages:delete", "assets:read"]); + const result = expandChaiGrantMap({ "*": true, "pages:delete": false }, [ + "pages:read", + "pages:delete", + "assets:read", + ]); expect(result).toContain("pages:read"); expect(result).not.toContain("pages:delete"); }); it("revokes entity:* after wildcard-all grant", () => { - const result = expandGrantMap({ "*": true, "pages:*": false }, ["pages:read", "pages:create", "assets:read"]); + const result = expandChaiGrantMap({ "*": true, "pages:*": false }, ["pages:read", "pages:create", "assets:read"]); expect(result).not.toContain("pages:read"); expect(result).not.toContain("pages:create"); expect(result).toContain("assets:read"); @@ -85,24 +89,24 @@ describe("intersectPermissions", () => { const catalog = ["pages:read", "pages:create", "pages:delete", "assets:read"]; it("returns intersection of two concrete lists", () => { - expect(intersectPermissions(["pages:read", "pages:create"], ["pages:read", "assets:read"], catalog)).toEqual([ + expect(intersectChaiPermissions(["pages:read", "pages:create"], ["pages:read", "assets:read"], catalog)).toEqual([ "pages:read", ]); }); it("expands wildcards before intersecting", () => { - const result = intersectPermissions(["pages:*"], ["pages:read", "assets:read"], catalog); + const result = intersectChaiPermissions(["pages:*"], ["pages:read", "assets:read"], catalog); expect(result).toContain("pages:read"); expect(result).not.toContain("assets:read"); expect(result).not.toContain("pages:create"); }); it("returns empty when no overlap", () => { - expect(intersectPermissions(["pages:create"], ["assets:read"], catalog)).toEqual([]); + expect(intersectChaiPermissions(["pages:create"], ["assets:read"], catalog)).toEqual([]); }); it("returns full catalog when both sides are *", () => { - const result = intersectPermissions(["*"], ["*"], catalog); + const result = intersectChaiPermissions(["*"], ["*"], catalog); expect(result).toEqual(expect.arrayContaining(catalog)); }); }); diff --git a/src/server/rbac/permissions.ts b/src/server/rbac/permissions.ts index 79f922b5a..544a531d2 100644 --- a/src/server/rbac/permissions.ts +++ b/src/server/rbac/permissions.ts @@ -28,13 +28,13 @@ function entityOf(permission: string): string { * Wildcard-aware: `*` matches everything, `entity:*` matches any op in the entity. * A retired key a stored role still grants satisfies its replacement (`LEGACY_PERMISSION_ALIASES`). */ -export function hasPermission(granted: string[] | null | undefined, required: string): boolean { +export function hasChaiPermission(granted: string[] | null | undefined, required: string): boolean { if (!required) return true; if (!granted || granted.length === 0) return false; if (granted.includes(WILDCARD_ALL)) return true; if (granted.includes(required)) return true; if (granted.includes(`${entityOf(required)}:*`)) return true; - return legacyAliasesOf(required).some((legacy) => hasPermission(granted, legacy)); + return legacyAliasesOf(required).some((legacy) => hasChaiPermission(granted, legacy)); } /** @@ -42,7 +42,7 @@ export function hasPermission(granted: string[] | null | undefined, required: st * catalog-bounded list of granted permission keys. `false` entries revoke a key * that an earlier wildcard granted. */ -export function expandGrantMap( +export function expandChaiGrantMap( map: Record | null | undefined, catalog: string[] = CHAI_PERMISSION_LIST, ): string[] { @@ -85,7 +85,7 @@ export function expandGrantMap( * compute the effective permission set for MCP requests: * effective = userPermissions ∩ delegatedScopes */ -export function intersectPermissions(a: string[], b: string[], catalog: string[] = CHAI_PERMISSION_LIST): string[] { +export function intersectChaiPermissions(a: string[], b: string[], catalog: string[] = CHAI_PERMISSION_LIST): string[] { const expand = (list: string[]): Set => { const out = new Set(); for (const key of list) { diff --git a/src/server/rbac/resolve-permissions.test.ts b/src/server/rbac/resolve-permissions.test.ts index 2fc557b42..55aa29255 100644 --- a/src/server/rbac/resolve-permissions.test.ts +++ b/src/server/rbac/resolve-permissions.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { resolvePermissions } from "./resolve-permissions"; +import { resolveChaiPermissions } from "./resolve-permissions"; const catalog = ["pages:read", "pages:create", "pages:delete", "assets:read", "assets:delete", "users:remove"]; @@ -11,12 +11,12 @@ const roleMap = { describe("resolvePermissions", () => { it("returns role permissions from roleMap", () => { - const result = resolvePermissions({ role: "viewer", roleMap, catalog }); + const result = resolveChaiPermissions({ role: "viewer", roleMap, catalog }); expect(result).toEqual(["pages:read"]); }); it("expands entity wildcard from role", () => { - const result = resolvePermissions({ role: "editor", roleMap, catalog }); + const result = resolveChaiPermissions({ role: "editor", roleMap, catalog }); expect(result).toContain("pages:read"); expect(result).toContain("pages:create"); expect(result).toContain("pages:delete"); @@ -25,22 +25,22 @@ describe("resolvePermissions", () => { }); it("expands * from admin role", () => { - const result = resolvePermissions({ role: "admin", roleMap, catalog }); + const result = resolveChaiPermissions({ role: "admin", roleMap, catalog }); expect(result).toEqual(expect.arrayContaining(catalog)); }); it("returns empty for unknown role with no roleMap entry", () => { - const result = resolvePermissions({ role: "ghost", roleMap, catalog }); + const result = resolveChaiPermissions({ role: "ghost", roleMap, catalog }); expect(result).toEqual([]); }); it("returns defaults when roleMap is null", () => { - const result = resolvePermissions({ role: "viewer", roleMap: null, catalog }); + const result = resolveChaiPermissions({ role: "viewer", roleMap: null, catalog }); expect(result).toEqual([]); }); it("applies array-form userOverride as additive grants", () => { - const result = resolvePermissions({ + const result = resolveChaiPermissions({ role: "viewer", roleMap, catalog, @@ -51,7 +51,7 @@ describe("resolvePermissions", () => { }); it("applies map-form userOverride true to grant", () => { - const result = resolvePermissions({ + const result = resolveChaiPermissions({ role: "viewer", roleMap, catalog, @@ -62,7 +62,7 @@ describe("resolvePermissions", () => { }); it("applies map-form userOverride false to revoke", () => { - const result = resolvePermissions({ + const result = resolveChaiPermissions({ role: "editor", roleMap, catalog, @@ -73,7 +73,7 @@ describe("resolvePermissions", () => { }); it("revoke wins over entity wildcard grant", () => { - const result = resolvePermissions({ + const result = resolveChaiPermissions({ role: "admin", roleMap, catalog, @@ -83,7 +83,7 @@ describe("resolvePermissions", () => { }); it("userOverride entity:* revokes all ops in entity", () => { - const result = resolvePermissions({ + const result = resolveChaiPermissions({ role: "admin", roleMap, catalog, diff --git a/src/server/rbac/resolve-permissions.ts b/src/server/rbac/resolve-permissions.ts index 9135b9e4c..f6eda7a42 100644 --- a/src/server/rbac/resolve-permissions.ts +++ b/src/server/rbac/resolve-permissions.ts @@ -1,13 +1,9 @@ -import { CHAI_PERMISSION_LIST, expandGrantMap } from "./permissions"; -import type { - ChaiRoleGrantMap, - ChaiRolesAndPermissions, - ChaiUserPermissionOverride, -} from "~/types/rbac"; +import { CHAI_PERMISSION_LIST, expandChaiGrantMap } from "./permissions"; +import type { ChaiRoleGrantMap, ChaiRolesAndPermissions, ChaiUserPermissionOverride } from "~/types/rbac"; export type { ChaiRoleGrantMap, - ChaiRoleEntry, + ChaiRoleGrant, ChaiRolesAndPermissions, ChaiUserPermissionOverride, } from "~/types/rbac"; @@ -53,7 +49,7 @@ function expandPermissionList(list: string[], catalog: string[]): string[] { return [...out]; } -export function resolvePermissions({ +export function resolveChaiPermissions({ role, roleMap, userOverride, @@ -67,9 +63,9 @@ export function resolvePermissions({ for (const [key, allowed] of Object.entries(overrideMap)) { if (allowed === true) { // Re-expand the single key (supports `entity:*`). - expandGrantMap({ [key]: true }, catalog).forEach((perm) => granted.add(perm)); + expandChaiGrantMap({ [key]: true }, catalog).forEach((perm) => granted.add(perm)); } else if (allowed === false) { - expandGrantMap({ [key]: true }, catalog).forEach((perm) => granted.delete(perm)); + expandChaiGrantMap({ [key]: true }, catalog).forEach((perm) => granted.delete(perm)); } } } diff --git a/src/server/repeater-data/fetch-repeater-items.test.ts b/src/server/repeater-data/fetch-repeater-items.test.ts index c9bfb2ddf..a9db91267 100644 --- a/src/server/repeater-data/fetch-repeater-items.test.ts +++ b/src/server/repeater-data/fetch-repeater-items.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from "vitest"; import { useTestChaiConfig } from "~/tests/setup/chai-config"; -import type { ChaiCollectionEntry } from "~/types/chaibuilder-config"; +import type { ChaiCollectionEntry } from "~/types/deprecated"; import type { ChaiBlock } from "~/types/common"; import type { ChaiRepeaterDataEntry } from "~/types/repeater-data"; import { fetchRepeaterItems } from "./fetch-repeater-items"; diff --git a/src/server/repeater-data/resolve-source.ts b/src/server/repeater-data/resolve-source.ts index 2a8c88f4e..8aa2ef15e 100644 --- a/src/server/repeater-data/resolve-source.ts +++ b/src/server/repeater-data/resolve-source.ts @@ -1,5 +1,5 @@ import { getConfigCollection, getConfigRepeaterDataSource } from "~/server/defaults/config-registry"; -import type { ChaiCollectionEntry } from "~/types/chaibuilder-config"; +import type { ChaiCollectionEntry } from "~/types/deprecated"; import type { ChaiRepeaterDataEntry } from "~/types/repeater-data"; export type ResolvedRepeaterSource = diff --git a/src/server/resolve-chai-context.test.ts b/src/server/resolve-chai-context.test.ts index e37b6d00a..a07eec86c 100644 --- a/src/server/resolve-chai-context.test.ts +++ b/src/server/resolve-chai-context.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { resetChaiContextResolverForTests, setChaiContextResolver } from "~/server/chai-context-resolver"; +import { resetChaiContextResolverForTests, registerChaiContextResolver } from "~/server/chai-context-resolver"; import { resetSharedChaiRequestContextForTests, resolveChaiContextViaResolver, @@ -26,7 +26,7 @@ describe("resolveChaiContextViaResolver", () => { }); it("captures the request headers accessor for plugins only when a request is present", async () => { - setChaiContextResolver(async () => ({ userId: "user-1" })); + registerChaiContextResolver(async () => ({ userId: "user-1" })); const withRequest = await resolveChaiContextViaResolver({ request: request({ "x-hint": "a, b" }) }); expect(withRequest.requestHeaders?.get("x-hint")).toBe("a, b"); @@ -37,7 +37,7 @@ describe("resolveChaiContextViaResolver", () => { }); it("carries host-supplied permissions and role onto the context", async () => { - setChaiContextResolver(async () => ({ userId: "user-1", role: "editor", permissions: ["pages:read"] })); + registerChaiContextResolver(async () => ({ userId: "user-1", role: "editor", permissions: ["pages:read"] })); const context = await resolveChaiContextViaResolver({}); @@ -45,7 +45,7 @@ describe("resolveChaiContextViaResolver", () => { }); it("accepts the deprecated delegatedScopes name and mirrors it onto delegatedPermissions", async () => { - setChaiContextResolver(async () => ({ delegatedScopes: ["pages:read"] })); + registerChaiContextResolver(async () => ({ delegatedScopes: ["pages:read"] })); const context = await resolveChaiContextViaResolver({}); @@ -54,7 +54,7 @@ describe("resolveChaiContextViaResolver", () => { }); it("mirrors delegatedPermissions back onto the deprecated name", async () => { - setChaiContextResolver(async () => ({ delegatedPermissions: ["assets:read"] })); + registerChaiContextResolver(async () => ({ delegatedPermissions: ["assets:read"] })); const context = await resolveChaiContextViaResolver({}); @@ -63,7 +63,7 @@ describe("resolveChaiContextViaResolver", () => { }); it("prefers delegatedPermissions when both names are returned", async () => { - setChaiContextResolver(async () => ({ + registerChaiContextResolver(async () => ({ delegatedPermissions: ["pages:read"], delegatedScopes: ["pages:*"], })); @@ -75,7 +75,7 @@ describe("resolveChaiContextViaResolver", () => { }); it("leaves delegation unset when the resolver names neither field", async () => { - setChaiContextResolver(async () => ({ userId: "user-1" })); + registerChaiContextResolver(async () => ({ userId: "user-1" })); const context = await resolveChaiContextViaResolver({}); @@ -99,7 +99,7 @@ describe("resolveSharedChaiContext re-entrancy", () => { // Models Payload auth: the resolver triggers a hook that calls getChaiBuilder() again. // Pre-guard this recursed forever (the nested call re-ran the resolver, which re-ran auth). let calls = 0; - setChaiContextResolver(async () => { + registerChaiContextResolver(async () => { calls++; if (calls > 5) throw new Error("resolver recursed"); const nested = await resolveSharedChaiContext(); @@ -114,7 +114,7 @@ describe("resolveSharedChaiContext re-entrancy", () => { }); it("does not cache the nested static default as the shared request context", async () => { - setChaiContextResolver(async () => { + registerChaiContextResolver(async () => { await resolveSharedChaiContext(); return { appId: "app-1", userId: "user-1" }; }); @@ -127,13 +127,13 @@ describe("resolveSharedChaiContext re-entrancy", () => { }); it("clears the guard when the resolver throws", async () => { - setChaiContextResolver(async () => { + registerChaiContextResolver(async () => { throw new Error("boom"); }); await expect(resolveSharedChaiContext({ params: Promise.resolve({}) } as any)).rejects.toThrow("boom"); - setChaiContextResolver(async () => ({ appId: "app-2", userId: "user-2" })); + registerChaiContextResolver(async () => ({ appId: "app-2", userId: "user-2" })); const context = await resolveSharedChaiContext(); expect(context).toMatchObject({ appId: "app-2", userId: "user-2" }); }); diff --git a/src/server/resolve-chai-context.ts b/src/server/resolve-chai-context.ts index 02d62d636..0674d6d6a 100644 --- a/src/server/resolve-chai-context.ts +++ b/src/server/resolve-chai-context.ts @@ -1,6 +1,6 @@ import { AsyncLocalStorage } from "async_hooks"; import { cache } from "react"; -import { getChaiContextResolver, staticDefaultChaiContext } from "~/server/chai-context-resolver"; +import { getRegisteredChaiContextResolver, createStaticChaiContext } from "~/server/chai-context-resolver"; import type { ChaiBuilderRouteProps, ChaiContextResolverArgs, @@ -48,7 +48,7 @@ export function resetSharedChaiRequestContextForTests(): void { * MCP tools, and any non-request environment. */ export async function resolveDefaultChaiContext(overrides?: Partial): Promise { - return staticDefaultChaiContext(overrides); + return createStaticChaiContext(overrides); } /** @@ -56,8 +56,8 @@ export async function resolveDefaultChaiContext(overrides?: Partial { - const resolver = getChaiContextResolver(); - const base = staticDefaultChaiContext(); + const resolver = getRegisteredChaiContextResolver(); + const base = createStaticChaiContext(); if (!resolver) { return withRequestContext(base, args.request); } @@ -157,11 +157,11 @@ export async function resolveSharedChaiContext( // The nested call gets the static default (unauthenticated) context instead; it is not // cached, so the outer resolve still stores the real context when it completes. if (resolvingGuard.getStore()) { - return staticDefaultChaiContext(); + return createStaticChaiContext(); } if (routeProps !== undefined) { - if (!getChaiContextResolver()) { + if (!getRegisteredChaiContextResolver()) { throw new Error( "ChaiBuilder: route props require a context resolver. Create the server handle with `createChaiBuilder(config, { context })` and call the `getChaiBuilder` it returns, or call `getChaiBuilder(config)` without route props.", ); @@ -175,9 +175,9 @@ export async function resolveSharedChaiContext( return state.context; } - const ctx = getChaiContextResolver() + const ctx = getRegisteredChaiContextResolver() ? await resolvingGuard.run(true, () => resolveChaiContextViaResolver({})) - : staticDefaultChaiContext(); + : createStaticChaiContext(); state.context = ctx; return ctx; } diff --git a/src/tests/setup/chai-config.ts b/src/tests/setup/chai-config.ts index 7b53f872c..0002baf78 100644 --- a/src/tests/setup/chai-config.ts +++ b/src/tests/setup/chai-config.ts @@ -1,9 +1,9 @@ import { editionTestServerPlugins } from "~/edition/test-harness"; -import { getAllRegisteredChaiBlocks } from "~/registry/v2/runtime/core"; +import { getRegisteredChaiBlocks } from "~/registry/v2/runtime/core"; import type { ChaiDbSetup } from "~/db/core"; import { buildChaiBuilderConfig } from "~/server/build-config"; import { resetChaiBuilderCoreForTests } from "~/server/get-chaibuilder"; -import { resetChaiContextResolverForTests, setChaiContextResolver } from "~/server/chai-context-resolver"; +import { resetChaiContextResolverForTests, registerChaiContextResolver } from "~/server/chai-context-resolver"; import { getActiveChaiBuilderConfig, setActiveChaiBuilderConfig } from "~/server/defaults/config-registry"; import type { ChaiBuilderServerConfigInput, ResolvedChaiBuilderServerConfig } from "~/server/defaults/types"; import { @@ -24,7 +24,7 @@ const blockEntriesBeforeConfig = new Map(); * harness restores the worker database after the test. */ export function useTestChaiConfig(input: Partial & { db?: ChaiDbSetup } = {}) { - const registry = getAllRegisteredChaiBlocks() as Record; + const registry = getRegisteredChaiBlocks() as Record; const before = { ...registry }; const config = buildChaiBuilderConfig({ ...input, @@ -54,7 +54,7 @@ blockEntriesBeforeConfig.clear(); /** Undoes the process-global runtime a test's `useTestChaiConfig` registered beyond the baseline. */ function restoreBaseRuntime(): void { - const registry = getAllRegisteredChaiBlocks() as Record; + const registry = getRegisteredChaiBlocks() as Record; for (const [type, entry] of blockEntriesBeforeConfig) { if (entry === undefined) delete registry[type]; else registry[type] = entry; @@ -62,7 +62,7 @@ function restoreBaseRuntime(): void { blockEntriesBeforeConfig.clear(); resetChaiContextResolverForTests(); - if (baseConfig.contextResolver) setChaiContextResolver(baseConfig.contextResolver); + if (baseConfig.contextResolver) registerChaiContextResolver(baseConfig.contextResolver); resetChaiRequestMiddlewareForTests(); for (const { name, handler } of baseConfig.requestMiddlewares) registerChaiRequestMiddleware(name, handler); } diff --git a/src/tests/setup/mcp.ts b/src/tests/setup/mcp.ts index 9de5aa4b0..9da097e51 100644 --- a/src/tests/setup/mcp.ts +++ b/src/tests/setup/mcp.ts @@ -1,5 +1,5 @@ import { runInFreshContext } from "~/server/chai-builder/state"; -import { setChaiContextResolver } from "~/server/chai-context-resolver"; +import { registerChaiContextResolver } from "~/server/chai-context-resolver"; import { getActiveChaiBuilderConfig } from "~/server/defaults/config-registry"; import { getChaiBuilder, resetChaiBuilderCoreForTests } from "~/server/get-chaibuilder"; import { runWithChaiMcpRequest, runWithChaiMcpToolContext } from "~/server/mcp/request-context"; @@ -34,7 +34,7 @@ export async function withMcpRequest( const context = testRequestContext({ permissions: ["*"], surface: "mcp", ...contextOverrides, draft: true }); // The harness restores the edition's own resolver after every test. - setChaiContextResolver(async () => context); + registerChaiContextResolver(async () => context); resetSharedChaiRequestContextForTests(); resetChaiBuilderCoreForTests(); try { diff --git a/src/tests/setup/stub-chai-db.ts b/src/tests/setup/stub-chai-db.ts index 4bcec66fa..603e642d7 100644 --- a/src/tests/setup/stub-chai-db.ts +++ b/src/tests/setup/stub-chai-db.ts @@ -1,7 +1,7 @@ -import type { DbInstance, ChaiDbSetup } from "~/db/core"; +import type { ChaiDbInstance, ChaiDbSetup } from "~/db/core"; import * as coreSchema from "~/drizzle/schema.sqlite"; -const STUB_DRIZZLE = {} as DbInstance; +const STUB_DRIZZLE = {} as ChaiDbInstance; /** Unit tests: avoids opening a real DB when calling `buildChaiBuilderConfig` (do not query through Chai `db`). */ export function stubChaiDbSetup(): ChaiDbSetup { diff --git a/src/tests/setup/test-db.ts b/src/tests/setup/test-db.ts index c86d2e7c4..b8204974c 100644 --- a/src/tests/setup/test-db.ts +++ b/src/tests/setup/test-db.ts @@ -1,7 +1,7 @@ import Database from "better-sqlite3"; import { drizzle, type BetterSQLite3Database } from "drizzle-orm/better-sqlite3"; -import { createBetterSqliteDB } from "~/db/better-sqlite3"; -import { registerDb, type ChaiDbSetup } from "~/db/core"; +import { createBetterSqliteDb } from "~/db/better-sqlite3"; +import { registerChaiDb, type ChaiDbSetup } from "~/db/core"; import * as schema from "~/edition/test-schema"; export type TestDb = BetterSQLite3Database; @@ -29,12 +29,12 @@ export function getTestDb(): TestDb { /** The same database as a ChaiBuilder `db` setup — what `buildChaiBuilderConfig({ db })` receives. */ export function getTestDbSetup(): ChaiDbSetup { - return (setup ??= createBetterSqliteDB({ drizzle: getTestDb(), schema })); + return (setup ??= createBetterSqliteDb({ drizzle: getTestDb(), schema })); } /** Points ChaiBuilder's `db` singleton at the worker's real in-memory database. */ export function registerTestDb(): void { - registerDb(getTestDbSetup()); + registerChaiDb(getTestDbSetup()); } export { schema }; diff --git a/src/types/actions.ts b/src/types/actions.ts index 0bbded88d..8f1a9c775 100644 --- a/src/types/actions.ts +++ b/src/types/actions.ts @@ -4,7 +4,7 @@ import type { ChaiBlock } from "~/types/common"; import type { ChaiTheme } from "./chaibuilder-editor-props"; import type { ChaiDesignTokens } from "./types"; -export type ChaiWebsiteSetting = { +export type ChaiSiteSettings = { appKey: string; fallbackLang: string; languages: string[]; @@ -166,37 +166,37 @@ export type ChaiAsset = { height?: number; }; -export type AssetsParams = { +export type ChaiListAssetsArgs = { search: string; limit: number; page: number; }; -export type ImageConfig = { +export type ChaiImageConfig = { lastImage?: string; aspectRatio?: "1:1" | "3:4" | "4:3" | "9:16" | "16:9"; quality?: number; }; -export type AIChatOptions = { +export type ChaiAiChatOptions = { messages: any[]; - image?: ImageConfig; + image?: ChaiImageConfig; systemPrompt?: string; initiator?: string | null; model?: string; - context?: AIContext; + context?: ChaiAiContext; designTokens?: ChaiDesignTokens; images?: string[]; attachments?: { url?: string; mediaType?: string; filename?: string }[]; options?: Record; }; -export type AIContext = { +export type ChaiAiContext = { site?: Record; page?: Record; }; -export interface ChaiBuilderPagesAIInterface { - handleRequest(options: AIChatOptions, res: any): Promise>; +export interface ChaiPagesAiHandler { + handleRequest(options: ChaiAiChatOptions, res: any): Promise>; isConfigured(): boolean; } diff --git a/src/types/ai-config.ts b/src/types/ai-config.ts index 832c55bc3..7a2288d4d 100644 --- a/src/types/ai-config.ts +++ b/src/types/ai-config.ts @@ -1,11 +1,11 @@ import type { ImageModel, LanguageModel } from "ai"; import type { AIModel } from "~/builder/pages/panels/ai-panel/ai-models-context"; -import type { ResolvedChaiAIGlobalConfig } from "~/types/server-config"; +import type { ResolvedChaiAiGlobalConfig } from "~/types/server-config"; -export type { LogAiRequestParams, ResolvedChaiAIGlobalConfig } from "~/types/server-config"; +export type { ChaiLogAiRequestArgs, ResolvedChaiAiGlobalConfig } from "~/types/server-config"; /** Partial AI config for input; use ResolvedChaiAIGlobalConfig after buildChaiBuilderConfig. */ -export type ChaiAIGlobalConfig = Partial & { +export type ChaiAiGlobalConfig = Partial & { models?: AIModel[]; resolveModel?: ( modelKey: string, diff --git a/src/types/chai-action.ts b/src/types/chai-action.ts index af7d46ee5..11f446b5e 100644 --- a/src/types/chai-action.ts +++ b/src/types/chai-action.ts @@ -18,7 +18,7 @@ export interface ChaiActionContext { appId: string; userId?: string; /** - * Effective access for this request, set by `dispatchChaiAction` on authenticated actions: + * Effective access for this request, set by `runChaiAction` on authenticated actions: * host-supplied context permissions or the resolved `app_users` membership, already clamped * by {@link delegatedPermissions}. Actions that resolve access themselves should return this * when present rather than looking it up again. @@ -52,7 +52,7 @@ export type ChaiRequiredPermission = string | string[] | ChaiPermission /** * The function form of {@link ChaiRequiredPermission}. `declaredPermissionKeys` * is the static superset of every key the resolver may return, for audits that - * inspect permissions without dispatching. Build with `permissionResolver()` + * inspect permissions without dispatching. Build with `defineChaiPermissionResolver()` * (`~/server/chai-actions/permission-keys`) rather than setting it by hand. */ export type ChaiPermissionResolver = { @@ -66,13 +66,13 @@ export type ChaiPermissionResolver = { */ export interface ChaiAction { /** - * Permission required to run this action. Enforced by `dispatchChaiAction`. + * Permission required to run this action. Enforced by `runChaiAction`. * Undeclared (undefined) = authenticated-only (no specific permission). */ requiredPermission?: ChaiRequiredPermission; /** * Every permission key {@link requiredPermission} may require, whatever the - * payload. Set by `withActionPermission`; do not assign it by hand. + * payload. Set by `withChaiActionPermission`; do not assign it by hand. */ declaredPermissionKeys?: string[]; validate(data: T): boolean; diff --git a/src/types/chaibuilder-config.ts b/src/types/chaibuilder-config.ts index c8d8af3fa..ef731d181 100644 --- a/src/types/chaibuilder-config.ts +++ b/src/types/chaibuilder-config.ts @@ -1,6 +1,5 @@ import type { ChaiPageType } from "~/types/actions"; import type { ChaiActionSurface } from "~/types/chai-action"; -import type { CollectionConfig } from "~/types/collection-config"; import type { ChaiBlock, ChaiPageProps } from "~/types/common"; import type { ChaiTrashableEntity } from "~/types/trash"; @@ -125,25 +124,6 @@ export type ChaiContextResolver, ) => Partial | Promise>; -/** - * @deprecated Context passed to the removed `resolveSiteUrl` config option. - * Resolve `siteUrl` inside your {@link ChaiContextResolver} instead. - */ -export type ChaiResolveSiteUrlContext = { - appId: string; -}; - -/** @deprecated Use {@link ChaiContextResolverArgs}. */ -export type ChaiRequestContextArgs = { - routeProps: ChaiBuilderRouteProps; - request?: Req; -}; - -/** @deprecated Use {@link ChaiContextResolver}. */ -export type ChaiRequestContextResolver = ( - args: ChaiRequestContextArgs, -) => Partial | Promise>; - /** * Same shape as Next.js App Router route component props (`page` / `layout` / `generateMetadata`). * `params` / `searchParams` may be `Promise`s (Next 15+) or plain objects. @@ -247,11 +227,7 @@ export type ChaiUpstreamPageSource = { * Page `id` if site `appId` may link it on `userId`'s behalf, else null. Gates creating a * linked page and resetting a clone back to its upstream page. */ - findLinkable(args: { - id: string; - appId: string; - userId: string; - }): Promise<{ + findLinkable(args: { id: string; appId: string; userId: string }): Promise<{ id: string; name: string; pageType: string | null; @@ -276,12 +252,6 @@ export type ChaiPageTypeEntry = ChaiPageType & { partial?: boolean; }; -/** - * Collection entry - * @deprecated Use `ChaiRepeaterDataEntry` instead. - */ -export type ChaiCollectionEntry = CollectionConfig; - export type { ChaiRepeaterDataEntry } from "~/types/repeater-data"; /** @@ -334,7 +304,7 @@ export type { ChaiBuilderServerConfigInput, ChaiDbConfigInput, ChaiDbSetup, - ResolvedChaiAIGlobalConfig, + ResolvedChaiAiGlobalConfig, ResolvedChaiBuilderServerConfig, ResolvedChaiDbConfig, } from "~/types/server-config"; diff --git a/src/types/chaibuilder-editor-props.ts b/src/types/chaibuilder-editor-props.ts index 2280978ca..50a09c5da 100644 --- a/src/types/chaibuilder-editor-props.ts +++ b/src/types/chaibuilder-editor-props.ts @@ -3,7 +3,7 @@ import { StructureRule } from "~/builder/hooks/structure-rules"; import { ChaiPage } from "~/builder/pages/utils/page-organization"; import { ChaiBlock } from "~/types/common"; import { ChaiLoggedInUser, ChaiPageType } from "./actions"; -import { ChaiCollectoin } from "./collections"; +import type { ChaiCollectoin } from "./deprecated"; import { ChaiRepeaterDataDefinition } from "./repeater-data"; import { ChaiDesignTokens, ChaiSiteWideUsageData } from "./types"; @@ -51,7 +51,7 @@ export type ChaiBreakpoint = { width: number; }; -export type ChaiSavePageData = { +export type ChaiSavePageArgs = { autoSave: boolean; blocks: ChaiBlock[]; needTranslations?: boolean; @@ -60,7 +60,7 @@ export type ChaiSavePageData = { linkPageIds?: string[]; }; -export type ChaiSaveWebsiteData = +export type ChaiSaveSiteArgs = | { type: "THEME"; data: ChaiTheme } | { type: "DESIGN_TOKENS"; data: ChaiDesignTokens } | { @@ -68,7 +68,7 @@ export type ChaiSaveWebsiteData = data: { theme: ChaiTheme; designTokens: ChaiDesignTokens }; }; -export type ChaiAskAiResponse = { +export type ChaiAskAiResult = { blocks?: Array<{ _id: string } & Partial>; usage?: Record; error?: any; @@ -275,7 +275,7 @@ export interface ChaiBuilderEditorProps { prompt: string, blocks: ChaiBlock[], lang: string, - ) => Promise; + ) => Promise; /** * Get partial blocks @@ -299,13 +299,13 @@ export interface ChaiBuilderEditorProps { * onSave callback function * @param saveData */ - onSave?: ({ blocks, autoSave }: ChaiSavePageData) => Promise; + onSave?: ({ blocks, autoSave }: ChaiSavePageArgs) => Promise; /** * onSaveWebsiteData callback function for theme and design tokens * @param saveData */ - onSaveWebsiteData?: (data: ChaiSaveWebsiteData) => Promise; + onSaveWebsiteData?: (data: ChaiSaveSiteArgs) => Promise; /** * onSaveStateChange callback function diff --git a/src/types/chaibuilder-instance.ts b/src/types/chaibuilder-instance.ts index 7172ffb07..3be022d63 100644 --- a/src/types/chaibuilder-instance.ts +++ b/src/types/chaibuilder-instance.ts @@ -1,11 +1,11 @@ import type { ChaiCoreSchema } from "~/db/schema-shape"; -import type { ChaiDbContext, DbInstance, DbResult } from "~/server/chai-actions/db"; +import type { ChaiDbContext, ChaiDbInstance, ChaiDbResult } from "~/server/chai-actions/db"; import type { - CreateRoleActionData, - DeleteRoleActionData, - GetRoleActionData, - RoleEntry, - UpdateRoleActionData, + ChaiCreateRoleArgs, + ChaiDeleteRoleArgs, + ChaiGetRoleArgs, + ChaiRoleRecord, + ChaiUpdateRoleArgs, } from "~/types/roles"; import type { createPage, @@ -58,10 +58,10 @@ import type { getSiteDomains } from "~/server/chai-builder/public/get-site-domai import type { getSiteSettings } from "~/server/chai-builder/public/get-site-settings"; import type { resolveLink } from "~/server/chai-builder/public/resolve-link"; import type { resolveLinksInPageBlocks } from "~/server/chai-builder/public/resolve-links-batch"; -import type { ResolvedChaiAIGlobalConfig, ResolvedChaiBuilderServerConfig } from "~/types/server-config"; +import type { ResolvedChaiAiGlobalConfig, ResolvedChaiBuilderServerConfig } from "~/types/server-config"; import type { ChaiPageType } from "~/types/actions"; import type { ChaiRequestContext } from "~/types/chaibuilder-config"; -import type { CollectionConfig } from "~/types/collection-config"; +import type { CollectionConfig } from "~/types/deprecated"; import type { ChaiRepeaterDataEntry } from "~/types/repeater-data"; import type { ChaiTrashableEntity } from "~/types/trash"; @@ -107,9 +107,9 @@ export interface ChaiBuilderInstance< getConfig(key: K): TExtra[K]; context: Readonly; - readonly db: DbInstance; + readonly db: ChaiDbInstance; readonly schema: ChaiCoreSchema; - safeQuery: (queryFn: (ctx: ChaiDbContext) => Promise) => Promise>; + safeQuery: (queryFn: (ctx: ChaiDbContext) => Promise) => Promise>; // Registry reads getPageType: (key: string) => ChaiPageTypeEntry | undefined; @@ -125,7 +125,7 @@ export interface ChaiBuilderInstance< getChaiCollection: (id: string) => ChaiRepeaterDataEntry | undefined; getChaiCollections: () => ChaiRepeaterDataEntry[]; getTrashEntity: (key: string) => ChaiTrashEntry | undefined; - getAIConfig: () => ResolvedChaiAIGlobalConfig; + getAIConfig: () => ResolvedChaiAiGlobalConfig; // Request / render scoping runPageRequest: (fn: () => T | Promise) => Promise; @@ -205,10 +205,10 @@ export interface ChaiBuilderInstance< * their plugin is absent. */ roles: { - getAll: () => Promise; - get: (data: GetRoleActionData) => Promise; - create: (data: CreateRoleActionData) => Promise; - update: (data: UpdateRoleActionData) => Promise; - delete: (data: DeleteRoleActionData) => Promise<{ deleted: boolean }>; + getAll: () => Promise; + get: (data: ChaiGetRoleArgs) => Promise; + create: (data: ChaiCreateRoleArgs) => Promise; + update: (data: ChaiUpdateRoleArgs) => Promise; + delete: (data: ChaiDeleteRoleArgs) => Promise<{ deleted: boolean }>; }; } diff --git a/src/types/collection-config.ts b/src/types/collection-config.ts deleted file mode 100644 index b33beb628..000000000 --- a/src/types/collection-config.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type { ChaiBlock } from "~/types/common"; - -/** @deprecated Use `ChaiRepeaterDataFetchParams` from `~/types/repeater-data` instead. */ -export type CollectionFetchParams = { - block: ChaiBlock; - inBuilder: boolean; - draft: boolean; - lang: string; - pageProps: { - slug: string; - params?: Record; - [key: string]: any; - }; -}; - -/** @deprecated Use `ChaiRepeaterDataConfig` from `~/types/repeater-data` instead — declarative fields with typed filters, sorting and limit. */ -export interface CollectionConfig { - id: string; - name: string; - icon?: string; - filters?: { id: string; name: string }[]; - sort?: { id: string; name: string }[]; - fetch: (params: CollectionFetchParams) => Promise<{ items: T[]; totalItems?: number }>; -} diff --git a/src/types/collections.ts b/src/types/collections.ts deleted file mode 100644 index d639e04d3..000000000 --- a/src/types/collections.ts +++ /dev/null @@ -1,30 +0,0 @@ -type FilterOptions = { - id: string; - name: string; - description?: string; -}; - -type SortOptions = { - id: string; - name: string; - description?: string; -}; - -/** - * @deprecated Use `ChaiRepeaterDataDefinition` from `~/types/repeater-data` instead. - * Note: the `sorts` key here never matched the server-side `CollectionConfig.sort` - * key, so the legacy Sort dropdown never populated. - */ -export type ChaiCollectoin = { - id: string; - name: string; - description?: string; - filters?: FilterOptions[]; - sorts?: SortOptions[]; -}; - -/** - * Correctly spelled alias of {@link ChaiCollectoin}. - * @deprecated Use `ChaiRepeaterDataDefinition` from `~/types/repeater-data` instead. - */ -export type ChaiCollection = ChaiCollectoin; diff --git a/src/types/db.ts b/src/types/db.ts index d00e8b5fd..1e3143760 100644 --- a/src/types/db.ts +++ b/src/types/db.ts @@ -1,2 +1,2 @@ -export type { ChaiDbSetup, DbInstance } from "~/db/core"; +export type { ChaiDbSetup, ChaiDbInstance } from "~/db/core"; export type { ChaiDbColumnNames, ChaiDbNaming, ChaiDbTableNaming, ChaiRelationColumnKey } from "~/drizzle/naming"; diff --git a/src/types/deprecated.ts b/src/types/deprecated.ts new file mode 100644 index 000000000..83dd00c72 --- /dev/null +++ b/src/types/deprecated.ts @@ -0,0 +1,220 @@ +/** + * Deprecated names of `/types`, re-exported by `./index.ts`. + * + * chaipro makes no breaking changes: a renamed or retired export keeps working from its original + * import path, with a `@deprecated` notice that names its replacement. Never delete an entry here. + * See API-CONSISTENCY.md. + */ +import type { ChaiTheme } from "~/types/chaibuilder-editor-props"; +import type { ChaiSavePageArgs } from "~/types/chaibuilder-editor-props"; +import type { ChaiBuilderRouteProps, ChaiIncomingRequest, ChaiRequestContext } from "~/types/chaibuilder-config"; +import type { ChaiBlock } from "~/types/common"; + +// --------------------------------------------------------------------------------------------- +// Collections, superseded by repeater data (`~/types/repeater-data`). +// --------------------------------------------------------------------------------------------- + +type FilterOptions = { + id: string; + name: string; + description?: string; +}; + +type SortOptions = { + id: string; + name: string; + description?: string; +}; + +/** + * @deprecated Use `ChaiRepeaterDataDefinition` from `/types`. Kept for compatibility. + * Note: the `sorts` key here never matched the server-side `CollectionConfig.sort` + * key, so the legacy Sort dropdown never populated. + */ +export type ChaiCollectoin = { + id: string; + name: string; + description?: string; + filters?: FilterOptions[]; + sorts?: SortOptions[]; +}; + +/** + * Correctly spelled alias of {@link ChaiCollectoin}. + * @deprecated Use `ChaiRepeaterDataDefinition` from `/types`. Kept for compatibility. + */ +export type ChaiCollection = ChaiCollectoin; + +/** @deprecated Use `ChaiRepeaterDataFetchArgs` from `/types`. Kept for compatibility. */ +export type CollectionFetchParams = { + block: ChaiBlock; + inBuilder: boolean; + draft: boolean; + lang: string; + pageProps: { + slug: string; + params?: Record; + [key: string]: any; + }; +}; + +/** + * @deprecated Use `ChaiRepeaterDataConfig` from `/types` — declarative fields with typed + * filters, sorting and limit. Kept for compatibility. + */ +export interface CollectionConfig { + id: string; + name: string; + icon?: string; + filters?: { id: string; name: string }[]; + sort?: { id: string; name: string }[]; + fetch: (params: CollectionFetchParams) => Promise<{ items: T[]; totalItems?: number }>; +} + +/** + * Collection entry + * @deprecated Use `ChaiRepeaterDataEntry` from `/types`. Kept for compatibility. + */ +export type ChaiCollectionEntry = CollectionConfig; + +// --------------------------------------------------------------------------------------------- +// Request context, superseded by the context resolver. +// --------------------------------------------------------------------------------------------- + +/** + * @deprecated Context passed to the removed `resolveSiteUrl` config option. + * Resolve `siteUrl` inside your `ChaiContextResolver` instead. Kept for compatibility. + */ +export type ChaiResolveSiteUrlContext = { + appId: string; +}; + +/** @deprecated Use `ChaiContextResolverArgs` from `/types`. Kept for compatibility. */ +export type ChaiRequestContextArgs = { + routeProps: ChaiBuilderRouteProps; + request?: Req; +}; + +/** @deprecated Use `ChaiContextResolver` from `/types`. Kept for compatibility. */ +export type ChaiRequestContextResolver = ( + args: ChaiRequestContextArgs, +) => Partial | Promise>; + +// --------------------------------------------------------------------------------------------- +// Renamed types. +// --------------------------------------------------------------------------------------------- + +/** @deprecated Use `ChaiTheme` from `/types`. Kept for compatibility. */ +export type ChaiBuilderThemeValues = ChaiTheme; + +/** @deprecated Use `ChaiSavePageArgs` from `/types`. Kept for compatibility. */ +export type SavePageData = ChaiSavePageArgs; + +export { + /** @deprecated Use `ChaiAiChatOptions` from `/types`. Kept for compatibility. */ + type ChaiAiChatOptions as AIChatOptions, + /** @deprecated Use `ChaiAiContext` from `/types`. Kept for compatibility. */ + type ChaiAiContext as AIContext, + /** @deprecated Use `ChaiListAssetsArgs` from `/types`. Kept for compatibility. */ + type ChaiListAssetsArgs as AssetsParams, + /** @deprecated Use `ChaiPagesAiHandler` from `/types`. Kept for compatibility. */ + type ChaiPagesAiHandler as ChaiBuilderPagesAIInterface, + /** @deprecated Use `ChaiSiteSettings` from `/types`. Kept for compatibility. */ + type ChaiSiteSettings as ChaiWebsiteSetting, + /** @deprecated Use `ChaiImageConfig` from `/types`. Kept for compatibility. */ + type ChaiImageConfig as ImageConfig, +} from "~/types/actions"; + +export { + /** @deprecated Use `ChaiAiGlobalConfig` from `/types`. Kept for compatibility. */ + type ChaiAiGlobalConfig as ChaiAIGlobalConfig, + /** @deprecated Use `ChaiLogAiRequestArgs` from `/types`. Kept for compatibility. */ + type ChaiLogAiRequestArgs as LogAiRequestParams, + /** @deprecated Use `ResolvedChaiAiGlobalConfig` from `/types`. Kept for compatibility. */ + type ResolvedChaiAiGlobalConfig as ResolvedChaiAIGlobalConfig, +} from "~/types/ai-config"; + +export { + /** @deprecated Use `ChaiAskAiResult` from `/types`. Kept for compatibility. */ + type ChaiAskAiResult as ChaiAskAiResponse, + /** @deprecated Use `ChaiSavePageArgs` from `/types`. Kept for compatibility. */ + type ChaiSavePageArgs as ChaiSavePageData, + /** @deprecated Use `ChaiSaveSiteArgs` from `/types`. Kept for compatibility. */ + type ChaiSaveSiteArgs as ChaiSaveWebsiteData, +} from "~/types/chaibuilder-editor-props"; + +export { + /** @deprecated Use `ChaiDbInstance` from `/types`. Kept for compatibility. */ + type ChaiDbInstance as DbInstance, +} from "~/types/db"; + +export { + /** @deprecated Use `ChaiGetAssetArgs` from `/types`. Kept for compatibility. */ + type ChaiGetAssetArgs as GetAssetInput, + /** @deprecated Use `ChaiSearchImagesArgs` from `/types`. Kept for compatibility. */ + type ChaiSearchImagesArgs as SearchImagesInput, + /** @deprecated Use `ChaiUpdateAssetArgs` from `/types`. Kept for compatibility. */ + type ChaiUpdateAssetArgs as UpdateAssetInput, +} from "~/types/media"; + +export { + /** @deprecated Use `ChaiRoleGrant` from `/types`. Kept for compatibility. */ + type ChaiRoleGrant as ChaiRoleEntry, +} from "~/types/rbac"; + +export { + /** @deprecated Use `ChaiRedirectEntry` from `/types`. Kept for compatibility. */ + type ChaiRedirectEntry as RedirectEntry, +} from "~/types/redirects"; + +export { + /** @deprecated Use `ChaiRepeaterDataFetchArgs` from `/types`. Kept for compatibility. */ + type ChaiRepeaterDataFetchArgs as ChaiRepeaterDataFetchParams, +} from "~/types/repeater-data"; + +export { + /** @deprecated Use `ChaiDeletePageRevisionArgs` from `/types`. Kept for compatibility. */ + type ChaiDeletePageRevisionArgs as DeletePageRevisionActionData, + /** @deprecated Use `ChaiGetPageRevisionsArgs` from `/types`. Kept for compatibility. */ + type ChaiGetPageRevisionsArgs as GetPageRevisionsActionData, + /** @deprecated Use `ChaiGetRevisionPageArgs` from `/types`. Kept for compatibility. */ + type ChaiGetRevisionPageArgs as GetRevisionPageActionData, + /** @deprecated Use `ChaiRestorePageArgs` from `/types`. Kept for compatibility. */ + type ChaiRestorePageArgs as RestorePageActionData, + /** @deprecated Use `ChaiRestorePagePart` from `/types`. Kept for compatibility. */ + type ChaiRestorePagePart as RestorePagePart, +} from "~/types/revisions"; + +export { + /** @deprecated Use `ChaiCreateRoleArgs` from `/types`. Kept for compatibility. */ + type ChaiCreateRoleArgs as CreateRoleActionData, + /** @deprecated Use `ChaiDeleteRoleArgs` from `/types`. Kept for compatibility. */ + type ChaiDeleteRoleArgs as DeleteRoleActionData, + /** @deprecated Use `ChaiGetRoleArgs` from `/types`. Kept for compatibility. */ + type ChaiGetRoleArgs as GetRoleActionData, + /** @deprecated Use `ChaiRoleRecord` from `/types`. Kept for compatibility. */ + type ChaiRoleRecord as RoleEntry, + /** @deprecated Use `ChaiUpdateRoleArgs` from `/types`. Kept for compatibility. */ + type ChaiUpdateRoleArgs as UpdateRoleActionData, +} from "~/types/roles"; + +export { + /** @deprecated Use `ChaiDeleteTrashPermanentlyArgs` from `/types`. Kept for compatibility. */ + type ChaiDeleteTrashPermanentlyArgs as DeletePermanentlyData, + /** @deprecated Use `ChaiGetTrashedItemsArgs` from `/types`. Kept for compatibility. */ + type ChaiGetTrashedItemsArgs as GetTrashedItemsData, + /** @deprecated Use `ChaiDeleteTrashByDaysArgs` from `/types`. Kept for compatibility. */ + type ChaiDeleteTrashByDaysArgs as PermanentlyDeleteByDaysData, + /** @deprecated Use `ChaiRestoreConflictResolution` from `/types`. Kept for compatibility. */ + type ChaiRestoreConflictResolution as RestoreConflictResolution, + /** @deprecated Use `ChaiRestoreTrashedItemArgs` from `/types`. Kept for compatibility. */ + type ChaiRestoreTrashedItemArgs as RestoreTrashedItemData, + /** @deprecated Use `ChaiTrashableRecordArgs` from `/types`. Kept for compatibility. */ + type ChaiTrashableRecordArgs as TrashableRecordData, + /** @deprecated Use `ChaiTrashContext` from `/types`. Kept for compatibility. */ + type ChaiTrashContext as TrashContext, + /** @deprecated Use `ChaiTrashEntityArgs` from `/types`. Kept for compatibility. */ + type ChaiTrashEntityArgs as TrashEntityData, + /** @deprecated Use `ChaiTrashRecord` from `/types`. Kept for compatibility. */ + type ChaiTrashRecord as TrashRecord, +} from "~/types/trash"; diff --git a/src/types/index.ts b/src/types/index.ts index 2d5160169..c4e2415a3 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -15,12 +15,11 @@ export * from "~/types/ai-config"; export * from "~/types/blocks"; export * from "~/types/chai-action"; export * from "~/types/chaibuilder-config"; -export * from "~/types/collection-config"; export * from "~/types/chaibuilder-editor-props"; -export * from "~/types/collections"; export * from "~/types/common"; export type { ChaiPageProps } from "~/types/common"; export * from "~/types/db"; +export * from "~/types/deprecated"; export * from "~/types/design-system"; export * from "~/types/media"; export * from "~/types/page-metadata"; @@ -39,3 +38,6 @@ export type ChaiRuntimeProp = { type: "runtime"; value: T; }; + +// Deprecated names, kept for compatibility. See ./deprecated.ts. +export * from "./deprecated"; diff --git a/src/types/media.ts b/src/types/media.ts index 0097b3a42..0e2ed32c1 100644 --- a/src/types/media.ts +++ b/src/types/media.ts @@ -4,7 +4,7 @@ * importing plugin code; the plugin's zod schema stays the source of * validation. */ -export type SearchImagesInput = { +export type ChaiSearchImagesArgs = { query: string; page?: number; limit?: number; @@ -17,11 +17,11 @@ export type SearchImagesInput = { * arrangement as SearchImagesInput above: core declares the shape, the * plugin's zod schema stays the source of validation. */ -export type GetAssetInput = { +export type ChaiGetAssetArgs = { id: string; }; -export type UpdateAssetInput = { +export type ChaiUpdateAssetArgs = { id: string; file?: string | Uint8Array; description?: Record; diff --git a/src/types/plugin.ts b/src/types/plugin.ts index 84c32d31d..4f444b3eb 100644 --- a/src/types/plugin.ts +++ b/src/types/plugin.ts @@ -4,7 +4,7 @@ import type { ChaiBuilderServerConfigInput, ResolvedChaiBuilderServerConfig } fr /** * Drizzle table/relation objects contributed by a plugin, keyed by export name. * The fragment matching the active dialect is merged into the DB schema at - * `buildChaiBuilderConfig` time, before `registerDb`. + * `buildChaiBuilderConfig` time, before `registerChaiDb`. */ export type ChaiSchemaFragment = { pg?: Record; diff --git a/src/types/rbac.ts b/src/types/rbac.ts index 4d0f41149..f90aa5750 100644 --- a/src/types/rbac.ts +++ b/src/types/rbac.ts @@ -2,10 +2,10 @@ export type ChaiRoleGrantMap = Record; /** Shape of a single role entry resolved from the `roles` table. */ -export type ChaiRoleEntry = { permissions?: string[] | null }; +export type ChaiRoleGrant = { permissions?: string[] | null }; /** Role -> entry map assembled from the `roles` table for a client. */ -export type ChaiRolesAndPermissions = Record; +export type ChaiRolesAndPermissions = Record; /** * Per-user override stored in `appUsers.permissions`. diff --git a/src/types/redirects.ts b/src/types/redirects.ts index 06ca77031..9c7eb806a 100644 --- a/src/types/redirects.ts +++ b/src/types/redirects.ts @@ -1,4 +1,4 @@ -export type RedirectEntry = { +export type ChaiRedirectEntry = { id: string; fromPath: string; toPath: string; diff --git a/src/types/repeater-data.ts b/src/types/repeater-data.ts index c810b39f7..809443f70 100644 --- a/src/types/repeater-data.ts +++ b/src/types/repeater-data.ts @@ -16,7 +16,7 @@ export type ChaiRepeaterOperator = /** * Single source of truth for which operators each field type supports. * Used by the builder filter UI, server-side query validation and - * the in-memory `applyRepeaterQuery` helper. + * the in-memory `applyChaiRepeaterQuery` helper. */ export const CHAI_REPEATER_OPERATORS_BY_TYPE: Record = { text: ["equals", "not_equals", "contains"], @@ -72,7 +72,7 @@ export type ChaiRepeaterQuery = { offset?: number; }; -export type ChaiRepeaterDataFetchParams = { +export type ChaiRepeaterDataFetchArgs = { block: ChaiBlock; inBuilder: boolean; draft: boolean; @@ -104,7 +104,7 @@ export interface ChaiRepeaterDataConfig { * in draft), and always stripped from the data. Per-call, so per-item tags * are possible. Tags must be tenant-scoped (include the app/company id). */ - fetch: (params: ChaiRepeaterDataFetchParams) => Promise<{ items: T[]; totalItems?: number; $cacheTags?: string[] }>; + fetch: (params: ChaiRepeaterDataFetchArgs) => Promise<{ items: T[]; totalItems?: number; $cacheTags?: string[] }>; /** * Detailed single-item fetch for the Collection Item block. The list `fetch` * returns subset fields for cards/grids; this returns the full document for @@ -112,7 +112,7 @@ export interface ChaiRepeaterDataConfig { * Implementing it opts the source into the Collection Item source picker. * Follows the same `$cacheTags` convention as `fetch`. */ - fetchItem?: (params: ChaiRepeaterDataFetchParams) => Promise<{ item: T | null; $cacheTags?: string[] }>; + fetchItem?: (params: ChaiRepeaterDataFetchArgs) => Promise<{ item: T | null; $cacheTags?: string[] }>; } export type ChaiRepeaterDataEntry = ChaiRepeaterDataConfig; diff --git a/src/types/revisions.ts b/src/types/revisions.ts index 5ff463aa9..a6199562c 100644 --- a/src/types/revisions.ts +++ b/src/types/revisions.ts @@ -3,11 +3,11 @@ * instance API can reference them without importing plugin code. */ -export type GetPageRevisionsActionData = { +export type ChaiGetPageRevisionsArgs = { pageId: string; }; -export type GetRevisionPageActionData = { +export type ChaiGetRevisionPageArgs = { id: string; type: "draft" | "live" | "revision"; lang?: string; @@ -20,9 +20,9 @@ export type GetRevisionPageActionData = { * which lives at `seo.jsonLD`; the `seo` slice restores the whole seo object * (JSON-LD included), while `jsonld` restores just that one key. */ -export type RestorePagePart = "blocks" | "seo" | "tracking" | "jsonld"; +export type ChaiRestorePagePart = "blocks" | "seo" | "tracking" | "jsonld"; -export type RestorePageActionData = { +export type ChaiRestorePageArgs = { revisionId: string; discardCurrent: boolean; pageId?: string; @@ -31,9 +31,9 @@ export type RestorePageActionData = { * today's behavior and the "bring back the old look" mental model, so a * rollback never silently undoes SEO work done since. */ - parts?: RestorePagePart[]; + parts?: ChaiRestorePagePart[]; }; -export type DeletePageRevisionActionData = { +export type ChaiDeletePageRevisionArgs = { revisionId: string; }; diff --git a/src/types/roles.ts b/src/types/roles.ts index 2cdac83a8..533b96e73 100644 --- a/src/types/roles.ts +++ b/src/types/roles.ts @@ -5,7 +5,7 @@ */ /** A row of the `roles` table as returned by the role CRUD actions. */ -export type RoleEntry = { +export type ChaiRoleRecord = { id: string; name: string; permissions: string[]; @@ -13,20 +13,20 @@ export type RoleEntry = { createdAt: string; }; -export type GetRoleActionData = { +export type ChaiGetRoleArgs = { name: string; }; -export type CreateRoleActionData = { +export type ChaiCreateRoleArgs = { name: string; permissions: string[]; }; -export type UpdateRoleActionData = { +export type ChaiUpdateRoleArgs = { name: string; permissions: string[]; }; -export type DeleteRoleActionData = { +export type ChaiDeleteRoleArgs = { name: string; }; diff --git a/src/types/server-config.ts b/src/types/server-config.ts index f186f52af..d40d7dbab 100644 --- a/src/types/server-config.ts +++ b/src/types/server-config.ts @@ -5,7 +5,6 @@ import type { CreditStatus } from "~/types/credits"; import type { ChaiAction } from "~/types/chai-action"; import type { ChaiBlockDataProvider, - ChaiCollectionEntry, ChaiRepeaterDataEntry, ChaiContextResolver, ChaiDebugLevel, @@ -16,12 +15,13 @@ import type { ChaiPageTypeEntry, ChaiTrashEntry, } from "~/types/chaibuilder-config"; +import type { ChaiCollectionEntry } from "~/types/deprecated"; import type { ChaiDbSetup } from "~/types/db"; import type { ChaiDesignSystemFeature } from "~/types/design-system"; import type { ChaiRequestMiddlewareEntry, ChaiSchemaFragment, ChaiServerPlugin, ChaiSetupHook } from "~/types/plugin"; import type { ChaiRolesAndPermissions } from "~/types/rbac"; -export type LogAiRequestParams = { +export type ChaiLogAiRequestArgs = { userId: string; startTime: number; response: Record; @@ -34,7 +34,7 @@ export type LogAiRequestParams = { export type { ChaiDbSetup }; -/** Result of `createPostgresDB`, `createLibsqlDB`, etc. — pass to `buildChaiBuilderConfig({ db })`. */ +/** Result of `createPostgresDb`, `createLibsqlDb`, etc. — pass to `buildChaiBuilderConfig({ db })`. */ export type ChaiDbConfigInput = ChaiDbSetup; export type ResolvedChaiDbConfig = ChaiDbSetup; @@ -80,7 +80,7 @@ export type ChaiAiProviderPlugin = { fingerprint?: () => string | undefined; }; -export type ResolvedChaiAIGlobalConfig = { +export type ResolvedChaiAiGlobalConfig = { models: AIModel[]; defaultModelId: string; /** Model key -> AI action names it handles, e.g. `{ "google/gemini-3-flash": ["AI_GENERATE_THEME"] }`. */ @@ -103,7 +103,7 @@ export type ResolvedChaiAIGlobalConfig = { */ providers?: ChaiAiProviderPlugin[]; logging: { - logger: (params: LogAiRequestParams) => void | Promise; + logger: (params: ChaiLogAiRequestArgs) => void | Promise; clientId: string | null; }; }; @@ -315,7 +315,7 @@ export type ResolvedChaiBuilderServerConfig = { defaultRoleGrants: ChaiDefaultRoleGrants; /** Role configuration. Undefined = use DEFAULT_ROLE_MAPS. */ roles: ChaiRolesConfig | undefined; - ai: ResolvedChaiAIGlobalConfig; + ai: ResolvedChaiAiGlobalConfig; mediaManager: ChaiMediaManagerConfig; db: ResolvedChaiDbConfig; /** Drizzle fragments contributed by plugins; merged into `db.schema` per dialect. */ @@ -367,7 +367,7 @@ export type ChaiBuilderServerConfigInput = { /** Collection data sources with declarative filter/sort/limit support. */ chaiCollections?: ChaiRepeaterDataEntry[]; blockDataProviders?: Record; - ai?: ChaiConfigDeepPartial; + ai?: ChaiConfigDeepPartial; /** Media manager tabs owned by the core. Plugin tabs are configured via plugin options. */ mediaManager?: ChaiMediaManagerConfigInput; trash?: ChaiTrashEntry[]; @@ -385,7 +385,7 @@ export type ChaiBuilderServerConfigInput = { /** * Additional default-role grants (role -> permission keys, wildcards allowed). * Contributed by plugins for their own keys; applied only on the - * DEFAULT_ROLE_MAPS fallback. Use `mergeDefaultRoleGrants` to append. + * DEFAULT_ROLE_MAPS fallback. Use `mergeChaiDefaultRoleGrants` to append. */ defaultRoleGrants?: ChaiDefaultRoleGrants; /** Role configuration. Omit to use DEFAULT_ROLE_MAPS. Pass `{ source: 'custom' }` to load from DB. */ diff --git a/src/types/trash.ts b/src/types/trash.ts index d4d061491..65bf1bc86 100644 --- a/src/types/trash.ts +++ b/src/types/trash.ts @@ -1,8 +1,8 @@ import type { ChaiActionContext } from "~/types/chai-action"; -export type TrashContext = ChaiActionContext & Record; +export type ChaiTrashContext = ChaiActionContext & Record; -export type TrashRecord = { +export type ChaiTrashRecord = { id: string; entityType: string; entityId: string; @@ -14,21 +14,21 @@ export type TrashRecord = { tags?: string[]; }; -export type TrashableRecordData = Omit; +export type ChaiTrashableRecordArgs = Omit; -export type RestoreConflictResolution = { +export type ChaiRestoreConflictResolution = { resolved: boolean; newSlug?: string; }; // Action data shapes — declared here (not in the trash plugin's action files) so the // typed `getChaiBuilder` instance API can reference them without importing plugin code. -export type TrashEntityData = { +export type ChaiTrashEntityArgs = { entityType: string; ids: string[]; }; -export type GetTrashedItemsData = { +export type ChaiGetTrashedItemsArgs = { page?: number; limit?: number; search?: string; @@ -37,15 +37,15 @@ export type GetTrashedItemsData = { sortOrder?: "asc" | "desc"; }; -export type RestoreTrashedItemData = { +export type ChaiRestoreTrashedItemArgs = { id: string; }; -export type DeletePermanentlyData = { +export type ChaiDeleteTrashPermanentlyArgs = { id: string; }; -export type PermanentlyDeleteByDaysData = { +export type ChaiDeleteTrashByDaysArgs = { days: number; }; @@ -53,9 +53,12 @@ export interface ChaiTrashableEntity { key: string; label: string; icon?: string; - moveToTrash: (id: string, context: TrashContext) => Promise; - restore: (record: TrashRecord, context: TrashContext) => Promise; - deletePermanently: (record: TrashRecord, context: TrashContext) => Promise; - hasRestoreConflict?: (record: TrashRecord, context: TrashContext) => Promise; - resolveRestoreConflict?: (record: TrashRecord, context: TrashContext) => Promise; + moveToTrash: (id: string, context: ChaiTrashContext) => Promise; + restore: (record: ChaiTrashRecord, context: ChaiTrashContext) => Promise; + deletePermanently: (record: ChaiTrashRecord, context: ChaiTrashContext) => Promise; + hasRestoreConflict?: (record: ChaiTrashRecord, context: ChaiTrashContext) => Promise; + resolveRestoreConflict?: ( + record: ChaiTrashRecord, + context: ChaiTrashContext, + ) => Promise; } diff --git a/src/types/types.ts b/src/types/types.ts index 9b36c5135..8199a9df1 100644 --- a/src/types/types.ts +++ b/src/types/types.ts @@ -8,11 +8,6 @@ export type ChaiRenderBlockProps = { export type ChaiBlockStyles = Record; -export type { - ChaiTheme as ChaiBuilderThemeValues, - ChaiSavePageData as SavePageData, -} from "~/types/chaibuilder-editor-props"; - export interface ChaiDesignTokens { [uniqueId: string]: { name: string; diff --git a/src/utils/apply-design-tokens.ts b/src/utils/apply-design-tokens.ts index e7eeda85b..6336c36d7 100644 --- a/src/utils/apply-design-tokens.ts +++ b/src/utils/apply-design-tokens.ts @@ -4,7 +4,7 @@ import { STYLES_KEY } from "~/constants/STRINGS"; import { ChaiBlock } from "~/types/common"; import { ChaiDesignTokens } from "~/types/types"; -export const applyDesignTokens = (blocks: ChaiBlock[], designTokens: ChaiDesignTokens) => { +export const applyChaiDesignTokens = (blocks: ChaiBlock[], designTokens: ChaiDesignTokens) => { return blocks.map((block) => { const styleKeys = keys(block).filter((key) => isString(block[key]) && block[key].startsWith(STYLES_KEY)); if (styleKeys.length === 0) return block; @@ -35,13 +35,13 @@ if (import.meta.vitest) { ]; const snapshot = structuredClone(input); - const result = applyDesignTokens(input, mockDesignTokens); + const result = applyChaiDesignTokens(input, mockDesignTokens); expect(input).toEqual(snapshot); expect(result[0]).not.toBe(input[0]); expect(result[0].styles).toBe("#styles:,bg-white"); // Re-applying on the untouched input must yield the same result - expect(applyDesignTokens(input, mockDesignTokens)[0].styles).toBe("#styles:,bg-white"); + expect(applyChaiDesignTokens(input, mockDesignTokens)[0].styles).toBe("#styles:,bg-white"); }); }); } diff --git a/src/utils/apply-repeater-query.ts b/src/utils/apply-repeater-query.ts index f02bf5477..34ea89347 100644 --- a/src/utils/apply-repeater-query.ts +++ b/src/utils/apply-repeater-query.ts @@ -84,7 +84,7 @@ const sortItems = (items: T[], sort: ChaiRepeaterSort[]): T[] => { * date strings compare as timestamps; missing item fields fail every filter * except `not_equals` / `not_in`, which pass. */ -export const applyRepeaterQuery = (items: T[], query: ChaiRepeaterQuery): T[] => { +export const applyChaiRepeaterQuery = (items: T[], query: ChaiRepeaterQuery): T[] => { const filters = query?.filters ?? []; const filtered = filters.length ? items.filter((item) => filters.every((f) => matchesFilter(item, f))) : items; const sorted = sortItems(filtered, query?.sort ?? []); @@ -98,12 +98,20 @@ if (import.meta.vitest) { const posts = [ { title: "Alpha", views: 10, featured: true, publishedAt: "2026-01-05", category: "news", slug: "/blog/alpha" }, - { title: "beta guide", views: 25, featured: false, publishedAt: "2026-03-01", category: "guide", slug: "/blog/beta" }, + { + title: "beta guide", + views: 25, + featured: false, + publishedAt: "2026-03-01", + category: "guide", + slug: "/blog/beta", + }, { title: "Gamma", views: 5, featured: true, publishedAt: "2025-11-20", category: "news", slug: "/blog/gamma" }, { title: "Delta", views: 25, category: "guide", slug: "/blog/delta" }, ]; - const run = (partial: Partial) => applyRepeaterQuery(posts, { filters: [], sort: [], ...partial }); + const run = (partial: Partial) => + applyChaiRepeaterQuery(posts, { filters: [], sort: [], ...partial }); describe("applyRepeaterQuery", () => { it("filters with equals / not_equals", () => { diff --git a/src/utils/convert-html-to-chai-blocks.ts b/src/utils/convert-html-to-chai-blocks.ts index b2bc0e159..faea93ed3 100644 --- a/src/utils/convert-html-to-chai-blocks.ts +++ b/src/utils/convert-html-to-chai-blocks.ts @@ -1,2 +1,2 @@ import { getBlocksFromHTML } from "./import-html/html-to-json"; -export const convertHTMLToChaiBlocks = getBlocksFromHTML; +export const parseChaiBlocksFromHtml = getBlocksFromHTML; diff --git a/src/utils/convert-to-blocks.ts b/src/utils/convert-to-blocks.ts index acbabf623..60f87cc3d 100644 --- a/src/utils/convert-to-blocks.ts +++ b/src/utils/convert-to-blocks.ts @@ -30,7 +30,7 @@ function removeAssetPrefix(input: string): string { * This function converts the chai format content to chai blocks * @param chaiFormatContent */ -export const convertToBlocks = (chaiFormatContent: string): ChaiBlock[] => { +export const parseChaiBlocksFromChaiFile = (chaiFormatContent: string): ChaiBlock[] => { if (!chaiFormatContent) return []; try { const blocks = JSON.parse(removeAssetPrefix(chaiFormatContent)); diff --git a/src/utils/deprecated.ts b/src/utils/deprecated.ts new file mode 100644 index 000000000..d925b1ba7 --- /dev/null +++ b/src/utils/deprecated.ts @@ -0,0 +1,42 @@ +/** + * Deprecated names of `/utils`, re-exported by `./index.ts`. + * + * chaipro makes no breaking changes: a renamed or retired export keeps working from its original + * import path, with a `@deprecated` notice that names its replacement. Never delete an entry here. + * See API-CONSISTENCY.md. + */ + +export { + /** @deprecated Use `generateUuid` from `/utils`. Kept for compatibility. */ + generateUuid as generateUUID, +} from "~/builder/core/functions/common-functions"; + +export { + /** @deprecated Use `applyChaiDesignTokens` from `/utils`. Kept for compatibility. */ + applyChaiDesignTokens as applyDesignTokens, +} from "~/utils/apply-design-tokens"; + +export { + /** @deprecated Use `applyChaiRepeaterQuery` from `/utils`. Kept for compatibility. */ + applyChaiRepeaterQuery as applyRepeaterQuery, +} from "~/utils/apply-repeater-query"; + +export { + /** @deprecated Use `parseChaiBlocksFromHtml` from `/utils`. Kept for compatibility. */ + parseChaiBlocksFromHtml as convertHTMLToChaiBlocks, +} from "~/utils/convert-html-to-chai-blocks"; + +export { + /** @deprecated Use `parseChaiBlocksFromChaiFile` from `/utils`. Kept for compatibility. */ + parseChaiBlocksFromChaiFile as convertToBlocks, +} from "~/utils/convert-to-blocks"; + +export { + /** @deprecated Use `getChaiTailwindTheme` from `/utils`. Kept for compatibility. */ + getChaiTailwindTheme as getChaiBuilderTheme, +} from "~/utils/get-chai-builder-theme"; + +export { + /** @deprecated Use `chaiTailwindPlugin` from `/utils`. Kept for compatibility. */ + default as chaiBuilderPlugin, +} from "~/utils/plugin"; diff --git a/src/utils/get-chai-builder-theme.ts b/src/utils/get-chai-builder-theme.ts index d1cd4e22d..046a543de 100644 --- a/src/utils/get-chai-builder-theme.ts +++ b/src/utils/get-chai-builder-theme.ts @@ -2,7 +2,7 @@ import { getChaiThemeOptions } from "~/builder/core/components/canvas/static/cha import { defaultThemeOptions } from "~/builder/hooks/default-theme-options"; import { ChaiThemeOptions } from "~/types/chaibuilder-editor-props"; -export const getChaiBuilderTheme = (themeOptions: ChaiThemeOptions = defaultThemeOptions) => { +export const getChaiTailwindTheme = (themeOptions: ChaiThemeOptions = defaultThemeOptions) => { return { container: { center: true, diff --git a/src/utils/import-html/html-to-json.ts b/src/utils/import-html/html-to-json.ts index 6e9533cce..28fecc390 100644 --- a/src/utils/import-html/html-to-json.ts +++ b/src/utils/import-html/html-to-json.ts @@ -24,10 +24,10 @@ import { unset, } from "lodash-es"; import { canAddChildBlock } from "~/builder/core/functions/block-helpers"; -import { generateUUID } from "~/builder/core/functions/common-functions"; +import { generateUuid } from "~/builder/core/functions/common-functions"; import { STYLES_KEY } from "~/constants/STRINGS"; import { cn } from "~/lib/utils"; -import { getBlockDefaultProps, syncBlocksWithDefaultProps } from "~/registry"; +import { getChaiBlockDefaultProps, syncChaiBlocksWithDefaultProps } from "~/registry"; import { ChaiBlock } from "~/types"; import { decodeStyleText, @@ -475,7 +475,7 @@ const traverseNodes = (nodes: HimalayaNode[], parent: any = null): ChaiBlock[] = if (node.type === "comment") return []; // * Generating block id and setting parent id if nested - let block: Partial> = { _id: generateUUID() }; + let block: Partial> = { _id: generateUuid() }; if (parent) block._parent = parent.block._id; /** @@ -762,7 +762,9 @@ const traverseNodes = (nodes: HimalayaNode[], parent: any = null): ChaiBlock[] = // button's text (or a submit input's value) becomes the label instead // of a Text child that does not show, which left the default "Submit" // on a French page. - const text = getTextContent(node.children || []).replace(/\s+/g, " ").trim(); + const text = getTextContent(node.children || []) + .replace(/\s+/g, " ") + .trim(); const value = String(get(find(node.attributes, { key: "value" }), "value", "") ?? "").trim(); const label = text || value; if (label) set(block, "label", label); @@ -920,7 +922,7 @@ export const mergeBlocksWithExisting = (importedBlocks: ChaiBlock[], existingBlo // AI rewrites emit a partial placement as a bare , and import // fills in the default wrapper. Keep the placement's own wrapper unless the edit set another. if (existingBlock._type === "PartialBlock") { - const defaults = getBlockDefaultProps("PartialBlock") as Record; + const defaults = getChaiBlockDefaultProps("PartialBlock") as Record; for (const key of PARTIAL_PLACEMENT_PROPS) { if (has(original, key) && (!has(importedBlock, key) || isEqual(merged[key], defaults[key]))) { merged[key] = original[key]; @@ -950,5 +952,5 @@ export const getBlocksFromHTML = async (html: string): Promise => { // syncBlocksWithDefaultProps first so every block carries its registered // schema-typed defaults; restoreBlockPropTypes then coerces any prop the // AI-HTML round-trip turned into a string back to its schema type. - return await resolveIconNames(restoreBlockPropTypes(syncBlocksWithDefaultProps(blocks))); + return await resolveIconNames(restoreBlockPropTypes(syncChaiBlocksWithDefaultProps(blocks))); }; diff --git a/src/utils/index.ts b/src/utils/index.ts index 7c6dd1991..98be7d2a8 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -1,13 +1,16 @@ -import chaiBuilderPlugin from "./plugin"; +import chaiTailwindPlugin from "./plugin"; -export { generateUUID } from "~/builder/core/functions/common-functions"; +export { generateUuid } from "~/builder/core/functions/common-functions"; export { applyChaiDataBinding } from "./apply-chai-data-binding"; export { analyzeChaiBindings, suggestChaiBindingConversion } from "./analyze-chai-bindings"; export type { ChaiBindingAnalysis } from "./analyze-chai-bindings"; -export { applyRepeaterQuery } from "./apply-repeater-query"; -export { applyDesignTokens } from "./apply-design-tokens"; -export { convertHTMLToChaiBlocks } from "./convert-html-to-chai-blocks"; -export { convertToBlocks } from "./convert-to-blocks"; -export { getChaiBuilderTheme } from "./get-chai-builder-theme"; +export { applyChaiRepeaterQuery } from "./apply-repeater-query"; +export { applyChaiDesignTokens } from "./apply-design-tokens"; +export { parseChaiBlocksFromHtml } from "./convert-html-to-chai-blocks"; +export { parseChaiBlocksFromChaiFile } from "./convert-to-blocks"; +export { getChaiTailwindTheme } from "./get-chai-builder-theme"; export { getCleanHostname } from "./get-hostname"; -export { chaiBuilderPlugin }; +export { chaiTailwindPlugin }; + +// Deprecated names, kept for compatibility. See ./deprecated.ts. +export * from "./deprecated"; diff --git a/src/web-blocks/custom/page-slot.tsx b/src/web-blocks/custom/page-slot.tsx index d0e9f89c5..c342324c3 100644 --- a/src/web-blocks/custom/page-slot.tsx +++ b/src/web-blocks/custom/page-slot.tsx @@ -4,7 +4,7 @@ import { registerChaiBlockProps } from "~/registry"; import { ChaiBlockComponentProps } from "~/types/blocks"; export type PageSlotProps = { - /** Empty = default slot (`children`). Named = matched via `WithChaiLayout slots={{ name: … }}`. */ + /** Empty = default slot (`children`). Named = matched via `ChaiLayout slots={{ name: … }}`. */ slotName: string; }; diff --git a/src/web-blocks/hidden/table.tsx b/src/web-blocks/hidden/table.tsx index fd43631d5..d49065954 100644 --- a/src/web-blocks/hidden/table.tsx +++ b/src/web-blocks/hidden/table.tsx @@ -7,7 +7,7 @@ import { } from "@radix-ui/react-icons"; import { isEmpty } from "lodash-es"; import { createElement } from "react"; -import { generateUUID } from "~/builder/core/functions/common-functions"; +import { generateUuid } from "~/builder/core/functions/common-functions"; import { registerChaiBlock, registerChaiBlockProps, stylesProp } from "~/registry"; import { useInnerHtml } from "~/web-blocks/use-inner-html"; import { ChaiBlockComponentProps, ChaiStyles } from "~/types/blocks"; @@ -185,7 +185,7 @@ export default TableBlock; function getDefaultBlocks(type: string): ChaiBlock[] { const td = (id: string, content: string) => ({ - _id: generateUUID(), + _id: generateUuid(), _parent: id, _type: "TableCell", styles: "#styles:,", @@ -193,7 +193,7 @@ function getDefaultBlocks(type: string): ChaiBlock[] { }); const tr = (id?: string) => { - const trId = generateUUID(); + const trId = generateUuid(); const rootBlock: ChaiBlock = { _type: "TableRow", _id: trId, @@ -204,7 +204,7 @@ function getDefaultBlocks(type: string): ChaiBlock[] { }; const thead = (id?: string) => { - const theadId = generateUUID(); + const theadId = generateUuid(); const rootBlock: ChaiBlock = { _id: theadId, _type: "TableHead", @@ -215,7 +215,7 @@ function getDefaultBlocks(type: string): ChaiBlock[] { }; const tbody = (id?: string) => { - const tbodyId = generateUUID(); + const tbodyId = generateUuid(); const rootBlock: ChaiBlock = { _id: tbodyId, _type: "TableBody", @@ -226,7 +226,7 @@ function getDefaultBlocks(type: string): ChaiBlock[] { }; if (type === "Table") { - const tableId = generateUUID(); + const tableId = generateUuid(); return [ { _id: tableId,