The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(docs): improve error messages for Partials directive (#42079)
Charis40c9bee53e3e
diff --git a/apps/docs/content/_partials/_fixtures/hyphenated-variables.mdx b/apps/docs/content/_partials/_fixtures/hyphenated-variables.mdxnew file mode 100644index 00000000000..db9c954cf53--- /dev/null+++ b/apps/docs/content/_partials/_fixtures/hyphenated-variables.mdx@@ -0,0 +1 @@+This partial has {{ .my-var }}, {{ .another_var }}, and {{ .myVar123 }}.diff --git a/apps/docs/content/_partials/_fixtures/multiple-variables.mdx b/apps/docs/content/_partials/_fixtures/multiple-variables.mdxnew file mode 100644index 00000000000..c5469dc3f7e--- /dev/null+++ b/apps/docs/content/_partials/_fixtures/multiple-variables.mdx@@ -0,0 +1 @@+This partial has {{ .var1 }}, {{ .var2 }}, and {{ .var3 }}.diff --git a/apps/docs/features/directives/Partial.test.ts b/apps/docs/features/directives/Partial.test.tsindex 58719aae357..5217554a15c 100644--- a/apps/docs/features/directives/Partial.test.ts+++ b/apps/docs/features/directives/Partial.test.ts@@ -115,4 +115,115 @@ Some more text.const mdast = fromDocsMarkdown(markdown)await expect(partialsRemark()(mdast)).rejects.toThrowError(/valid JSON/)})++ it('should error when required variable is missing', async () => {+ const markdown = `+# Embed partial++<$Partial path="/_fixtures/variables.mdx" />++Some more text.+`.trim()++ const mdast = fromDocsMarkdown(markdown)+ await expect(partialsRemark()(mdast)).rejects.toThrowError(+ /Missing required variable in \$Partial ".*variables\.mdx": "var"/+ )+ })++ it('should error when unexpected variable is provided', async () => {+ const markdown = `+# Embed partial++<$Partial path="/_fixtures/variables.mdx" variables={{ "var": "correct", "extra": "unexpected" }} />++Some more text.+`.trim()++ const mdast = fromDocsMarkdown(markdown)+ await expect(partialsRemark()(mdast)).rejects.toThrowError(+ /Unexpected variable in \$Partial ".*variables\.mdx": "extra"/+ )+ })++ it('should error with detailed message for multiple missing variables', async () => {+ const markdown = `+# Embed partial++<$Partial path="/_fixtures/multiple-variables.mdx" variables={{ "var1": "value1" }} />++Some more text.+`.trim()++ const mdast = fromDocsMarkdown(markdown)+ await expect(partialsRemark()(mdast)).rejects.toThrowError(+ /Missing required variables.*"var2".*"var3".*Expected variables.*"var1".*"var2".*"var3".*Provided variable: "var1"/s+ )+ })++ it('should error with detailed message for multiple unexpected variables', async () => {+ const markdown = `+# Embed partial++<$Partial path="/_fixtures/variables.mdx" variables={{ "var": "correct", "extra1": "wrong", "extra2": "also wrong" }} />++Some more text.+`.trim()++ const mdast = fromDocsMarkdown(markdown)+ await expect(partialsRemark()(mdast)).rejects.toThrowError(+ /Unexpected variables.*"extra1".*"extra2".*Expected variable: "var".*Provided variables.*"var".*"extra1".*"extra2"/s+ )+ })++ it('should succeed when all variables match exactly', async () => {+ const markdown = `+# Embed partial++<$Partial path="/_fixtures/multiple-variables.mdx" variables={{ "var1": "first", "var2": "second", "var3": "third" }} />++Some more text.+`.trim()++ const mdast = fromDocsMarkdown(markdown)+ const transformed = await partialsRemark()(mdast)+ const output = toMarkdown(transformed, { extensions: [mdxToMarkdown()] })++ expect(output).toContain('first')+ expect(output).toContain('second')+ expect(output).toContain('third')+ })++ it('should support hyphenated variable names', async () => {+ const markdown = `+# Embed partial++<$Partial path="/_fixtures/hyphenated-variables.mdx" variables={{ "my-var": "hyphenated value", "another_var": "underscored value", "myVar123": "alphanumeric value" }} />++Some more text.+`.trim()++ const mdast = fromDocsMarkdown(markdown)+ const transformed = await partialsRemark()(mdast)+ const output = toMarkdown(transformed, { extensions: [mdxToMarkdown()] })++ expect(output).toContain('hyphenated value')+ expect(output).toContain('underscored value')+ expect(output).toContain('alphanumeric value')+ })++ it('should error when hyphenated variable is missing', async () => {+ const markdown = `+# Embed partial++<$Partial path="/_fixtures/hyphenated-variables.mdx" variables={{ "my-var": "value" }} />++Some more text.+`.trim()++ const mdast = fromDocsMarkdown(markdown)+ await expect(partialsRemark()(mdast)).rejects.toThrowError(+ /Missing required variables.*"another_var".*"myVar123".*Expected variables.*"my-var".*"another_var".*"myVar123".*Provided variable: "my-var"/s+ )+ })})diff --git a/apps/docs/features/directives/Partial.ts b/apps/docs/features/directives/Partial.tsindex 888071f2a70..15d40004f54 100644--- a/apps/docs/features/directives/Partial.ts+++ b/apps/docs/features/directives/Partial.ts@@ -73,6 +73,60 @@ function toFilePath(node: MdxJsxFlowElement) {return filePath}+/**+ * Extracts all variable names expected in the partial content.+ * Returns a Set of variable names found in {{ .variableName }} patterns.+ * Variable names can contain alphanumeric characters, hyphens, and underscores.+ */+function extractExpectedVariables(content: string): Set<string> {+ const variablePattern = /(?<!\\)\{\{\s*\.([\w-]+)\s*\}\}/g+ const variables = new Set<string>()+ let match++ while ((match = variablePattern.exec(content)) !== null) {+ variables.add(match[1])+ }++ return variables+}++/**+ * Validates that all expected variables are provided and no unexpected variables are included.+ * Throws descriptive errors if validation fails.+ */+function validateVariables(+ content: string,+ vars: Record<string, string> | undefined,+ partialPath: string+) {+ const expectedVars = extractExpectedVariables(content)+ const providedVars = vars ? new Set(Object.keys(vars)) : new Set<string>()++ // Check for missing variables+ const missingVars = [...expectedVars].filter((v) => !providedVars.has(v))+ if (missingVars.length > 0) {+ const varList = missingVars.map((v) => `"${v}"`).join(', ')+ const plural = missingVars.length > 1+ throw new Error(+ `Missing required variable${plural ? 's' : ''} in $Partial "${partialPath}": ${varList}\n` ++ `Expected variable${expectedVars.size > 1 ? 's' : ''}: ${[...expectedVars].map((v) => `"${v}"`).join(', ')}\n` ++ `Provided variable${providedVars.size !== 1 ? 's' : ''}: ${providedVars.size > 0 ? [...providedVars].map((v) => `"${v}"`).join(', ') : 'none'}`+ )+ }++ // Check for unexpected variables+ const unexpectedVars = [...providedVars].filter((v) => !expectedVars.has(v))+ if (unexpectedVars.length > 0) {+ const varList = unexpectedVars.map((v) => `"${v}"`).join(', ')+ const plural = unexpectedVars.length > 1+ throw new Error(+ `Unexpected variable${plural ? 's' : ''} in $Partial "${partialPath}": ${varList}\n` ++ `Expected variable${expectedVars.size !== 1 ? 's' : ''}: ${expectedVars.size > 0 ? [...expectedVars].map((v) => `"${v}"`).join(', ') : 'none'}\n` ++ `Provided variable${plural ? 's' : ''}: ${[...providedVars].map((v) => `"${v}"`).join(', ')}`+ )+ }+}+function substituteVars(content: string, vars: Record<string, string> | undefined) {if (vars === undefined) {return content@@ -105,7 +159,12 @@ function getVariables(node: MdxJsxFlowElement): undefined | Record<string, strinasync function fetchPartialsContent(tree: Root) {// INVARIANT: These must be pushed to in the same order because the index is // used to keep track of the relationship.- const partialNodes = [] as [Parent, MdxJsxFlowElement, undefined | Record<string, string>][]+ const partialNodes = [] as [+ Parent,+ MdxJsxFlowElement,+ undefined | Record<string, string>,+ string,+ ][]const pendingFetches = [] as Promise<string>[]visitParents(tree, 'mdxJsxFlowElement', (node: MdxJsxFlowElement, ancestors) => {@@ -115,8 +174,9 @@ async function fetchPartialsContent(tree: Root) {const filePath = toFilePath(node)const variables = getVariables(node)const fetchTask = readFile(filePath, 'utf-8')+ const partialPath = getAttributeValue(node, 'path') as string- partialNodes.push([parent, node, variables])+ partialNodes.push([parent, node, variables, partialPath])pendingFetches.push(fetchTask)})@@ -124,19 +184,21 @@ async function fetchPartialsContent(tree: Root) {const nodeContentMap = new Map<MdxJsxFlowElement,- [Parent, string, undefined | Record<string, string>]+ [Parent, string, undefined | Record<string, string>, string]>()- partialNodes.forEach(([parent, node, variables], index) => {- nodeContentMap.set(node, [parent, resolvedContent[index], variables])+ partialNodes.forEach(([parent, node, variables, partialPath], index) => {+ nodeContentMap.set(node, [parent, resolvedContent[index], variables, partialPath])})return nodeContentMap}function rewriteNodes(- contentMap: Map<MdxJsxFlowElement, [Parent, string, undefined | Record<string, string>]>+ contentMap: Map<MdxJsxFlowElement, [Parent, string, undefined | Record<string, string>, string]>) {- for (const [node, [parent, rawContent, vars]] of contentMap) {- let content = substituteVars(rawContent.trim(), vars)+ for (const [node, [parent, rawContent, vars, partialPath]] of contentMap) {+ const trimmedContent = rawContent.trim()+ validateVariables(trimmedContent, vars, partialPath)+ let content = substituteVars(trimmedContent, vars)const replacementContent = fromDocsMarkdown(content)parent.children.splice(parent.children.indexOf(node), 1, replacementContent)}