Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat(docs-search): ingest reference docs

Greg Richardson9058770134a5
diff --git a/apps/docs/components/Clippy/ClippyModal.tsx b/apps/docs/components/Clippy/ClippyModal.tsx
index 5ecbb46b25e..1af52330b73 100644
--- a/apps/docs/components/Clippy/ClippyModal.tsx
+++ b/apps/docs/components/Clippy/ClippyModal.tsx
@@ -228,7 +228,7 @@ const ClippyModal: FC<Props> = ({ onClose }) => {
return (
<div key={page.id} className="flex flex-col gap-3">
<SearchResult
- href={`${page.path}`}
+ href={page.path}
type={SearchResultType.Document}
title={page.meta.title}
/>
@@ -239,7 +239,9 @@ const ClippyModal: FC<Props> = ({ onClose }) => {
{pageSections.map((section) => (
<SearchResult
key={section.id}
- href={`${page.path}#${section.slug}`}
+ href={`${page.path}${page.type === 'reference' ? '/' : '#'}${
+ section.slug
+ }`}
type={SearchResultType.Section}
title={section.heading}
chip={page.meta.title}
diff --git a/apps/docs/lib/helpers.ts b/apps/docs/lib/helpers.ts
index 899aea15618..29fdac4b8e5 100644
--- a/apps/docs/lib/helpers.ts
+++ b/apps/docs/lib/helpers.ts
@@ -33,9 +33,16 @@ export function getPageType(asPath: string) {
return page
}
-export function flattenSections(sections) {
- var a = []
- for (var i = 0; i < sections.length; i++) {
+export type ReferenceSection = {
+ title: string
+ id?: string
+ slug?: string
+ items?: ReferenceSection[]
+}
+
+export function flattenSections(sections: ReferenceSection[]) {
+ let a: ReferenceSection[] = []
+ for (let i = 0; i < sections.length; i++) {
if (sections[i].id) {
// only push a section that has an id
// these are reserved for sidebar subtitles
diff --git a/apps/docs/scripts/generate-embeddings.ts b/apps/docs/scripts/generate-embeddings.ts
index 6bc3f5dc19a..b0598804d76 100644
--- a/apps/docs/scripts/generate-embeddings.ts
+++ b/apps/docs/scripts/generate-embeddings.ts
@@ -4,6 +4,7 @@ import dotenv from 'dotenv'
import { ObjectExpression } from 'estree'
import { readdir, readFile, stat } from 'fs/promises'
import GithubSlugger from 'github-slugger'
+import yaml from 'js-yaml'
import { Content, Root } from 'mdast'
import { fromMarkdown } from 'mdast-util-from-markdown'
import { mdxFromMarkdown, MdxjsEsm } from 'mdast-util-mdx'
@@ -12,10 +13,15 @@ import { toString } from 'mdast-util-to-string'
import { mdxjs } from 'micromark-extension-mdxjs'
import 'openai'
import { Configuration, OpenAIApi } from 'openai'
+import { OpenAPIV3 } from 'openapi-types'
import { basename, dirname, join } from 'path'
import { u } from 'unist-builder'
import { filter } from 'unist-util-filter'
import { inspect } from 'util'
+import { IFunctionDefinition, ISpec } from '../components/reference/Reference.types'
+import { CliCommand, CliSpec } from '../generator/types/CliSpec'
+import { flattenSections, ReferenceSection } from '../lib/helpers'
+import { enrichedOperation, gen_v3 } from '../lib/refGenerator/helpers'
dotenv.config()
@@ -220,6 +226,174 @@ async function walk(dir: string, parentPath?: string): Promise<WalkEntry[]> {
return flattenedFiles.sort((a, b) => a.path.localeCompare(b.path))
}
+abstract class BaseEmbeddingSource {
+ checksum?: string
+ meta?: Meta
+ sections?: Section[]
+
+ constructor(public source: string, public path: string, public parentPath?: string) {}
+
+ abstract load(): Promise<{ checksum: string; meta?: Meta; sections: Section[] }>
+}
+
+class MarkdownEmbeddingSource extends BaseEmbeddingSource {
+ type: 'markdown' = 'markdown'
+
+ constructor(source: string, public filePath: string, public parentFilePath?: string) {
+ const path = filePath.replace(/^pages/, '').replace(/\.mdx?$/, '')
+ const parentPath = parentFilePath?.replace(/^pages/, '').replace(/\.mdx?$/, '')
+
+ super(source, path, parentPath)
+ }
+
+ async load() {
+ const contents = await readFile(this.filePath, 'utf8')
+
+ const { checksum, meta, sections } = processMdxForSearch(contents)
+
+ this.checksum = checksum
+ this.meta = meta
+ this.sections = sections
+
+ return {
+ checksum,
+ meta,
+ sections,
+ }
+ }
+}
+
+abstract class ReferenceEmbeddingSource<SpecSection> extends BaseEmbeddingSource {
+ type: 'reference' = 'reference'
+
+ constructor(
+ source: string,
+ path: string,
+ public meta: Meta,
+ public specFilePath: string,
+ public sectionsFilePath: string
+ ) {
+ super(source, path)
+ }
+
+ async load() {
+ const specContents = await readFile(this.specFilePath, 'utf8')
+ const refSectionsContents = await readFile(this.sectionsFilePath, 'utf8')
+
+ const refSections: ReferenceSection[] = JSON.parse(refSectionsContents)
+ const flattenedRefSections = flattenSections(refSections)
+
+ const checksum = createHash('sha256')
+ .update(specContents + refSectionsContents)
+ .digest('base64')
+
+ const specSections = this.getSpecSections(specContents)
+
+ const sections = flattenedRefSections
+ .map((refSection) => {
+ const specSection = this.matchSpecSection(specSections, refSection.id)
+
+ if (!specSection) {
+ return
+ }
+
+ return {
+ heading: refSection.title,
+ slug: refSection.slug,
+ content: `${this.meta.title} for ${refSection.title}:\n${this.formatSection(
+ specSection,
+ refSection
+ )}`,
+ }
+ })
+ .filter((section) => !!section)
+
+ this.checksum = checksum
+ this.sections = sections
+
+ return {
+ checksum,
+ sections,
+ meta: this.meta,
+ }
+ }
+
+ abstract getSpecSections(specContents: string): SpecSection[]
+ abstract matchSpecSection(specSections: SpecSection[], id: string): SpecSection
+ abstract formatSection(specSection: SpecSection, refSection: ReferenceSection): string
+}
+
+class OpenApiEmbeddingSource extends ReferenceEmbeddingSource<enrichedOperation> {
+ getSpecSections(specContents: string): enrichedOperation[] {
+ const spec: OpenAPIV3.Document<{}> = JSON.parse(specContents)
+
+ const generatedSpec = gen_v3(spec, '', {
+ apiUrl: 'apiv0',
+ })
+
+ return generatedSpec.operations
+ }
+ matchSpecSection(operations: enrichedOperation[], id: string): enrichedOperation {
+ return operations.find((operation) => operation.operationId === id)
+ }
+ formatSection(specOperation: enrichedOperation) {
+ const { summary, description, operation, path, tags } = specOperation
+ return JSON.stringify({
+ summary,
+ description,
+ operation,
+ path,
+ tags,
+ })
+ }
+}
+
+class ClientLibEmbeddingSource extends ReferenceEmbeddingSource<IFunctionDefinition> {
+ getSpecSections(specContents: string): IFunctionDefinition[] {
+ const spec = yaml.load(specContents) as ISpec
+
+ return spec.functions
+ }
+ matchSpecSection(functionDefinitions: IFunctionDefinition[], id: string): IFunctionDefinition {
+ return functionDefinitions.find((functionDefinition) => functionDefinition.id === id)
+ }
+ formatSection(functionDefinition: IFunctionDefinition, refSection: ReferenceSection): string {
+ const { title } = refSection
+ const { description, title: functionName } = functionDefinition
+
+ return JSON.stringify({
+ title,
+ description,
+ functionName,
+ })
+ }
+}
+
+class CliEmbeddingSource extends ReferenceEmbeddingSource<CliCommand> {
+ getSpecSections(specContents: string): CliCommand[] {
+ const spec = yaml.load(specContents) as CliSpec
+
+ return spec.commands
+ }
+ matchSpecSection(cliCommands: CliCommand[], id: string): CliCommand {
+ return cliCommands.find((cliCommand) => cliCommand.id === id)
+ }
+ formatSection(cliCommand: CliCommand): string {
+ const { summary, description, usage } = cliCommand
+ return JSON.stringify({
+ summary,
+ description,
+ usage,
+ })
+ }
+}
+
+type EmbeddingSource =
+ | MarkdownEmbeddingSource
+ | OpenApiEmbeddingSource
+ | ClientLibEmbeddingSource
+ | CliEmbeddingSource
+
async function generateEmbeddings() {
// TODO: use better CLI lib like yargs
const args = process.argv.slice(2)
@@ -237,14 +411,65 @@ async function generateEmbeddings() {
const supabaseClient = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL,
- process.env.SUPABASE_SERVICE_ROLE_KEY
+ process.env.SUPABASE_SERVICE_ROLE_KEY,
+ {
+ auth: {
+ persistSession: false,
+ autoRefreshToken: false,
+ },
+ }
)
- const markdownFiles = (await walk('pages'))
- .filter(({ path }) => /\.mdx?$/.test(path))
- .filter(({ path }) => !ignoredFiles.includes(path))
-
- console.log(`Discovered ${markdownFiles.length} pages`)
+ const embeddingSources: EmbeddingSource[] = [
+ new OpenApiEmbeddingSource(
+ 'api',
+ '/reference/api',
+ { title: 'Management API Reference' },
+ '../../spec/transforms/api_v0_openapi_deparsed.json',
+ '../../spec/common-api-sections.json'
+ ),
+ new ClientLibEmbeddingSource(
+ 'js-lib',
+ '/reference/javascript',
+ { title: 'JavaScript Reference' },
+ '../../spec/supabase_js_v2.yml',
+ '../../spec/common-client-libs-sections.json'
+ ),
+ new ClientLibEmbeddingSource(
+ 'dart-lib',
+ '/reference/dart',
+ { title: 'Dart Reference' },
+ '../../spec/supabase_dart_v1.yml',
+ '../../spec/common-client-libs-sections.json'
+ ),
+ new ClientLibEmbeddingSource(
+ 'python-lib',
+ '/reference/python',
+ { title: 'Python Reference' },
+ '../../spec/supabase_py_v2.yml',
+ '../../spec/common-client-libs-sections.json'
+ ),
+ new ClientLibEmbeddingSource(
+ 'csharp-lib',
+ '/reference/csharp',
+ { title: 'C# Reference' },
+ '../../spec/supabase_csharp_v0.yml',
+ '../../spec/common-client-libs-sections.json'
+ ),
+ new CliEmbeddingSource(
+ 'cli',
+ '/reference/cli',
+ { title: 'CLI Reference' },
+ '../../spec/cli_v1_commands.yaml',
+ '../../spec/common-cli-sections.json'
+ ),
+ ...(await walk('pages'))
+ .filter(({ path }) => /\.mdx?$/.test(path))
+ .filter(({ path }) => !ignoredFiles.includes(path))
+ .map((entry) => new MarkdownEmbeddingSource('guide', entry.path)),
+ ]
+
+ console.log(`Discovered ${embeddingSources.length} pages`)
if (!shouldRefresh) {
console.log('Checking which pages are new or have changed')
@@ -252,14 +477,11 @@ async function generateEmbeddings() {
console.log('Refresh flag set, re-generating all pages')
}
- for (const markdownFile of markdownFiles) {
- const path = markdownFile.path.replace(/^pages/, '').replace(/\.mdx?$/, '')
- const parentPath = markdownFile.parentPath?.replace(/^pages/, '').replace(/\.mdx?$/, '')
+ for (const embeddingSource of embeddingSources) {
+ const { type, source, path, parentPath } = embeddingSource
try {
- const contents = await readFile(markdownFile.path, 'utf8')
-
- const { checksum, meta, sections } = processMdxForSearch(contents)
+ const { checksum, meta, sections } = await embeddingSource.load()
// Check for existing page in DB and compare checksums
const { error: fetchPageError, data: existingPage } = await supabaseClient
@@ -345,6 +567,8 @@ async function generateEmbeddings() {
{
checksum: null,
path,
+ type,
+ source,
meta,
parent_page_id: parentPage?.id,
},
diff --git a/package.json b/package.json
index 27c148a2ab9..391cb08d37d 100644
--- a/package.json
+++ b/package.json
@@ -29,7 +29,8 @@
"test": "jest",
"test:studio": "turbo run test --filter=studio",
"perf:kong": "ab -t 5 -c 20 -T application/json http://localhost:8000/",
- "perf:meta": "ab -t 5 -c 20 -T application/json http://localhost:5555/tables"
+ "perf:meta": "ab -t 5 -c 20 -T application/json http://localhost:5555/tables",
+ "generate:types": "supabase gen types typescript --local > ./supabase/functions/common/database-types.ts"
},
"devDependencies": {
"@types/json-stringify-safe": "^5.0.0",
diff --git a/supabase/functions/common/database-types.ts b/supabase/functions/common/database-types.ts
new file mode 100644
index 00000000000..bf0addcb2cc
--- /dev/null
+++ b/supabase/functions/common/database-types.ts
@@ -0,0 +1,319 @@
+export type Json =
+ | string
+ | number
+ | boolean
+ | null
+ | { [key: string]: Json }
+ | Json[]
+
+export interface Database {
+ graphql_public: {
+ Tables: {
+ [_ in never]: never
+ }
+ Views: {
+ [_ in never]: never
+ }
+ Functions: {
+ graphql: {
+ Args: {
+ operationName?: string
+ query?: string
+ variables?: Json
+ extensions?: Json
+ }
+ Returns: Json
+ }
+ }
+ Enums: {
+ [_ in never]: never
+ }
+ CompositeTypes: {
+ [_ in never]: never
+ }
+ }
+ public: {
+ Tables: {
+ page: {
+ Row: {
+ checksum: string | null
+ id: number
+ meta: Json | null
+ parent_page_id: number | null
+ path: string
+ source: string | null
+ type: string | null
+ }
+ Insert: {
+ checksum?: string | null
+ id?: number
+ meta?: Json | null
+ parent_page_id?: number | null
+ path: string
+ source?: string | null
+ type?: string | null
+ }
+ Update: {
+ checksum?: string | null
+ id?: number
+ meta?: Json | null
+ parent_page_id?: number | null
+ path?: string
+ source?: string | null
+ type?: string | null
+ }
+ }
+ page_section: {
+ Row: {
+ content: string | null
+ embedding: unknown | null
+ heading: string | null
+ id: number
+ page_id: number
+ slug: string | null
+ token_count: number | null
+ }
+ Insert: {
+ content?: string | null
+ embedding?: unknown | null
+ heading?: string | null
+ id?: number
+ page_id: number
+ slug?: string | null
+ token_count?: number | null
+ }
+ Update: {
+ content?: string | null
+ embedding?: unknown | null
+ heading?: string | null
+ id?: number
+ page_id?: number
+ slug?: string | null
+ token_count?: number | null
+ }
+ }
+ }
+ Views: {
+ [_ in never]: never
+ }
+ Functions: {
+ get_page_parents: {
+ Args: {
+ page_id: number
+ }
+ Returns: {
+ id: number
+ parent_page_id: number
+ path: string
+ meta: Json
+ }[]
+ }
+ ivfflathandler: {
+ Args: {
+ "": unknown
+ }
+ Returns: unknown
+ }
+ match_page_sections: {
+ Args: {
+ embedding: unknown
+ match_threshold: number
+ match_count: number
+ min_content_length: number
+ }
+ Returns: {
+ id: number
+ page_id: number
+ slug: string
+ heading: string
+ content: string
+ similarity: number
+ }[]
+ }
+ vector_avg: {
+ Args: {
+ "": number[]
+ }
+ Returns: unknown
+ }
+ vector_dims: {
+ Args: {
+ "": unknown
+ }
+ Returns: number
+ }
+ vector_norm: {
+ Args: {
+ "": unknown
+ }
+ Returns: number
+ }
+ vector_out: {
+ Args: {
+ "": unknown
+ }
+ Returns: unknown
+ }
+ vector_send: {
+ Args: {
+ "": unknown
+ }
+ Returns: string
+ }
+ vector_typmod_in: {
+ Args: {
+ "": unknown[]
+ }
+ Returns: number
+ }
+ }
+ Enums: {
+ [_ in never]: never
+ }
+ CompositeTypes: {
+ [_ in never]: never
+ }
+ }
+ storage: {
+ Tables: {
+ buckets: {
+ Row: {
+ created_at: string | null
+ id: string
+ name: string
+ owner: string | null
+ public: boolean | null
+ updated_at: string | null
+ }
+ Insert: {
+ created_at?: string | null
+ id: string
+ name: string
+ owner?: string | null
+ public?: boolean | null
+ updated_at?: string | null
+ }
+ Update: {
+ created_at?: string | null
+ id?: string
+ name?: string
+ owner?: string | null
+ public?: boolean | null
+ updated_at?: string | null
+ }
+ }
+ migrations: {
+ Row: {
+ executed_at: string | null
+ hash: string
+ id: number
+ name: string
+ }
+ Insert: {
+ executed_at?: string | null
+ hash: string
+ id: number
+ name: string
+ }
+ Update: {
+ executed_at?: string | null
+ hash?: string
+ id?: number
+ name?: string
+ }
+ }
+ objects: {
+ Row: {
+ bucket_id: string | null
+ created_at: string | null
+ id: string
+ last_accessed_at: string | null
+ metadata: Json | null
+ name: string | null
+ owner: string | null
+ path_tokens: string[] | null
+ updated_at: string | null
+ }
+ Insert: {
+ bucket_id?: string | null
+ created_at?: string | null
+ id?: string
+ last_accessed_at?: string | null
+ metadata?: Json | null
+ name?: string | null
+ owner?: string | null
+ path_tokens?: string[] | null
+ updated_at?: string | null
+ }
+ Update: {
+ bucket_id?: string | null
+ created_at?: string | null
+ id?: string
+ last_accessed_at?: string | null
+ metadata?: Json | null
+ name?: string | null
+ owner?: string | null
+ path_tokens?: string[] | null
+ updated_at?: string | null
+ }
+ }
+ }
+ Views: {
+ [_ in never]: never
+ }
+ Functions: {
+ extension: {
+ Args: {
+ name: string
+ }
+ Returns: string
+ }
+ filename: {
+ Args: {
+ name: string
+ }
+ Returns: string
+ }
+ foldername: {
+ Args: {
+ name: string
+ }
+ Returns: string[]
+ }
+ get_size_by_bucket: {
+ Args: Record<PropertyKey, never>
+ Returns: {
+ size: number
+ bucket_id: string
+ }[]
+ }
+ search: {
+ Args: {
+ prefix: string
+ bucketname: string
+ limits?: number
+ levels?: number
+ offsets?: number
+ search?: string
+ sortcolumn?: string
+ sortorder?: string
+ }
+ Returns: {
+ name: string
+ id: string
+ updated_at: string
+ created_at: string
+ last_accessed_at: string
+ metadata: Json
+ }[]
+ }
+ }
+ Enums: {
+ [_ in never]: never
+ }
+ CompositeTypes: {
+ [_ in never]: never
+ }
+ }
+}
+
diff --git a/supabase/functions/search/index.ts b/supabase/functions/search/index.ts
index 93cb0812c9b..1b475eecf5f 100644
--- a/supabase/functions/search/index.ts
+++ b/supabase/functions/search/index.ts
@@ -2,6 +2,7 @@ import { serve } from 'https://deno.land/[email protected]/http/server.ts'
import 'https://deno.land/x/[email protected]/mod.ts'
import { createClient } from 'https://esm.sh/@supabase/[email protected]'
import { Configuration, OpenAIApi } from 'https://esm.sh/[email protected]'
+import { Database } from '../common/database-types.ts'
import { ApplicationError, UserError } from '../common/errors.ts'
const openAiKey = Deno.env.get('OPENAI_KEY')
@@ -46,7 +47,7 @@ serve(async (req) => {
const sanitizedQuery = query.trim()
- const supabaseClient = createClient(supabaseUrl, supabaseServiceKey)
+ const supabaseClient = createClient<Database>(supabaseUrl, supabaseServiceKey)
const configuration = new Configuration({ apiKey: openAiKey })
const openai = new OpenAIApi(configuration)
@@ -73,7 +74,6 @@ serve(async (req) => {
}
const [{ embedding }] = embeddingResponse.data.data
-
const { error: matchError, data: pageSections } = await supabaseClient.rpc(
'match_page_sections',
{
@@ -85,7 +85,7 @@ serve(async (req) => {
)
if (matchError || !pageSections) {
- throw new ApplicationError('Failed to match page sections', matchError)
+ throw new ApplicationError('Failed to match page sections', matchError ?? undefined)
}
const uniquePageIds = pageSections
diff --git a/supabase/migrations/20230228205709_page_source.sql b/supabase/migrations/20230228205709_page_source.sql
new file mode 100644
index 00000000000..04ef19ff810
--- /dev/null
+++ b/supabase/migrations/20230228205709_page_source.sql
@@ -0,0 +1,3 @@
+alter table "public"."page"
+add column type text,
+add column source text;