package jsvm
import (
"bytes"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"ganigeorgiev.com/pocketbase/pocketbase/plugins/jsvm/internal/types/generated"
"ganigeorgiev.com/pocketbase/pocketbase/tools/routine"
"ganigeorgiev.com/pocketbase/pocketbase/tools/template"
"github.com/dop251/goja"
"github.com/dop251/goja_nodejs/buffer"
"github.com/dop251/goja_nodejs/console"
"github.com/dop251/goja_nodejs/process"
"github.com/dop251/goja_nodejs/require"
"github.com/fatih/color"
"github.com/fsnotify/fsnotify"
)
const typesFileName = "types.d.ts"
var defaultScriptPath = "pb.js"
func init() {
cwd, err := os.Getwd()
if err != nil {
color.Yellow("Failed to retrieve the current working directory: %v", err)
} else {
defaultScriptPath = filepath.Join(cwd, defaultScriptPath)
}
}
type Config struct {
OnInit func(vm *goja.Runtime)
HooksWatch bool
HooksDir string
HooksFilesPattern string
HooksPoolSize int
MigrationsDir string
MigrationsFilesPattern string
TypesDir string
}
func MustRegister(app core.App, config Config) {
if err := Register(app, config); err != nil {
panic(err)
}
}
func Register(app core.App, config Config) error {
p := &plugin{app: app, config: config}
if p.config.HooksDir == "" {
p.config.HooksDir = filepath.Join(app.DataDir(), "../pb_hooks")
}
if p.config.MigrationsDir == "" {
p.config.MigrationsDir = filepath.Join(app.DataDir(), "../pb_migrations")
}
if p.config.HooksFilesPattern == "" {
p.config.HooksFilesPattern = `^.*(\.pb\.js|\.pb\.ts)$`
}
if p.config.MigrationsFilesPattern == "" {
p.config.MigrationsFilesPattern = `^.*(\.js|\.ts)$`
}
if p.config.TypesDir == "" {
p.config.TypesDir = app.DataDir()
}
p.app.OnBootstrap().BindFunc(func(e *core.BootstrapEvent) error {
err := e.Next()
if err != nil {
return err
}
err = p.refreshTypesFile()
if err != nil {
color.Yellow("Unable to refresh app types file: %v", err)
}
return nil
})
if err := p.registerMigrations(); err != nil {
return fmt.Errorf("registerMigrations: %w", err)
}
if err := p.registerHooks(); err != nil {
return fmt.Errorf("registerHooks: %w", err)
}
return nil
}
type plugin struct {
app core.App
config Config
}
func (p *plugin) registerMigrations() error {
files, err := filesContent(p.config.MigrationsDir, p.config.MigrationsFilesPattern)
if err != nil {
return err
}
absHooksDir, err := filepath.Abs(p.config.HooksDir)
if err != nil {
return err
}
registry := new(require.Registry)
templateRegistry := template.NewRegistry()
for file, content := range files {
vm := goja.New()
registry.Enable(vm)
console.Enable(vm)
process.Enable(vm)
buffer.Enable(vm)
BindCore(vm)
BindDbx(vm)
BindSecurity(vm)
BindOS(vm)
BindFilepath(vm)
BindHTTP(vm)
BindFilesystem(vm)
BindForms(vm)
BindMails(vm)
vm.Set("$template", templateRegistry)
vm.Set("__hooks", absHooksDir)
vm.Set("migrate", func(up, down func(txApp core.App) error) {
core.AppMigrations.Register(
func(txApp core.App) error {
return routine.SafeWrap(func() error {
if up == nil {
return nil
}
return up(txApp)
})()
},
func(txApp core.App) error {
return routine.SafeWrap(func() error {
if down == nil {
return nil
}
return down(txApp)
})()
},
file,
)
})
if p.config.OnInit != nil {
p.config.OnInit(vm)
}
_, err := vm.RunScript(defaultScriptPath, string(content))
if err != nil {
return fmt.Errorf("failed to run migration %s: %w", file, err)
}
}
return nil
}
func (p *plugin) registerHooks() error {
files, err := filesContent(p.config.HooksDir, p.config.HooksFilesPattern)
if err != nil {
return err
}
for name, content := range files {
if len(content) != 0 {
continue
}
path := filepath.Join(p.config.HooksDir, name)
directive := `/// <reference path="` + p.relativeTypesPath(p.config.HooksDir) + `" />`
if err := prependToEmptyFile(path, directive+"\n\n"); err != nil {
color.Yellow("Unable to prepend the types reference: %v", err)
}
}
if p.config.HooksWatch {
if err := p.watchHooks(); err != nil {
color.Yellow("Unable to init hooks watcher: %v", err)
}
}
if len(files) == 0 {
return nil
}
absHooksDir, err := filepath.Abs(p.config.HooksDir)
if err != nil {
return err
}
p.app.OnServe().BindFunc(func(e *core.ServeEvent) error {
e.Router.BindFunc(p.normalizeServeExceptions)
return e.Next()
})
requireRegistry := new(require.Registry)
templateRegistry := template.NewRegistry()
sharedBinds := func(vm *goja.Runtime) {
requireRegistry.Enable(vm)
console.Enable(vm)
process.Enable(vm)
buffer.Enable(vm)
BindCore(vm)
BindDbx(vm)
BindSecurity(vm)
BindOS(vm)
BindFilepath(vm)
BindHTTP(vm)
BindFilesystem(vm)
BindForms(vm)
BindMails(vm)
BindApis(vm)
vm.Set("$app", p.app)
vm.Set("$template", templateRegistry)
vm.Set("__hooks", absHooksDir)
if p.config.OnInit != nil {
p.config.OnInit(vm)
}
}
executors := newPool(p.config.HooksPoolSize, func() *goja.Runtime {
executor := goja.New()
sharedBinds(executor)
return executor
})
loader := goja.New()
sharedBinds(loader)
hooksBinds(p.app, loader, executors)
cronBinds(p.app, loader, executors)
routerBinds(p.app, loader, executors)
for file, content := range files {
func() {
defer func() {
if err := recover(); err != nil {
fmtErr := fmt.Errorf("failed to execute %s:\n - %v", file, err)
if p.config.HooksWatch {
color.Red("%v", fmtErr)
} else {
panic(fmtErr)
}
}
}()
_, err := loader.RunScript(defaultScriptPath, string(content))
if err != nil {
panic(err)
}
}()
}
return nil
}
func (p *plugin) normalizeServeExceptions(e *core.RequestEvent) error {
err := e.Next()
if err == nil || e.Written() {
return err
}
return normalizeException(err)
}
func (p *plugin) watchHooks() error {
watchDir := p.config.HooksDir
hooksDirInfo, err := os.Lstat(p.config.HooksDir)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return nil
}
return err
}
if hooksDirInfo.Mode()&os.ModeSymlink == os.ModeSymlink {
watchDir, err = filepath.EvalSymlinks(p.config.HooksDir)
if err != nil {
return fmt.Errorf("failed to resolve hooksDir symlink: %w", err)
}
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
var debounceTimer *time.Timer
stopDebounceTimer := func() {
if debounceTimer != nil {
debounceTimer.Stop()
debounceTimer = nil
}
}
p.app.OnTerminate().BindFunc(func(e *core.TerminateEvent) error {
watcher.Close()
stopDebounceTimer()
return e.Next()
})
routine.FireAndForget(func() {
defer stopDebounceTimer()
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
stopDebounceTimer()
debounceTimer = time.AfterFunc(50*time.Millisecond, func() {
if runtime.GOOS == "windows" {
color.Yellow("File %s changed, please restart the app manually", event.Name)
} else {
color.Yellow("File %s changed, restarting...", event.Name)
if err := p.app.Restart(); err != nil {
color.Red("Failed to restart the app:", err)
}
}
})
case err, ok := <-watcher.Errors:
if !ok {
return
}
color.Red("Watch error:", err)
}
}
})
dirsErr := filepath.WalkDir(watchDir, func(path string, entry fs.DirEntry, err error) error {
if err != nil || !entry.IsDir() {
return nil
}
if strings.HasPrefix(entry.Name(), ".") || entry.Name() == "node_modules" {
return filepath.SkipDir
}
return watcher.Add(path)
})
if dirsErr != nil {
watcher.Close()
}
return dirsErr
}
func (p *plugin) fullTypesPath() string {
return filepath.Join(p.config.TypesDir, typesFileName)
}
func (p *plugin) relativeTypesPath(basepath string) string {
fullPath := p.fullTypesPath()
rel, err := filepath.Rel(basepath, fullPath)
if err != nil {
rel = fullPath
}
return rel
}
func (p *plugin) refreshTypesFile() error {
fullPath := p.fullTypesPath()
dir := filepath.Dir(fullPath)
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return err
}
data, err := generated.Types.ReadFile(typesFileName)
if err != nil {
return err
}
existingFile, err := os.Open(fullPath)
if err == nil {
timestamp := make([]byte, 13)
io.ReadFull(existingFile, timestamp)
existingFile.Close()
if len(data) >= len(timestamp) && bytes.Equal(data[:13], timestamp) {
return nil
}
}
return os.WriteFile(fullPath, data, 0644)
}
func prependToEmptyFile(path, text string) error {
info, err := os.Stat(path)
if err == nil && info.Size() == 0 {
return os.WriteFile(path, []byte(text), 0644)
}
return err
}
func filesContent(dirPath string, pattern string) (map[string][]byte, error) {
files, err := os.ReadDir(dirPath)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return map[string][]byte{}, nil
}
return nil, err
}
var exp *regexp.Regexp
if pattern != "" {
var err error
if exp, err = regexp.Compile(pattern); err != nil {
return nil, err
}
}
result := map[string][]byte{}
for _, f := range files {
if f.IsDir() || (exp != nil && !exp.MatchString(f.Name())) {
continue
}
raw, err := os.ReadFile(filepath.Join(dirPath, f.Name()))
if err != nil {
return nil, err
}
result[f.Name()] = raw
}
return result, nil
}