Skip to content

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

feat(docs): track last-changed date (#27016)

Chariscb8b43ff8e2b
diff --git a/apps/docs/package.json b/apps/docs/package.json
index 2ce3f0375ed..332686ad900 100644
--- a/apps/docs/package.json
+++ b/apps/docs/package.json
@@ -97,6 +97,7 @@
"jest-environment-jsdom": "^29.7.0",
"npm-run-all": "^4.1.5",
"openapi-types": "^12.1.3",
+ "simple-git": "^3.24.0",
"tsconfig": "*",
"tsx": "^4.6.2",
"typescript": "^5.4.3"
diff --git a/apps/docs/scripts/last-changed.ts b/apps/docs/scripts/last-changed.ts
new file mode 100644
index 00000000000..1151d52d241
--- /dev/null
+++ b/apps/docs/scripts/last-changed.ts
@@ -0,0 +1,272 @@
+/**
+ * Updates the `last_changed` table with new content changes.
+ *
+ * The default behavior is to match checksums to determine the `last_changed`
+ * date.
+ *
+ * Options:
+ *
+ * --reset, -r
+ * If the `reset` flag is given, the `last_changed` date is determined from
+ * the last Git commit date.
+ */
+
+import 'dotenv/config'
+
+import { createClient, type SupabaseClient } from '@supabase/supabase-js'
+import matter from 'gray-matter'
+import { createHash } from 'node:crypto'
+import { readdirSync } from 'node:fs'
+import { readFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { parseArgs } from 'node:util'
+import { simpleGit } from 'simple-git'
+
+import { Section } from './helpers.mdx'
+
+interface Options {
+ reset: boolean
+}
+
+interface Stats {
+ sectionsUpdated: number
+ sectionsRemoved: number
+}
+
+type SectionWithChecksum = Omit<Section, 'heading'> &
+ Pick<Required<Section>, 'heading'> & {
+ checksum: string
+ }
+
+const REQUIRED_ENV_VARS = {
+ SUPABASE_URL: 'NEXT_PUBLIC_SUPABASE_URL',
+ SERVICE_ROLE_KEY: 'SUPABASE_SERVICE_ROLE_KEY',
+} as const
+
+async function main() {
+ console.log('Updating content timestamps....')
+
+ checkEnv()
+
+ const { reset } = parseOptions()
+ const supabase = createSupabaseClient()
+
+ const stats: Stats = {
+ sectionsUpdated: 0,
+ sectionsRemoved: 0,
+ }
+
+ await updateContentDates({ reset, supabase, stats })
+
+ console.log('Content timestamps successfully updated')
+ console.log(` - ${stats.sectionsUpdated} sections updated`)
+ console.log(` - ${stats.sectionsRemoved} old sections removed`)
+}
+
+function checkEnv() {
+ const requiredEnvVars = Object.values(REQUIRED_ENV_VARS)
+
+ for (const variable of requiredEnvVars) {
+ if (!process.env[variable]) {
+ abortWithError(`Missing required environment variable: ${variable}`)
+ }
+ }
+}
+
+function abortWithError(message: string) {
+ console.error(message)
+ process.exit(1)
+}
+
+function parseOptions(): Options {
+ const args = process.argv.slice(2)
+ const options = {
+ reset: {
+ type: 'boolean',
+ short: 'r',
+ },
+ } as const
+
+ const {
+ values: { reset },
+ } = parseArgs({ args, options })
+ return { reset: reset ?? false }
+}
+
+function createSupabaseClient() {
+ return createClient(
+ process.env[REQUIRED_ENV_VARS.SUPABASE_URL],
+ process.env[REQUIRED_ENV_VARS.SERVICE_ROLE_KEY]
+ )
+}
+
+async function updateContentDates({
+ supabase,
+ reset,
+ stats,
+}: {
+ supabase: SupabaseClient
+ reset: boolean
+ stats: Stats
+}) {
+ const CONTENT_DIR = getContentDir()
+ const mdxFiles = await walkDir(CONTENT_DIR)
+
+ const timestamp = new Date()
+
+ const updateTasks: Array<Promise<void>> = []
+ for (const file of mdxFiles) {
+ const tasks = await updateTimestamps(file, { supabase, reset, timestamp, stats })
+ updateTasks.push(...tasks)
+ }
+ await Promise.all(updateTasks)
+
+ await cleanupObsoleteRows(timestamp, supabase, stats)
+}
+
+function getContentDir() {
+ return join(__dirname, '..', 'content')
+}
+
+async function walkDir(fullPath: string) {
+ const allFiles = readdirSync(fullPath, { withFileTypes: true, recursive: true })
+ const mdxFiles = allFiles
+ .filter((file) => file.isFile() && file.name.endsWith('.mdx'))
+ .map((file) => join(file.parentPath, file.name))
+ return mdxFiles
+}
+
+async function updateTimestamps(
+ filePath: string,
+ {
+ supabase,
+ reset,
+ timestamp,
+ stats,
+ }: { supabase: SupabaseClient; reset: boolean; timestamp: Date; stats: Stats }
+) {
+ try {
+ const content = await readFile(filePath, 'utf-8')
+ const sections = processMdx(content)
+ return sections.map((section) => {
+ if (reset) {
+ return updateTimestampsWithLastCommitDate(filePath, section, timestamp, supabase, stats)
+ } else {
+ throw Error('not implemented')
+ }
+ })
+ } catch (err) {
+ console.error(`Failed to update sections for file ${filePath}`)
+ }
+}
+
+function processMdx(rawContent: string): Array<SectionWithChecksum> {
+ const { content } = matter(rawContent)
+
+ const GLOBAL_HEADING_REGEX = /(?:^|\n)(?=#+\s+[^\n]+[\n$])/g
+ const sections = content.split(GLOBAL_HEADING_REGEX)
+
+ const seenHeadings = new Map<string, number>()
+
+ const HEADING_MATCH_REGEX = /^#+\s+([^\n]+)[\n$]/
+ const result: Array<SectionWithChecksum> = sections.map((section) => {
+ const rawHeading = section.match(HEADING_MATCH_REGEX)?.[1] ?? '[EMPTY]'
+
+ let heading = rawHeading
+ if (seenHeadings.has(rawHeading)) {
+ const idx = seenHeadings.get(rawHeading) + 1
+ seenHeadings.set(rawHeading, idx)
+ heading = `${rawHeading} (${idx})`
+ } else {
+ seenHeadings.set(rawHeading, 1)
+ }
+
+ const normalizedSection = section
+ .trim()
+ .replace(/[\n\t]/g, ' ')
+ .replace(/\s+/g, ' ')
+ const checksum = createHash('sha256').update(normalizedSection).digest('base64')
+
+ return {
+ heading,
+ content: normalizedSection,
+ checksum,
+ }
+ })
+
+ return result
+}
+
+async function updateTimestampsWithLastCommitDate(
+ filePath: string,
+ section: SectionWithChecksum,
+ timestamp: Date,
+ supabase: SupabaseClient,
+ stats: Stats
+) {
+ try {
+ const git = simpleGit()
+ const updatedAt = (await git.raw('log', '-1', '--format=%cI', filePath)).trim()
+
+ const contentDir = getContentDir()
+ const parentPage = `/content${filePath.replace(contentDir, '')}`
+
+ const { data, error } = await supabase
+ .from('last_changed')
+ .select('id')
+ .eq('parent_page', parentPage)
+ .eq('heading', section.heading)
+ .maybeSingle()
+ if (error) {
+ throw Error(error.message ?? 'Failed to fetch section from database')
+ }
+
+ if (data && 'id' in data) {
+ const { error } = await supabase
+ .from('last_changed')
+ .update({
+ checksum: section.checksum,
+ last_updated: updatedAt,
+ last_checked: timestamp,
+ })
+ .eq('id', data.id)
+ if (error) {
+ throw Error(error.message ?? 'Failed to update row')
+ }
+ stats.sectionsUpdated++
+ } else {
+ const { error } = await supabase.from('last_changed').insert({
+ parent_page: parentPage,
+ heading: section.heading,
+ checksum: section.checksum,
+ last_updated: updatedAt,
+ last_checked: timestamp,
+ })
+ if (error) {
+ throw Error(error.message ?? 'Failed to insert row')
+ }
+ stats.sectionsUpdated++
+ }
+ } catch (err) {
+ console.error(
+ `Failed to update timestamp with last commit date for section ${filePath}:${section.heading}: ${err}`
+ )
+ }
+}
+
+async function cleanupObsoleteRows(timestamp: Date, supabase: SupabaseClient, stats: Stats) {
+ try {
+ const { count, error } = await supabase
+ .from('last_changed')
+ .delete({ count: 'exact' })
+ .neq('last_checked', timestamp.toISOString())
+ stats.sectionsRemoved = count
+ if (error) {
+ throw Error(error.message ?? 'Failed to delete rows')
+ }
+ } catch (err) {
+ console.error(`Error cleanup obsolete rows: ${err}`)
+ }
+}
+
+main()
diff --git a/package-lock.json b/package-lock.json
index dbe1053f661..524b6b1e2d7 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -787,6 +787,7 @@
"jest-environment-jsdom": "^29.7.0",
"npm-run-all": "^4.1.5",
"openapi-types": "^12.1.3",
+ "simple-git": "^3.24.0",
"tsconfig": "*",
"tsx": "^4.6.2",
"typescript": "^5.4.3"
@@ -9226,6 +9227,21 @@
"dev": true,
"license": "Apache-2.0"
},
+ "node_modules/@kwsites/file-exists": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@kwsites/file-exists/-/file-exists-1.1.1.tgz",
+ "integrity": "sha512-m9/5YGR18lIwxSFDwfE3oA7bWuq9kdau6ugN4H2rJeyhFQZcG9AgSHkQtSD15a8WvTgfz9aikZMrKPHvbpqFiw==",
+ "dev": true,
+ "dependencies": {
+ "debug": "^4.1.1"
+ }
+ },
+ "node_modules/@kwsites/promise-deferred": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@kwsites/promise-deferred/-/promise-deferred-1.1.1.tgz",
+ "integrity": "sha512-GaHYm+c0O9MjZRu0ongGBRbinu8gVAMd2UZjji6jVmqKtZluZnptXGWhz1E8j8D2HJ3f/yMxKAUC0b+57wncIw==",
+ "dev": true
+ },
"node_modules/@lezer/common": {
"version": "1.1.0",
"license": "MIT",
@@ -46659,6 +46675,21 @@
"simple-concat": "^1.0.0"
}
},
+ "node_modules/simple-git": {
+ "version": "3.24.0",
+ "resolved": "https://registry.npmjs.org/simple-git/-/simple-git-3.24.0.tgz",
+ "integrity": "sha512-QqAKee9Twv+3k8IFOFfPB2hnk6as6Y6ACUpwCtQvRYBAes23Wv3SZlHVobAzqcE8gfsisCvPw3HGW3HYM+VYYw==",
+ "dev": true,
+ "dependencies": {
+ "@kwsites/file-exists": "^1.1.1",
+ "@kwsites/promise-deferred": "^1.1.1",
+ "debug": "^4.3.4"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/steveukx/git-js?sponsor=1"
+ }
+ },
"node_modules/simple-swizzle": {
"version": "0.2.2",
"license": "MIT",
diff --git a/supabase/migrations/20240604035404_last_changed.sql b/supabase/migrations/20240604035404_last_changed.sql
new file mode 100644
index 00000000000..6a2195bbd54
--- /dev/null
+++ b/supabase/migrations/20240604035404_last_changed.sql
@@ -0,0 +1,28 @@
+create table last_changed (
+ id bigint primary key generated always as identity,
+ checksum text not null,
+ parent_page text not null,
+ heading text not null,
+ last_updated timestamp with time zone default now() not null,
+ last_checked timestamp with time zone default now() not null,
+ unique (parent_page, heading)
+);
+
+comment on table last_changed is
+'Records when page sections from docs content were last edited.';
+comment on column last_changed.checksum is
+'Checksum of most recent section contents.';
+comment on column last_changed.parent_page is
+'Path of the page containing this section.';
+comment on column last_changed.last_updated is
+'When the content was last edited.';
+comment on column last_changed.last_checked is
+'When the content was last checked. Used to identify and delete obsolete sections.';
+
+alter table last_changed enable row level security;
+
+revoke all on last_changed from anon;
+revoke all on last_changed from authenticated;
+
+create index idx_last_changed_parent_page_btree
+on last_changed (parent_page);