This repository has been archived by the owner on Sep 8, 2024. It is now read-only.
generated from crashmax-dev/vite-userscript-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsupabase-plugin.ts
98 lines (83 loc) · 2.38 KB
/
supabase-plugin.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import fs from 'node:fs/promises'
import path from 'node:path'
import type { SupabaseClient } from '@supabase/supabase-js'
import type { Plugin } from 'vite'
interface PluginConfig {
name: string
version: string
bucketId: string
supabase: SupabaseClient
}
export const Supabase = (config: PluginConfig): Plugin => {
let isBuildWatch: boolean
let outDir: string
return {
name: 'vite-plugin-supabase',
apply: 'build',
enforce: 'post',
configResolved: (userConfig) => {
isBuildWatch = (userConfig.build.watch ?? false) as boolean
outDir = userConfig.build.outDir
},
buildEnd: async (error) => {
if (error || isBuildWatch) return
try {
await uploadFilesToSupabase(config, outDir)
} catch (err) {
console.log(err)
}
}
}
}
const fileOptions = {
contentType: 'text/javascript',
upsert: true,
cacheControl: '0'
}
async function uploadFilesToSupabase(
config: PluginConfig,
outDir: string
): Promise<void> {
const __dirname = path.dirname(new URL(import.meta.url).pathname)
const files = await fs.readdir(path.join(__dirname, outDir), {
encoding: 'utf-8',
recursive: false,
withFileTypes: true
})
for (const file of files) {
if (!file.isFile() || !file.name.startsWith(config.name)) {
continue
}
const versionPathDir = path.join(config.name, config.version)
const fileBody = await fs.readFile(
path.join(__dirname, outDir, file.name),
{
encoding: 'utf-8'
}
)
// registry/<name>/<version>/<name>.user.js
const { error } = await config.supabase.storage
.from(config.bucketId)
.upload(path.join(versionPathDir, file.name), fileBody, fileOptions)
if (error) {
console.log(error)
} else {
const publicUrl = config.supabase.storage
.from(config.bucketId)
.getPublicUrl(path.join(versionPathDir, file.name))
console.log(publicUrl.data.publicUrl)
}
// registry/<name>/<name>.user.js
const { error: error2 } = await config.supabase.storage
.from(config.bucketId)
.upload(path.join(config.name, file.name), fileBody, fileOptions)
if (error2) {
console.log(error2)
} else {
const publicUrl = config.supabase.storage
.from(config.bucketId)
.getPublicUrl(path.join(config.name, file.name))
console.log(publicUrl.data.publicUrl)
}
}
}