Skip to content

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

change spec to generator

Copplebec787735f99
diff --git a/packages/generator/LegacyReferenceGenerator.ts b/packages/generator/LegacyReferenceGenerator.ts
new file mode 100644
index 00000000000..41469ff0fea
--- /dev/null
+++ b/packages/generator/LegacyReferenceGenerator.ts
@@ -0,0 +1,329 @@
+// @ts-nocheck
+
+/**
+ * Usage:
+ * ts-node ReferenceGenerator.ts -o {output_dir} {input}.yml
+ *
+ * Example:
+ * ts-node ReferenceGenerator.ts -o docs/client spec/supabase.yml
+ */
+
+import Example from './src/legacy/components/Example'
+import Page from './src/legacy/components/Page'
+import Sidebar from './src/legacy/components/Sidebar'
+import SidebarCategory from './src/legacy/components/SidebarCategory'
+import Tab from './src/legacy/components/Tab'
+import {
+ slugify,
+ tsDocCommentToMdComment,
+ writeToDisk,
+} from './src/legacy/lib/helpers'
+import { TsDoc, OpenRef } from './src/legacy/definitions'
+
+const yaml = require('js-yaml')
+const fs = require('fs')
+
+const main = (fileNames: string[], options: any) => {
+ try {
+ const outputDir = options.o || options.output || ''
+ fileNames.forEach((inputFileName) => {
+ gen(inputFileName, outputDir)
+ })
+ return
+ } catch (e) {
+ console.log(e)
+ }
+}
+
+async function gen(inputFileName: string, outputDir: string) {
+ const docSpec = yaml.safeLoad(fs.readFileSync(inputFileName, 'utf8'))
+ const defRef = docSpec.info.definition
+ ? fs.readFileSync(docSpec.info.definition, 'utf8')
+ : '{}'
+
+ const definition = JSON.parse(defRef)
+ const id = docSpec.info.id
+ const allLanguages = docSpec.info.libraries
+ const pages = Object.entries(docSpec.pages).map(
+ ([name, x]: [string, OpenRef.Page]) => ({
+ ...x,
+ pageName: name,
+ })
+ )
+
+ // // Sidebar
+ // const inputFileNameToSnakeCase = inputFileName
+ // .replace('/', '_')
+ // .replace('.yml', '')
+ // const sidebarFileName = `sidebar_${inputFileNameToSnakeCase}.js`
+ // const sidebar = generateSidebar(docSpec)
+ // await writeToDisk(sidebarFileName, sidebar)
+ // console.log('Sidebar created: ', sidebarFileName)
+
+ // Index Page
+ const indexFilename = outputDir + `/index.mdx`
+ const index = generateDocsIndexPage(docSpec, inputFileName)
+ await writeToDisk(indexFilename, index)
+ console.log('The index was saved: ', indexFilename)
+
+ // Generate Pages
+ pages.forEach(async (pageSpec: OpenRef.Page) => {
+ try {
+ const slug = slugify(pageSpec.pageName)
+ const hasTsRef = pageSpec['$ref'] || null
+ const tsDefinition = hasTsRef && extractTsDocNode(hasTsRef, definition)
+ if (hasTsRef && !tsDefinition)
+ throw new Error('Definition not found: ' + hasTsRef)
+
+ const description =
+ pageSpec.description ||
+ tsDocCommentToMdComment(getDescriptionFromDefintion(tsDefinition))
+
+ // Create page
+ const content = Page({
+ slug: (docSpec.info.slugPrefix || '') + slug,
+ id: slug,
+ specFileName: inputFileName,
+ title: pageSpec.title || pageSpec.pageName,
+ description,
+ parameters: hasTsRef ? generateParameters(tsDefinition) : '',
+ spotlight: generateSpotlight(
+ id,
+ pageSpec['examples'] || [],
+ allLanguages
+ ),
+ examples: generateExamples(
+ id,
+ pageSpec['examples'] || [],
+ allLanguages
+ ),
+ notes: pageSpec.notes,
+ })
+
+ // Write to disk
+ const dest = outputDir + `/${slug}.mdx`
+ await writeToDisk(dest, content)
+ console.log('Saved: ', dest)
+ } catch (error) {
+ console.error(error)
+ }
+ })
+}
+
+function generateParameters(tsDefinition: any) {
+ let functionDeclaration = null
+ if (tsDefinition.kindString == 'Method') {
+ functionDeclaration = tsDefinition
+ } else if (tsDefinition.kindString == 'Constructor') {
+ functionDeclaration = tsDefinition
+ } else functionDeclaration = tsDefinition?.type?.declaration
+ if (!functionDeclaration) return ''
+
+ const paramDefinitions: TsDoc.TypeDefinition[] =
+ functionDeclaration.signatures[0].parameters // PMC: seems flaky.. why the [0]?
+ if (!paramDefinitions) return ''
+
+ // const paramsComments: TsDoc.CommentTag = tsDefinition.comment?.tags?.filter(x => x.tag == 'param')
+ let parameters = paramDefinitions
+ .map((x) => recurseThroughParams(x))
+ .join(`\n`)
+ return methodListGroup(parameters)
+}
+
+function getDescriptionFromDefintion(tsDefinition) {
+ if (!tsDefinition) return null
+ if (
+ ['Method', 'Constructor', 'Constructor signature'].includes(
+ tsDefinition.kindString
+ )
+ )
+ return tsDefinition?.signatures[0].comment
+ else return tsDefinition?.comment || ''
+}
+
+function recurseThroughParams(paramDefinition: TsDoc.TypeDefinition) {
+ let children = paramDefinition.type?.declaration?.children
+ const labelParams = {
+ name: paramDefinition.name,
+ isOptional: !!paramDefinition.flags.isOptional,
+ type: extractParamTypeAsString(paramDefinition),
+ description: paramDefinition.comment
+ ? tsDocCommentToMdComment(paramDefinition.comment)
+ : null,
+ }
+ let subContent = ''
+
+ if (!!children) {
+ let properties = children
+ .sort((a, b) => a.name.localeCompare(b.name)) // first alphabetical
+ .sort((a, b) => (a.flags?.isOptional ? 1 : -1)) // required params first
+ .map((x) => recurseThroughParams(x))
+ let heading = `<h5 class="method-list-title method-list-title-isChild expanded">Properties</h5>`
+ subContent = methodListGroup([heading].concat(properties).join('\n'))
+ }
+
+ return methodListItemLabel(labelParams, subContent)
+}
+
+const methodListGroup = (items) => `
+<ul className="method-list-group">
+ ${items}
+</ul>
+`
+
+const methodListItemLabel = (
+ { name, isOptional, type, description },
+ subContent
+) => `
+<li className="method-list-item">
+ <h4 className="method-list-item-label">
+ <span className="method-list-item-label-name">
+ ${name}
+ </span>
+ <span className="method-list-item-label-badge ${!isOptional && 'required'}">
+ ${isOptional ? 'optional' : 'required'}
+ </span>
+ <span className="method-list-item-validation">
+ ${type}
+ </span>
+ </h4>
+ <div class="method-list-item-description">
+
+${description ? description : 'No description provided. '}
+
+ </div>
+ ${subContent}
+</li>
+`
+
+function generateExamples(id: string, specExamples: any, allLanguages: any) {
+ return specExamples.map((example) => {
+ let allTabs = example.hideCodeBlock
+ ? ''
+ : generateCodeBlocks(allLanguages, example)
+ return Example({
+ name: example.name,
+ description: example.description,
+ tabs: allTabs,
+ note: example.note,
+ })
+ })
+}
+
+/**
+ * A spotlight is an example which appears at the top of the page.
+ */
+function generateSpotlight(
+ id: string,
+ specExamples: any | any[],
+ allLanguages: any
+) {
+ if (!Array.isArray(specExamples)) {
+ throw new Error(
+ `Examples for each spec should be an array, received: \n${specExamples}`
+ )
+ }
+ const spotlight =
+ (specExamples && specExamples.find((x) => x.isSpotlight)) || null
+ const spotlightContent = !spotlight
+ ? ''
+ : generateCodeBlocks(allLanguages, spotlight)
+ return spotlightContent
+}
+
+function generateTabs(allLanguages: any, example: any) {
+ return allLanguages
+ .map((library) => {
+ let content = example[library.id] || notImplemented
+ return Tab(library.id, content)
+ })
+ .join('\n')
+}
+
+function generateCodeBlocks(allLanguages: any, example: any) {
+ return allLanguages
+ .map((library) => {
+ let content = example[library.id] || notImplemented
+ return content
+ })
+ .join('\n')
+}
+
+const notImplemented = `
+\`\`\`
+Not yet implemented
+\`\`\`
+`
+
+function extractParamTypeAsString(paramDefinition) {
+ if (paramDefinition.type?.name) {
+ return `<code>${paramDefinition.type.name}</code>`
+ }
+ if (paramDefinition.type?.type == 'union') {
+ return paramDefinition.type.types
+ .map((x) =>
+ x.value
+ ? `<code>${x.value}</code>`
+ : x.name
+ ? `<code>${x.name}</code>`
+ : x.type
+ ? `<code>${x.type}</code>`
+ : ''
+ )
+ .join(' | ')
+ } else {
+ return '<code>object</code>'
+ }
+}
+
+/**
+ * Iterates through the definition to find the correct definition.
+ * You can pass it a deeply nested node using dot notation. eg: 'LoggedInUser.data.email'
+ */
+function extractTsDocNode(nodeToFind: string, definition: any) {
+ const nodePath = nodeToFind.split('.')
+ let i = 0
+ let previousNode = definition
+ let currentNode = definition
+ while (i < nodePath.length) {
+ previousNode = currentNode
+ currentNode =
+ previousNode.children.find((x) => x.name == nodePath[i]) || null
+ if (currentNode == null) {
+ console.log(
+ `Cant find ${nodePath[i]} in ${previousNode.children.map(
+ (x) => '\n' + x.name
+ )}`
+ )
+ break
+ }
+ i++
+ }
+ return currentNode
+}
+
+function generateSidebar(docSpec: any) {
+ let path = docSpec.info.docs.path || ''
+ let categories = docSpec.info.docs.sidebar.map((x) => {
+ const items = x.items.map((item) => {
+ let slug = slugify(item)
+ return `'${path}${slug}'`
+ })
+ return SidebarCategory(x.name, items)
+ })
+ return Sidebar(categories)
+}
+
+function generateDocsIndexPage(docSpec: any, inputFileName: string) {
+ return Page({
+ slug: slugify(docSpec.info.title),
+ id: 'index',
+ title: docSpec.info.title,
+ specFileName: inputFileName,
+ description: docSpec.info.description,
+ })
+}
+
+// Run everything
+const argv = require('minimist')(process.argv.slice(2))
+main(argv['_'], argv)
diff --git a/packages/spec/index.ts b/packages/generator/index.ts
similarity index 100%
rename from packages/spec/index.ts
rename to packages/generator/index.ts
diff --git a/packages/spec/package-lock.json b/packages/generator/package-lock.json
similarity index 100%
rename from packages/spec/package-lock.json
rename to packages/generator/package-lock.json
diff --git a/packages/spec/package.json b/packages/generator/package.json
similarity index 92%
rename from packages/spec/package.json
rename to packages/generator/package.json
index 7dcdd9b9119..b03a885d4eb 100644
--- a/packages/spec/package.json
+++ b/packages/generator/package.json
@@ -12,6 +12,8 @@
"cli:gen:config": "ts-node ./index.ts gen --type config --input ../../spec/cli_v1_config.yaml --output ../../apps/reference/_cli/generated/config.mdx",
"gotrue:gen": "npm run gotrue:gen:config",
"gotrue:gen:config": "ts-node ./index.ts gen --type config --input ../../spec/gotrue_v1_config.yaml --output ../../apps/reference/_gotrue/config.mdx",
+ "dart:gen": "npm run dart:gen:ref",
+ "dart:gen:ref": "ts-node ./LegacyReferenceGenerator.ts gen -o ../../apps/reference/_dart_generated ../../spec/supabase_dart_v1_ref.yaml",
"storage:gen": "npm run storage:gen:api && npm run storage:gen:config",
"storage:gen:api": "ts-node ./index.ts gen --type api --input ../../spec/transforms/storage_v0_openapi_deparsed.json --output ../../apps/reference/_storage/generated/usage.mdx",
"storage:gen:config": "ts-node ./index.ts gen --type config --input ../../spec/storage_v1_config.yaml --output ../../apps/reference/_storage/generated/config.mdx",
diff --git a/packages/spec/src/docs/api.ts b/packages/generator/src/docs/api.ts
similarity index 100%
rename from packages/spec/src/docs/api.ts
rename to packages/generator/src/docs/api.ts
diff --git a/packages/spec/src/docs/cli.ts b/packages/generator/src/docs/cli.ts
similarity index 100%
rename from packages/spec/src/docs/cli.ts
rename to packages/generator/src/docs/cli.ts
diff --git a/packages/spec/src/docs/config.ts b/packages/generator/src/docs/config.ts
similarity index 100%
rename from packages/spec/src/docs/config.ts
rename to packages/generator/src/docs/config.ts
diff --git a/packages/spec/src/docs/helpers.ts b/packages/generator/src/docs/helpers.ts
similarity index 100%
rename from packages/spec/src/docs/helpers.ts
rename to packages/generator/src/docs/helpers.ts
diff --git a/packages/spec/src/docs/index.ts b/packages/generator/src/docs/index.ts
similarity index 100%
rename from packages/spec/src/docs/index.ts
rename to packages/generator/src/docs/index.ts
diff --git a/packages/spec/src/docs/sdk.ts b/packages/generator/src/docs/sdk.ts
similarity index 100%
rename from packages/spec/src/docs/sdk.ts
rename to packages/generator/src/docs/sdk.ts
diff --git a/packages/spec/src/docs/templates/ApiTemplate.ts b/packages/generator/src/docs/templates/ApiTemplate.ts
similarity index 100%
rename from packages/spec/src/docs/templates/ApiTemplate.ts
rename to packages/generator/src/docs/templates/ApiTemplate.ts
diff --git a/packages/spec/src/docs/templates/CliTemplate.ts b/packages/generator/src/docs/templates/CliTemplate.ts
similarity index 100%
rename from packages/spec/src/docs/templates/CliTemplate.ts
rename to packages/generator/src/docs/templates/CliTemplate.ts
diff --git a/packages/spec/src/docs/templates/ConfigTemplate.ts b/packages/generator/src/docs/templates/ConfigTemplate.ts
similarity index 100%
rename from packages/spec/src/docs/templates/ConfigTemplate.ts
rename to packages/generator/src/docs/templates/ConfigTemplate.ts
diff --git a/packages/spec/src/docs/templates/SdkTemplate.ts b/packages/generator/src/docs/templates/SdkTemplate.ts
similarity index 100%
rename from packages/spec/src/docs/templates/SdkTemplate.ts
rename to packages/generator/src/docs/templates/SdkTemplate.ts
diff --git a/packages/generator/src/legacy/components/Example.ts b/packages/generator/src/legacy/components/Example.ts
new file mode 100644
index 00000000000..c77a743a269
--- /dev/null
+++ b/packages/generator/src/legacy/components/Example.ts
@@ -0,0 +1,24 @@
+type params = { name: string; description: string; tabs: string; note: string; }
+
+const Example = ({name, description = '', tabs = '', note = ''}: params) => {
+ if (note !== '') {
+ const [noteTitle, ...noteText] = note.split('\n');
+ console.log(noteText);
+ note = `
+:::note ${noteTitle}
+ ${noteText.join('\n')}
+:::
+`;
+ }
+ return `
+### ${name}
+
+${description}
+
+${tabs}
+
+${note}
+`.trim()
+}
+
+export default Example
diff --git a/packages/generator/src/legacy/components/Page.ts b/packages/generator/src/legacy/components/Page.ts
new file mode 100644
index 00000000000..b360ff495c1
--- /dev/null
+++ b/packages/generator/src/legacy/components/Page.ts
@@ -0,0 +1,67 @@
+const EDIT_BASE_URL = 'https://github.com/supabase/supabase/edit/master/web'
+
+type PageParmas = {
+ id: string
+ title: string
+ slug: string
+ specFileName: string
+ description?: string
+ parameters?: string
+ examples?: string[]
+ spotlight?: string
+ notes?: string
+ result?: string
+ errors?: string
+}
+
+const Page = ({
+ id,
+ title,
+ slug,
+ specFileName,
+ description = '',
+ parameters = '',
+ examples = [],
+ spotlight = '',
+ notes = '',
+ result = '',
+ errors = '',
+}: PageParmas) =>
+ `
+---
+id: ${id}
+title: "${title}"
+slug: ${slug}
+custom_edit_url: ${EDIT_BASE_URL}/${specFileName}
+---
+
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+${description}
+
+${spotlight}
+
+${parameters ? `## Parameters` : ''}
+
+${parameters}
+
+${notes ? '## Notes' : ''}
+
+${notes}
+
+${result ? `## Result` : ''}
+
+${result}
+
+${errors ? `## Errors` : ''}
+
+${errors}
+
+${examples.length > 0 ? '## Examples' : ''}
+
+${examples.join(`\n\n`)}
+
+`.trim()
+
+export default Page
diff --git a/packages/generator/src/legacy/components/Sidebar.ts b/packages/generator/src/legacy/components/Sidebar.ts
new file mode 100644
index 00000000000..4f756eae09b
--- /dev/null
+++ b/packages/generator/src/legacy/components/Sidebar.ts
@@ -0,0 +1,10 @@
+const Sidebar = (categories) =>
+ `
+module.exports = {
+ docs: [
+ ${categories.map((x) => x).join(',\n ')}
+ ],
+}
+`.trim()
+
+export default Sidebar
diff --git a/packages/generator/src/legacy/components/SidebarCategory.ts b/packages/generator/src/legacy/components/SidebarCategory.ts
new file mode 100644
index 00000000000..bc1826e0d69
--- /dev/null
+++ b/packages/generator/src/legacy/components/SidebarCategory.ts
@@ -0,0 +1,8 @@
+export default function SidebarCategory(name, items) {
+ return `{
+ type: 'category',
+ label: '${name}',
+ items: [${items.join(', ')}],
+ collapsed: true,
+ }`
+}
diff --git a/packages/generator/src/legacy/components/Tab.ts b/packages/generator/src/legacy/components/Tab.ts
new file mode 100644
index 00000000000..9395cd0515e
--- /dev/null
+++ b/packages/generator/src/legacy/components/Tab.ts
@@ -0,0 +1,10 @@
+const Tab = (library, exampleText) =>
+ `
+<TabItem value="${library}">
+
+${exampleText}
+
+</TabItem>
+`.trim()
+
+export default Tab
diff --git a/packages/generator/src/legacy/components/Tabs.ts b/packages/generator/src/legacy/components/Tabs.ts
new file mode 100644
index 00000000000..9e78f07d8b2
--- /dev/null
+++ b/packages/generator/src/legacy/components/Tabs.ts
@@ -0,0 +1,13 @@
+const Tabs = (id, libraries = [], examples = []) =>
+ `
+<Tabs
+ defaultValue="${libraries[0].id}"
+ groupId="${id}"
+ values={[${libraries.map((x) => `{ label: '${x.name}', value: '${x.id}' }`).toString()}]}>
+
+${examples}
+
+</Tabs>
+`.trim()
+
+export default Tabs
diff --git a/packages/generator/src/legacy/definitions.ts b/packages/generator/src/legacy/definitions.ts
new file mode 100644
index 00000000000..96f1f44dfe3
--- /dev/null
+++ b/packages/generator/src/legacy/definitions.ts
@@ -0,0 +1,33 @@
+export namespace TsDoc {
+ export type DocComment = {
+ shortText?: string
+ text?: string
+ tags?: CommentTag[]
+ }
+ export type CommentTag = {
+ tag: 'param' | 'returns'
+ text: string
+ param: string
+ }
+
+ export type TypeDefinition = {
+ id: string
+ name: string
+ kind: number
+ kindString: 'Parameter' | 'Method'
+ comment?: CommentTag
+ flags: { isExported: boolean; isOptional?: boolean }
+ type: { type: string; name: string; declaration: TypeDefinition }
+ children: TypeDefinition[]
+ }
+}
+
+export namespace OpenRef {
+ export type Page = {
+ pageName: string
+ title?: string
+ description?: string
+ notes?: string
+ // $ref?: string // reference to a TSDoc node
+ }
+}
diff --git a/packages/generator/src/legacy/lib/helpers.ts b/packages/generator/src/legacy/lib/helpers.ts
new file mode 100644
index 00000000000..9df412e7708
--- /dev/null
+++ b/packages/generator/src/legacy/lib/helpers.ts
@@ -0,0 +1,54 @@
+import { TsDoc } from '../definitions'
+
+const fs = require('fs')
+
+/**
+ * tsDocCommentToMdParams()
+ */
+export const tsDocCommentToMdParams = (tags?: TsDoc.CommentTag[]) =>
+ tags
+ .filter((x) => x.tag == 'param')
+ .map((x) =>
+ `
+tag
+
+`.trim()
+ )
+ .join('\n')
+
+/**
+ * tsDocCommentToMarkdown()
+ */
+export const tsDocCommentToMdComment = (commentObject: TsDoc.DocComment) =>
+ `
+${commentObject?.shortText || ''}
+
+${commentObject?.text || ''}
+
+`.trim()
+
+/**
+ * slugify()
+ */
+export const slugify = (text) => {
+ return text
+ .toString()
+ .toLowerCase()
+ .replace(/[. )(]/g, '-') // Replace spaces and brackets -
+ .replace(/[^\w\-]+/g, '') // Remove all non-word chars
+ .replace(/\-\-+/g, '-') // Replace multiple - with single -
+ .replace(/^-+/, '') // Trim - from start of text
+ .replace(/-+$/, '') // Trim - from end of text
+}
+
+/**
+ * writeToDisk()
+ */
+export const writeToDisk = (fileName: string, content: any) => {
+ return new Promise((resolve, reject) => {
+ fs.writeFile(fileName, content, (err) => {
+ if (err) return reject(err)
+ else return resolve(true)
+ })
+ })
+}
diff --git a/packages/spec/src/types/CliSpec.ts b/packages/generator/src/types/CliSpec.ts
similarity index 100%
rename from packages/spec/src/types/CliSpec.ts
rename to packages/generator/src/types/CliSpec.ts
diff --git a/packages/spec/src/types/ConfigSpec.ts b/packages/generator/src/types/ConfigSpec.ts
similarity index 100%
rename from packages/spec/src/types/ConfigSpec.ts
rename to packages/generator/src/types/ConfigSpec.ts
diff --git a/packages/spec/src/types/SdkSpec.ts b/packages/generator/src/types/SdkSpec.ts
similarity index 100%
rename from packages/spec/src/types/SdkSpec.ts
rename to packages/generator/src/types/SdkSpec.ts
diff --git a/packages/spec/src/types/Spec.ts b/packages/generator/src/types/Spec.ts
similarity index 100%
rename from packages/spec/src/types/Spec.ts
rename to packages/generator/src/types/Spec.ts
diff --git a/packages/spec/tsconfig.json b/packages/generator/tsconfig.json
similarity index 100%
rename from packages/spec/tsconfig.json
rename to packages/generator/tsconfig.json