From 114c01ac1212434187cb154866ffdf609d1fadeb Mon Sep 17 00:00:00 2001 From: Gani Georgiev Date: Mon, 7 Sep 2026 19:27:58 +0300 Subject: [PATCH 1/4] [#7836] fixed migration logs write deadlock and added app.ClearBootstrap/OnClearBootstrap helpers --- CHANGELOG.md | 8 + core/app.go | 13 +- core/base.go | 183 +- core/base_test.go | 185 +- core/log_printer_test.go | 11 +- core/system_alert_test.go | 4 +- plugins/jsvm/binds_test.go | 2 +- .../jsvm/internal/types/generated/types.d.ts | 12751 ++++++++-------- pocketbase.go | 2 +- tests/app.go | 10 +- tools/logger/batch_handler.go | 7 + ui/.env | 2 +- .../{index-VdywtJWb.js => index-BdKjfEsN.js} | 4 +- ....js => pageConfirmEmailChange-6fN8Ilq2.js} | 2 +- ...s => pageConfirmPasswordReset-CdUMVnrB.js} | 2 +- ...js => pageConfirmVerification-hLlj_RIY.js} | 2 +- ...-1JgM1ovU.js => pageInstaller-BYU_-RZq.js} | 2 +- ui/dist/index.html | 2 +- 18 files changed, 6703 insertions(+), 6489 deletions(-) rename ui/dist/assets/{index-VdywtJWb.js => index-BdKjfEsN.js} (99%) rename ui/dist/assets/{pageConfirmEmailChange-CL83yU_3.js => pageConfirmEmailChange-6fN8Ilq2.js} (97%) rename ui/dist/assets/{pageConfirmPasswordReset-D1ms_2ce.js => pageConfirmPasswordReset-CdUMVnrB.js} (97%) rename ui/dist/assets/{pageConfirmVerification-BGAA0TUZ.js => pageConfirmVerification-hLlj_RIY.js} (96%) rename ui/dist/assets/{pageInstaller-1JgM1ovU.js => pageInstaller-BYU_-RZq.js} (98%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ea9a2ff2e..9a19353ee1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,11 @@ +## v0.40.4 (WIP) + +- Fixed migration deadlock if a logs db write is triggered from within the migration ([#7836](https://github.com/pocketbase/pocketbase/issues/7836)). + +- `app.ResetBootstrapState()` was deprecated in favour of `app.ClearBootstrap()`. + Additionally a new `app.OnClearBootstrap()` hook was added to allow clearing custom `OnBootstrap` resources in case the app us reinitialized without triggering `OnTerminate`. + + ## v0.40.3 - Write the status header for JSON responses only if the fields picker succeed or has acceptable fallback. diff --git a/core/app.go b/core/app.go index 1bbec9c067..0cd4fccf92 100644 --- a/core/app.go +++ b/core/app.go @@ -54,11 +54,16 @@ type App interface { // Bootstrap initializes the application // (aka. create data dir, open db connections, load settings, etc.). // - // It will call ResetBootstrapState() if the application was already bootstrapped. + // It calls ClearBootstrap() if the application was already bootstrapped. Bootstrap() error - // ResetBootstrapState releases the initialized core app resources + // ClearBootstrap releases the initialized core app resources // (closing db connections, stopping cron ticker, etc.). + // + // This method is no-op if the application is not bootstrapped yet. + ClearBootstrap() error + + // Deprecated: use ClearBootstrap(). ResetBootstrapState() error // DataDir returns the app data directory path. @@ -713,6 +718,10 @@ type App interface { // resources (db, app settings, etc). OnBootstrap() *hook.Hook[*BootstrapEvent] + // OnClearBootstrap hook is triggered on unsetting the main application + // resources (db, app settings, etc) to their initial nil/empty value. + OnClearBootstrap() *hook.Hook[*BootstrapEvent] + // OnServe hook is triggered when the app web server is started // (after starting the TCP listener but before initializing the blocking serve task), // allowing you to adjust its options and attach new routes or middlewares. diff --git a/core/base.go b/core/base.go index 3d0f41c11f..5ab27c4700 100644 --- a/core/base.go +++ b/core/base.go @@ -12,6 +12,7 @@ import ( "regexp" "runtime" "strings" + "sync/atomic" "time" "github.com/fatih/color" @@ -89,11 +90,12 @@ type BaseApp struct { auxNonconcurrentDB dbx.Builder // app event hooks - onBootstrap *hook.Hook[*BootstrapEvent] - onServe *hook.Hook[*ServeEvent] - onTerminate *hook.Hook[*TerminateEvent] - onBackupCreate *hook.Hook[*BackupEvent] - onBackupRestore *hook.Hook[*BackupEvent] + onBootstrap *hook.Hook[*BootstrapEvent] + onClearBootstrap *hook.Hook[*BootstrapEvent] + onServe *hook.Hook[*ServeEvent] + onTerminate *hook.Hook[*TerminateEvent] + onBackupCreate *hook.Hook[*BackupEvent] + onBackupRestore *hook.Hook[*BackupEvent] // db model hooks onModelValidate *hook.Hook[*ModelEvent] @@ -249,6 +251,7 @@ func NewBaseApp(config BaseAppConfig) *BaseApp { func (app *BaseApp) initHooks() { // app event hooks app.onBootstrap = &hook.Hook[*BootstrapEvent]{} + app.onClearBootstrap = &hook.Hook[*BootstrapEvent]{} app.onServe = &hook.Hook[*ServeEvent]{} app.onTerminate = &hook.Hook[*TerminateEvent]{} app.onBackupCreate = &hook.Hook[*BackupEvent]{} @@ -405,14 +408,14 @@ func (app *BaseApp) IsBootstrapped() bool { // Bootstrap initializes the application // (aka. create data dir, open db connections, load settings, etc.). // -// It will call ResetBootstrapState() if the application was already bootstrapped. +// It calls ClearBootstrap() if the application was already bootstrapped. func (app *BaseApp) Bootstrap() error { event := &BootstrapEvent{} event.App = app err := app.OnBootstrap().Trigger(event, func(e *BootstrapEvent) error { - // clear resources of previous core state (if any) - if err := app.ResetBootstrapState(); err != nil { + // clear previous bootstrap state (if any) + if err := app.ClearBootstrap(); err != nil { return err } @@ -460,41 +463,55 @@ func (app *BaseApp) Bootstrap() error { return err } -type closer interface { - Close() error +// Deprecated: use [ClearBootstrap]. +func (app *BaseApp) ResetBootstrapState() error { + return app.ClearBootstrap() } -// ResetBootstrapState releases the initialized core app resources +// ClearBootstrap releases the initialized core app resources // (closing db connections, stopping cron ticker, etc.). -func (app *BaseApp) ResetBootstrapState() error { - app.Cron().Stop() +// +// This method is no-op if the application is not bootstrapped yet. +func (app *BaseApp) ClearBootstrap() error { + if !app.IsBootstrapped() { + return nil + } - var errs []error + event := &BootstrapEvent{} + event.App = app - dbs := []*dbx.Builder{ - &app.concurrentDB, - &app.nonconcurrentDB, - &app.auxConcurrentDB, - &app.auxNonconcurrentDB, - } + return app.OnClearBootstrap().Trigger(event, func(e *BootstrapEvent) error { + type closer interface { + Close() error + } - for _, db := range dbs { - if db == nil { - continue + var errs []error + + dbs := []*dbx.Builder{ + &app.concurrentDB, + &app.nonconcurrentDB, + &app.auxConcurrentDB, + &app.auxNonconcurrentDB, } - if v, ok := (*db).(closer); ok { - if err := v.Close(); err != nil { - errs = append(errs, err) + + for _, db := range dbs { + if db == nil { + continue } + if v, ok := (*db).(closer); ok { + if err := v.Close(); err != nil { + errs = append(errs, err) + } + } + *db = nil } - *db = nil - } - if len(errs) > 0 { - return errors.Join(errs...) - } + if len(errs) > 0 { + return errors.Join(errs...) + } - return nil + return nil + }) } // DB returns the default app data.db builder instance. @@ -817,7 +834,7 @@ func (app *BaseApp) Restart() error { event.IsRestart = true return app.OnTerminate().Trigger(event, func(e *TerminateEvent) error { - _ = e.App.ResetBootstrapState() + _ = e.App.ClearBootstrap() // attempt to restart the bootstrap process in case execve returns an error for some reason defer func() { @@ -860,6 +877,10 @@ func (app *BaseApp) OnBootstrap() *hook.Hook[*BootstrapEvent] { return app.onBootstrap } +func (app *BaseApp) OnClearBootstrap() *hook.Hook[*BootstrapEvent] { + return app.onClearBootstrap +} + func (app *BaseApp) OnServe() *hook.Hook[*ServeEvent] { return app.onServe } @@ -1413,7 +1434,15 @@ func (app *BaseApp) registerBaseHooks() { Id: "__pbCronStart__", Func: func(e *ServeEvent) error { app.Cron().Start() + return e.Next() + }, + Priority: 999, + }) + app.OnClearBootstrap().Bind(&hook.Handler[*BootstrapEvent]{ + Id: "__pbCronStop__", + Func: func(e *BootstrapEvent) error { + app.Cron().Stop() return e.Next() }, Priority: 999, @@ -1470,9 +1499,41 @@ func getLoggerMinLevel(app App) slog.Level { } func (app *BaseApp) initLogger() error { + var stopped atomic.Bool + duration := 3 * time.Second ticker := time.NewTicker(duration) - done := make(chan bool, 1) + + done := make(chan struct{}, 1) + + runLogsWrite := func(logs []*logger.Log) { + if !app.IsBootstrapped() || app.Settings().Logs.MaxDays == 0 { + return + } + + // write the accumulated logs + // + // note: based on several local tests there is no + // significant performance difference between small number + // of separate write queries vs 1 big INSERT + app.AuxRunInTransaction(func(txApp App) error { + model := &Log{} + for _, l := range logs { + model.MarkAsNew() + model.Id = GenerateDefaultRandomId() + model.Level = int(l.Level) + model.Message = l.Message + model.Data = l.Data + model.Created, _ = types.ParseDateTime(l.Time) + + if err := txApp.AuxSave(model); err != nil { + log.Println("Failed to write log", model, err) + } + } + + return nil + }) + } handler := logger.NewBatchHandler(logger.BatchOptions{ Level: getLoggerMinLevel(app), @@ -1487,35 +1548,25 @@ func (app *BaseApp) initLogger() error { } } - ticker.Reset(duration) + if !stopped.Load() { + ticker.Reset(duration) + } return app.Settings().Logs.MaxDays > 0 }, WriteFunc: func(ctx context.Context, logs []*logger.Log) error { - if !app.IsBootstrapped() || app.Settings().Logs.MaxDays == 0 { - return nil + // don't block and wait for the write transaction to complete + // when we can't be sure if the logs write wasn't triggered while + // inside another AUX db transaction (ticker or batch threshold reached) + // which can block indefinitely and cause deadlock + // (https://github.com/pocketbase/pocketbase/issues/7836) + shouldBlock, _ := ctx.Value(logger.BlockKey).(bool) + if shouldBlock { + runLogsWrite(logs) + } else { + routine.FireAndForget(func() { runLogsWrite(logs) }) } - // write the accumulated logs - // (note: based on several local tests there is no significant performance difference between small number of separate write queries vs 1 big INSERT) - app.AuxRunInTransaction(func(txApp App) error { - model := &Log{} - for _, l := range logs { - model.MarkAsNew() - model.Id = GenerateDefaultRandomId() - model.Level = int(l.Level) - model.Message = l.Message - model.Data = l.Data - model.Created, _ = types.ParseDateTime(l.Time) - - if err := txApp.AuxSave(model); err != nil { - log.Println("Failed to write log", model, err) - } - } - - return nil - }) - return nil }, }) @@ -1535,17 +1586,21 @@ func (app *BaseApp) initLogger() error { app.logger = slog.New(handler) - // write all remaining logs before ticker.Stop to avoid races with ResetBootstrap user calls - app.OnTerminate().Bind(&hook.Handler[*TerminateEvent]{ - Id: "__pbAppLoggerOnTerminate__", - Func: func(e *TerminateEvent) error { - handler.WriteAll(context.Background()) + // attempt to write all queued logs before clearing the application bootstrap state + app.OnClearBootstrap().Bind(&hook.Handler[*BootstrapEvent]{ + Id: "__pbAppLoggerFlushBeforeStop__", + Func: func(e *BootstrapEvent) error { + // extra precaution in case the hook was manually triggered while inside aux db transaction + _, isTx := e.App.AuxNonconcurrentDB().(*dbx.Tx) + ctx := context.WithValue(context.Background(), logger.BlockKey, !isTx) + handler.WriteAll(ctx) + stopped.Store(true) ticker.Stop() - // don't block in case OnTerminate is triggered more than once + // don't block in case the hook is triggered more than once select { - case done <- true: + case done <- struct{}{}: default: } diff --git a/core/base_test.go b/core/base_test.go index 0e383f8d5e..62947a51c8 100644 --- a/core/base_test.go +++ b/core/base_test.go @@ -65,7 +65,7 @@ func TestBaseAppBootstrap(t *testing.T) { app := core.NewBaseApp(core.BaseAppConfig{ DataDir: testDataDir, }) - defer app.ResetBootstrapState() + defer app.ClearBootstrap() if app.IsBootstrapped() { t.Fatal("Didn't expect the application to be bootstrapped.") @@ -115,7 +115,7 @@ func TestBaseAppBootstrap(t *testing.T) { runNilChecks(nilChecksBeforeReset) // reset - if err := app.ResetBootstrapState(); err != nil { + if err := app.ClearBootstrap(); err != nil { t.Fatal(err) } @@ -141,7 +141,7 @@ func TestNewBaseAppTx(t *testing.T) { app := core.NewBaseApp(core.BaseAppConfig{ DataDir: testDataDir, }) - defer app.ResetBootstrapState() + defer app.ClearBootstrap() if err := app.Bootstrap(); err != nil { t.Fatal(err) @@ -185,7 +185,7 @@ func TestBaseAppNewMailClient(t *testing.T) { DataDir: testDataDir, EncryptionEnv: "pb_test_env", }) - defer app.ResetBootstrapState() + defer app.ClearBootstrap() client1 := app.NewMailClient() m1, ok := client1.(*mailer.Sendmail) @@ -215,7 +215,7 @@ func TestBaseAppNewFilesystem(t *testing.T) { app := core.NewBaseApp(core.BaseAppConfig{ DataDir: testDataDir, }) - defer app.ResetBootstrapState() + defer app.ClearBootstrap() // local local, localErr := app.NewFilesystem() @@ -244,7 +244,7 @@ func TestBaseAppNewBackupsFilesystem(t *testing.T) { app := core.NewBaseApp(core.BaseAppConfig{ DataDir: testDataDir, }) - defer app.ResetBootstrapState() + defer app.ClearBootstrap() // local local, localErr := app.NewBackupsFilesystem() @@ -266,71 +266,172 @@ func TestBaseAppNewBackupsFilesystem(t *testing.T) { } } -func TestBaseAppLoggerWrites(t *testing.T) { - t.Parallel() +const logsThreshold = 200 - app, _ := tests.NewTestApp() - defer app.Cleanup() +func assertLogsCount(t *testing.T, app core.App, expected int) { + var total int - // reset - if err := app.DeleteOldLogs(time.Now()); err != nil { - t.Fatal(err) + err := app.LogQuery().Select("count(*)").Row(&total) + if err != nil { + t.Fatalf("Failed to fetch total logs: %v", err) } - const logsThreshold = 200 + if total != expected { + t.Fatalf("Expected %d log(s), got %d", expected, total) + } +} - totalLogs := func(app core.App, t *testing.T) int { - var total int +func TestBaseAppLoggerWrites(t *testing.T) { + t.Parallel() - err := app.LogQuery().Select("count(*)").Row(&total) - if err != nil { - t.Fatalf("Failed to fetch total logs: %v", err) - } + // note: outside of synctest because the bootstrap tickers could deadlock + app, _ := tests.NewTestApp() + defer app.Cleanup() - return total + // clear old logs + err := app.DeleteOldLogs(time.Now()) + if err != nil { + t.Fatal(err) } t.Run("disabled logs retention", func(t *testing.T) { - app.Settings().Logs.MaxDays = 0 + synctest.Test(t, func(t *testing.T) { + app.Settings().Logs.MaxDays = 0 - for i := 0; i < logsThreshold+1; i++ { - app.Logger().Error("test") - } + for i := 0; i < logsThreshold+1; i++ { + app.Logger().Error("test") + } - if total := totalLogs(app, t); total != 0 { - t.Fatalf("Expected no logs, got %d", total) - } + // short delay for the non-blocking write goroutine + synctest.Sleep(time.Nanosecond) + + assertLogsCount(t, app, 0) + }) }) t.Run("test batch logs writes", func(t *testing.T) { synctest.Test(t, func(t *testing.T) { - app.Settings().Logs.MaxDays = 1 + app.Settings().Logs.MaxDays = 2 for i := 0; i < logsThreshold-1; i++ { app.Logger().Error("test") } - if total := totalLogs(app, t); total != 0 { - t.Fatalf("Expected no logs, got %d", total) - } + // short delay for the non-blocking write goroutine + synctest.Sleep(time.Nanosecond) + + // below threshold + assertLogsCount(t, app, 0) - // should trigger batch write + // threshold reached -> should trigger batch write app.Logger().Error("test") - // should be added for the next batch write + // should be skipped from this batch and added for the next app.Logger().Error("test") - if total := totalLogs(app, t); total != logsThreshold { - t.Fatalf("Expected %d logs, got %d", logsThreshold, total) - } + // short delay for the non-blocking write goroutine + synctest.Sleep(time.Nanosecond) + + assertLogsCount(t, app, logsThreshold) + + // note: we can't test the flush timer here because the ticker + // was started out of the synctest buble to avoid deadlocks + // (see TestBaseAppLoggerWritesAwaited for a flaky but real timer test) + }) + }) +} - // wait for 3 secs to check the timer trigger - synctest.Sleep(3000 * time.Millisecond) +func TestBaseAppLoggerWritesAwaited(t *testing.T) { + t.Parallel() - if total := totalLogs(app, t); total != logsThreshold { - t.Fatalf("Expected %d logs, got %d", logsThreshold, total) + app, _ := tests.NewTestApp() + defer app.Cleanup() + + // clear old logs + err := app.DeleteOldLogs(time.Now()) + if err != nil { + t.Fatal(err) + } + + // enable logs persistence + app.Settings().Logs.MaxDays = 1 + err = app.Save(app.Settings()) + if err != nil { + t.Fatal(err) + } + + t.Run("flush on timer tick", func(t *testing.T) { + timeout := time.After(5 * time.Second) + done := make(chan struct{}) + + logsHook := app.OnModelAfterCreateSuccess("_logs") + hookId := logsHook.BindFunc(func(e *core.ModelEvent) error { + done <- struct{}{} + return e.Next() + }) + defer logsHook.Unbind(hookId) + + app.Logger().Error("test") + + // short wait to ensure that there is no non-blocking write + time.Sleep(500 * time.Millisecond) + + assertLogsCount(t, app, 0) + + // wait for the ticker to write the db record + select { + case <-timeout: + t.Fatal("ticker wait timeout") + case <-done: + } + + assertLogsCount(t, app, 1) + }) + + t.Run("before ClearBootstrap flush", func(t *testing.T) { + app.Logger().Error("test") + + app.Bootstrap() + + assertLogsCount(t, app, 2) + }) + + t.Run("batch flush inside aux transaction shouldn't hang", func(t *testing.T) { + timeout := time.After(1 * time.Second) + done := make(chan struct{}) + totalCreated := 0 + + logsHook := app.OnModelAfterCreateSuccess("_logs") + hookId := logsHook.BindFunc(func(e *core.ModelEvent) error { + totalCreated++ + if totalCreated == 200 { + done <- struct{}{} + } + return e.Next() + }) + defer logsHook.Unbind(hookId) + + app.AuxRunInTransaction(func(txApp core.App) error { + for range logsThreshold { + txApp.Logger().Error("test") } + + return nil }) + + // wait for the non-blocking write + select { + case <-timeout: + t.Fatal("non-blocking write timeout") + case <-done: + } + + assertLogsCount(t, app, 202) + + // force clear to ensure that there are no other logs + app.Bootstrap() + + assertLogsCount(t, app, 202) }) } @@ -373,7 +474,7 @@ func TestBaseAppRefreshSettingsLoggerMinLevelEnabled(t *testing.T) { DataDir: testDataDir, IsDev: s.isDev, }) - defer app.ResetBootstrapState() + defer app.ClearBootstrap() if err := app.Bootstrap(); err != nil { t.Fatal(err) diff --git a/core/log_printer_test.go b/core/log_printer_test.go index 4349749541..37f59baee7 100644 --- a/core/log_printer_test.go +++ b/core/log_printer_test.go @@ -3,17 +3,24 @@ package core import ( "context" "database/sql" + "io" "log/slog" "os" "testing" "time" + "github.com/fatih/color" "github.com/pocketbase/dbx" "github.com/pocketbase/pocketbase/tools/list" "github.com/pocketbase/pocketbase/tools/logger" ) func TestBaseAppLoggerLevelDevPrint(t *testing.T) { + // temp unset to avoid littering the stdout if the test fails when in dev mode + colorOutput := color.Output + color.Output = io.Discard + defer func() { color.Output = colorOutput }() + testLogLevel := 4 scenarios := []struct { @@ -48,7 +55,7 @@ func TestBaseAppLoggerLevelDevPrint(t *testing.T) { DataDir: testDataDir, IsDev: s.isDev, }) - defer app.ResetBootstrapState() + defer app.ClearBootstrap() if err := app.Bootstrap(); err != nil { t.Fatal(err) @@ -68,7 +75,7 @@ func TestBaseAppLoggerLevelDevPrint(t *testing.T) { var printedLevels []int var persistedLevels []int - ctx := context.Background() + ctx := context.WithValue(context.Background(), logger.BlockKey, true) // track printed logs originalPrintLog := printLog diff --git a/core/system_alert_test.go b/core/system_alert_test.go index 0230749928..122f6b0f26 100644 --- a/core/system_alert_test.go +++ b/core/system_alert_test.go @@ -19,7 +19,7 @@ func TestSendSystemAlert(t *testing.T) { testApp := NewBaseApp(BaseAppConfig{ DataDir: testDataDir, }) - defer testApp.ResetBootstrapState() + defer testApp.ClearBootstrap() if err := testApp.Bootstrap(); err != nil { t.Fatal(err) @@ -72,7 +72,7 @@ func TestSendSystemAlertToAllSuperusers(t *testing.T) { testApp := NewBaseApp(BaseAppConfig{ DataDir: testDataDir, }) - defer testApp.ResetBootstrapState() + defer testApp.ClearBootstrap() if err := testApp.Bootstrap(); err != nil { t.Fatal(err) diff --git a/plugins/jsvm/binds_test.go b/plugins/jsvm/binds_test.go index 0d8ca9b90e..a93a58b8c5 100644 --- a/plugins/jsvm/binds_test.go +++ b/plugins/jsvm/binds_test.go @@ -1613,7 +1613,7 @@ func TestHooksBindsCount(t *testing.T) { vm := goja.New() hooksBinds(app, vm, nil) - testBindsCount(vm, "this", 82, t) + testBindsCount(vm, "this", 83, t) } func TestHooksBinds(t *testing.T) { diff --git a/plugins/jsvm/internal/types/generated/types.d.ts b/plugins/jsvm/internal/types/generated/types.d.ts index e563f4256c..dfd5547404 100644 --- a/plugins/jsvm/internal/types/generated/types.d.ts +++ b/plugins/jsvm/internal/types/generated/types.d.ts @@ -1,4 +1,4 @@ -// 1788714636 +// 1788798413 // GENERATED CODE - DO NOT MODIFY BY HAND // ------------------------------------------------------------------- @@ -1268,6 +1268,7 @@ declare function migrate( /** @group PocketBase */declare function onBackupRestore(handler: (e: core.BackupEvent) => void): void /** @group PocketBase */declare function onBatchRequest(handler: (e: core.BatchRequestEvent) => void): void /** @group PocketBase */declare function onBootstrap(handler: (e: core.BootstrapEvent) => void): void +/** @group PocketBase */declare function onClearBootstrap(handler: (e: core.BootstrapEvent) => void): void /** @group PocketBase */declare function onCollectionAfterCreateError(handler: (e: core.CollectionErrorEvent) => void, ...tags: string[]): void /** @group PocketBase */declare function onCollectionAfterCreateSuccess(handler: (e: core.CollectionEvent) => void, ...tags: string[]): void /** @group PocketBase */declare function onCollectionAfterDeleteError(handler: (e: core.CollectionErrorEvent) => void, ...tags: string[]): void @@ -1964,8 +1965,8 @@ namespace os { * than ReadFrom. This is used to permit ReadFrom to call io.Copy * without leading to a recursive call to ReadFrom. */ - type _sgIssSZ = noReadFrom&File - interface fileWithoutReadFrom extends _sgIssSZ { + type _sOnbNdj = noReadFrom&File + interface fileWithoutReadFrom extends _sOnbNdj { } interface File { /** @@ -2009,8 +2010,8 @@ namespace os { * than WriteTo. This is used to permit WriteTo to call io.Copy * without leading to a recursive call to WriteTo. */ - type _sRmRjyu = noWriteTo&File - interface fileWithoutWriteTo extends _sRmRjyu { + type _smWZqhB = noWriteTo&File + interface fileWithoutWriteTo extends _smWZqhB { } interface File { /** @@ -2957,8 +2958,8 @@ namespace os { * * The methods of File are safe for concurrent use. */ - type _spYcXgA = file - interface File extends _spYcXgA { + type _sWrfMom = file + interface File extends _sWrfMom { } /** * A FileInfo describes a file and is returned by [Stat] and [Lstat]. @@ -3009,603 +3010,910 @@ namespace os { } /** - * Package dbx provides a set of DB-agnostic and easy-to-use query building methods for relational databases. + * Package filepath implements utility routines for manipulating filename paths + * in a way compatible with the target operating system-defined file paths. + * + * The filepath package uses either forward slashes or backslashes, + * depending on the operating system. To process paths such as URLs + * that always use forward slashes regardless of the operating + * system, see the [path] package. */ -namespace dbx { - /** - * Builder supports building SQL statements in a DB-agnostic way. - * Builder mainly provides two sets of query building methods: those building SELECT statements - * and those manipulating DB data or schema (e.g. INSERT statements, CREATE TABLE statements). - */ - interface Builder { - [key:string]: any; - /** - * NewQuery creates a new Query object with the given SQL statement. - * The SQL statement may contain parameter placeholders which can be bound with actual parameter - * values before the statement is executed. - */ - newQuery(_arg0: string): (Query) +namespace filepath { + interface match { /** - * Select returns a new SelectQuery object that can be used to build a SELECT statement. - * The parameters to this method should be the list column names to be selected. - * A column name may have an optional alias name. For example, Select("id", "my_name AS name"). + * Match reports whether name matches the shell file name pattern. + * The pattern syntax is: + * + * ``` + * pattern: + * { term } + * term: + * '*' matches any sequence of non-Separator characters + * '?' matches any single non-Separator character + * '[' [ '^' ] { character-range } ']' + * character class (must be non-empty) + * c matches character c (c != '*', '?', '\\', '[') + * '\\' c matches character c (except on Windows) + * + * character-range: + * c matches character c (c != '\\', '-', ']') + * '\\' c matches character c (except on Windows) + * lo '-' hi matches character c for lo <= c <= hi + * ``` + * + * Path segments in the pattern must be separated by [Separator]. + * + * Match requires pattern to match all of name, not just a substring. + * The only possible returned error is [ErrBadPattern], when pattern + * is malformed. + * + * On Windows, escaping is disabled. Instead, '\\' is treated as + * path separator. */ - select(..._arg0: string[]): (SelectQuery) + (pattern: string, name: string): boolean + } + interface glob { /** - * ModelQuery returns a new ModelQuery object that can be used to perform model insertion, update, and deletion. - * The parameter to this method should be a pointer to the model struct that needs to be inserted, updated, or deleted. + * Glob returns the names of all files matching pattern or nil + * if there is no matching file. The syntax of patterns is the same + * as in [Match]. The pattern may describe hierarchical names such as + * /usr/*\/bin/ed (assuming the [Separator] is '/'). + * + * Glob ignores file system errors such as I/O errors reading directories. + * The only possible returned error is [ErrBadPattern], when pattern + * is malformed. */ - model(_arg0: { - }): (ModelQuery) + (pattern: string): Array + } + interface clean { /** - * GeneratePlaceholder generates an anonymous parameter placeholder with the given parameter ID. + * Clean returns the shortest path name equivalent to path + * by purely lexical processing. It applies the following rules + * iteratively until no further processing can be done: + * + * 1. Replace multiple [Separator] elements with a single one. + * 2. Eliminate each . path name element (the current directory). + * 3. Eliminate each inner .. path name element (the parent directory) + * ``` + * along with the non-.. element that precedes it. + * ``` + * 4. Eliminate .. elements that begin a rooted path: + * ``` + * that is, replace "/.." by "/" at the beginning of a path, + * assuming Separator is '/'. + * ``` + * + * The returned path ends in a slash only if it represents a root directory, + * such as "/" on Unix or `C:\` on Windows. + * + * Finally, any occurrences of slash are replaced by Separator. + * + * If the result of this process is an empty string, Clean + * returns the string ".". + * + * On Windows, Clean does not modify the volume name other than to replace + * occurrences of "/" with `\`. + * For example, Clean("//host/share/../x") returns `\\host\share\x`. + * + * See also Rob Pike, “Lexical File Names in Plan 9 or + * Getting Dot-Dot Right,” + * https://9p.io/sys/doc/lexnames.html */ - generatePlaceholder(_arg0: number): string + (path: string): string + } + interface isLocal { /** - * Quote quotes a string so that it can be embedded in a SQL statement as a string value. + * IsLocal reports whether path, using lexical analysis only, has all of these properties: + * + * ``` + * - is within the subtree rooted at the directory in which path is evaluated + * - is not an absolute path + * - is not empty + * - on Windows, is not a reserved name such as "NUL" + * ``` + * + * If IsLocal(path) returns true, then + * Join(base, path) will always produce a path contained within base and + * Clean(path) will always produce an unrooted path with no ".." path elements. + * + * IsLocal is a purely lexical operation. + * In particular, it does not account for the effect of any symbolic links + * that may exist in the filesystem. */ - quote(_arg0: string): string + (path: string): boolean + } + interface localize { /** - * QuoteSimpleTableName quotes a simple table name. - * A simple table name does not contain any schema prefix. + * Localize converts a slash-separated path into an operating system path. + * The input path must be a valid path as reported by [io/fs.ValidPath]. + * + * Localize returns an error if the path cannot be represented by the operating system. + * For example, the path a\b is rejected on Windows, on which \ is a separator + * character and cannot be part of a filename. + * + * The path returned by Localize will always be local, as reported by IsLocal. */ - quoteSimpleTableName(_arg0: string): string + (path: string): string + } + interface toSlash { /** - * QuoteSimpleColumnName quotes a simple column name. - * A simple column name does not contain any table prefix. + * ToSlash returns the result of replacing each separator character + * in path with a slash ('/') character. Multiple separators are + * replaced by multiple slashes. */ - quoteSimpleColumnName(_arg0: string): string + (path: string): string + } + interface fromSlash { /** - * QueryBuilder returns the query builder supporting the current DB. + * FromSlash returns the result of replacing each slash ('/') character + * in path with a separator character. Multiple slashes are replaced + * by multiple separators. + * + * See also the Localize function, which converts a slash-separated path + * as used by the io/fs package to an operating system path. */ - queryBuilder(): QueryBuilder + (path: string): string + } + interface splitList { /** - * Insert creates a Query that represents an INSERT SQL statement. - * The keys of cols are the column names, while the values of cols are the corresponding column - * values to be inserted. + * SplitList splits a list of paths joined by the OS-specific [ListSeparator], + * usually found in PATH or GOPATH environment variables. + * Unlike strings.Split, SplitList returns an empty slice when passed an empty + * string. */ - insert(table: string, cols: Params): (Query) + (path: string): Array + } + interface split { /** - * Upsert creates a Query that represents an UPSERT SQL statement. - * Upsert inserts a row into the table if the primary key or unique index is not found. - * Otherwise it will update the row with the new values. - * The keys of cols are the column names, while the values of cols are the corresponding column - * values to be inserted. + * Split splits path immediately following the final [Separator], + * separating it into a directory and file name component. + * If there is no Separator in path, Split returns an empty dir + * and file set to path. + * The returned values have the property that path = dir+file. */ - upsert(table: string, cols: Params, ...constraints: string[]): (Query) + (path: string): [string, string] + } + interface join { /** - * Update creates a Query that represents an UPDATE SQL statement. - * The keys of cols are the column names, while the values of cols are the corresponding new column - * values. If the "where" expression is nil, the UPDATE SQL statement will have no WHERE clause - * (be careful in this case as the SQL statement will update ALL rows in the table). + * Join joins any number of path elements into a single path, + * separating them with an OS specific [Separator]. Empty elements + * are ignored. The result is Cleaned. However, if the argument + * list is empty or all its elements are empty, Join returns + * an empty string. + * On Windows, the result will only be a UNC path if the first + * non-empty element is a UNC path. */ - update(table: string, cols: Params, where: Expression): (Query) + (...elem: string[]): string + } + interface ext { /** - * Delete creates a Query that represents a DELETE SQL statement. - * If the "where" expression is nil, the DELETE SQL statement will have no WHERE clause - * (be careful in this case as the SQL statement will delete ALL rows in the table). + * Ext returns the file name extension used by path. + * The extension is the suffix beginning at the final dot + * in the final element of path; it is empty if there is + * no dot. */ - delete(table: string, where: Expression): (Query) + (path: string): string + } + interface evalSymlinks { /** - * CreateTable creates a Query that represents a CREATE TABLE SQL statement. - * The keys of cols are the column names, while the values of cols are the corresponding column types. - * The optional "options" parameters will be appended to the generated SQL statement. + * EvalSymlinks returns the path name after the evaluation of any symbolic + * links. + * If path is relative the result will be relative to the current directory, + * unless one of the components is an absolute symbolic link. + * EvalSymlinks calls [Clean] on the result. */ - createTable(table: string, cols: _TygojaDict, ...options: string[]): (Query) + (path: string): string + } + interface isAbs { /** - * RenameTable creates a Query that can be used to rename a table. + * IsAbs reports whether the path is absolute. */ - renameTable(oldName: string, newName: string): (Query) + (path: string): boolean + } + interface abs { /** - * DropTable creates a Query that can be used to drop a table. + * Abs returns an absolute representation of path. + * If the path is not absolute it will be joined with the current + * working directory to turn it into an absolute path. The absolute + * path name for a given file is not guaranteed to be unique. + * Abs calls [Clean] on the result. */ - dropTable(table: string): (Query) + (path: string): string + } + interface rel { /** - * TruncateTable creates a Query that can be used to truncate a table. + * Rel returns a relative path that is lexically equivalent to targPath when + * joined to basePath with an intervening separator. That is, + * [Join](basePath, Rel(basePath, targPath)) is equivalent to targPath itself. + * + * The returned path will always be relative to basePath, even if basePath and + * targPath share no elements. Rel calls [Clean] on the result. + * + * An error is returned if targPath can't be made relative to basePath + * or if knowing the current working directory would be necessary to compute it. */ - truncateTable(table: string): (Query) - /** - * AddColumn creates a Query that can be used to add a column to a table. - */ - addColumn(table: string, col: string, typ: string): (Query) - /** - * DropColumn creates a Query that can be used to drop a column from a table. - */ - dropColumn(table: string, col: string): (Query) - /** - * RenameColumn creates a Query that can be used to rename a column in a table. - */ - renameColumn(table: string, oldName: string, newName: string): (Query) - /** - * AlterColumn creates a Query that can be used to change the definition of a table column. - */ - alterColumn(table: string, col: string, typ: string): (Query) - /** - * AddPrimaryKey creates a Query that can be used to specify primary key(s) for a table. - * The "name" parameter specifies the name of the primary key constraint. - */ - addPrimaryKey(table: string, name: string, ...cols: string[]): (Query) + (basePath: string, targPath: string): string + } + /** + * WalkFunc is the type of the function called by [Walk] to visit each + * file or directory. + * + * The path argument contains the argument to Walk as a prefix. + * That is, if Walk is called with root argument "dir" and finds a file + * named "a" in that directory, the walk function will be called with + * argument "dir/a". + * + * The directory and file are joined with Join, which may clean the + * directory name: if Walk is called with the root argument "x/../dir" + * and finds a file named "a" in that directory, the walk function will + * be called with argument "dir/a", not "x/../dir/a". + * + * The info argument is the fs.FileInfo for the named path. + * + * The error result returned by the function controls how Walk continues. + * If the function returns the special value [SkipDir], Walk skips the + * current directory (path if info.IsDir() is true, otherwise path's + * parent directory). If the function returns the special value [SkipAll], + * Walk skips all remaining files and directories. Otherwise, if the function + * returns a non-nil error, Walk stops entirely and returns that error. + * + * The err argument reports an error related to path, signaling that Walk + * will not walk into that directory. The function can decide how to + * handle that error; as described earlier, returning the error will + * cause Walk to stop walking the entire tree. + * + * Walk calls the function with a non-nil err argument in two cases. + * + * First, if an [os.Lstat] on the root directory or any directory or file + * in the tree fails, Walk calls the function with path set to that + * directory or file's path, info set to nil, and err set to the error + * from os.Lstat. + * + * Second, if a directory's Readdirnames method fails, Walk calls the + * function with path set to the directory's path, info, set to an + * [fs.FileInfo] describing the directory, and err set to the error from + * Readdirnames. + */ + interface WalkFunc {(path: string, info: fs.FileInfo, err: Error): void } + interface walkDir { /** - * DropPrimaryKey creates a Query that can be used to remove the named primary key constraint from a table. + * WalkDir walks the file tree rooted at root, calling fn for each file or + * directory in the tree, including root. + * + * All errors that arise visiting files and directories are filtered by fn: + * see the [fs.WalkDirFunc] documentation for details. + * + * The files are walked in lexical order, which makes the output deterministic + * but requires WalkDir to read an entire directory into memory before proceeding + * to walk that directory. + * + * WalkDir does not follow symbolic links. + * + * WalkDir calls fn with paths that use the separator character appropriate + * for the operating system. This is unlike [io/fs.WalkDir], which always + * uses slash separated paths. */ - dropPrimaryKey(table: string, name: string): (Query) + (root: string, fn: fs.WalkDirFunc): void + } + interface walk { /** - * AddForeignKey creates a Query that can be used to add a foreign key constraint to a table. - * The length of cols and refCols must be the same as they refer to the primary and referential columns. - * The optional "options" parameters will be appended to the SQL statement. They can be used to - * specify options such as "ON DELETE CASCADE". + * Walk walks the file tree rooted at root, calling fn for each file or + * directory in the tree, including root. + * + * All errors that arise visiting files and directories are filtered by fn: + * see the [WalkFunc] documentation for details. + * + * The files are walked in lexical order, which makes the output deterministic + * but requires Walk to read an entire directory into memory before proceeding + * to walk that directory. + * + * Walk does not follow symbolic links. + * + * Walk is less efficient than [WalkDir], introduced in Go 1.16, + * which avoids calling os.Lstat on every visited file or directory. */ - addForeignKey(table: string, name: string, cols: Array, refCols: Array, refTable: string, ...options: string[]): (Query) + (root: string, fn: WalkFunc): void + } + interface base { /** - * DropForeignKey creates a Query that can be used to remove the named foreign key constraint from a table. + * Base returns the last element of path. + * Trailing path separators are removed before extracting the last element. + * If the path is empty, Base returns ".". + * If the path consists entirely of separators, Base returns a single separator. */ - dropForeignKey(table: string, name: string): (Query) + (path: string): string + } + interface dir { /** - * CreateIndex creates a Query that can be used to create an index for a table. + * Dir returns all but the last element of path, typically the path's directory. + * After dropping the final element, Dir calls [Clean] on the path and trailing + * slashes are removed. + * If the path is empty, Dir returns ".". + * If the path consists entirely of separators, Dir returns a single separator. + * The returned path does not end in a separator unless it is the root directory. + * + * On Windows, given a volume-only name such as "C:", Dir returns "C:.", + * the current directory on drive C. To obtain the drive's root "C:\", + * use [VolumeName] combined with a separator. */ - createIndex(table: string, name: string, ...cols: string[]): (Query) + (path: string): string + } + interface volumeName { /** - * CreateUniqueIndex creates a Query that can be used to create a unique index for a table. + * VolumeName returns leading volume name. + * Given "C:\foo\bar" it returns "C:" on Windows. + * Given "\\host\share\foo" it returns "\\host\share". + * On other platforms it returns "". */ - createUniqueIndex(table: string, name: string, ...cols: string[]): (Query) + (path: string): string + } + interface hasPrefix { /** - * DropIndex creates a Query that can be used to remove the named index from a table. + * HasPrefix exists for historical compatibility and should not be used. + * + * Deprecated: HasPrefix does not respect path boundaries and + * does not ignore case when required. */ - dropIndex(table: string, name: string): (Query) + (p: string, prefix: string): boolean } +} + +/** + * Package validation provides configurable and extensible rules for validating data of various types. + */ +namespace ozzo_validation { /** - * BaseBuilder provides a basic implementation of the Builder interface. + * Error interface represents an validation error */ - interface BaseBuilder { + interface Error { + [key:string]: any; + error(): string + code(): string + message(): string + setMessage(_arg0: string): Error + params(): _TygojaDict + setParams(_arg0: _TygojaDict): Error } - interface newBaseBuilder { +} + +namespace security { + interface s256Challenge { /** - * NewBaseBuilder creates a new BaseBuilder instance. + * S256Challenge creates base64 encoded sha256 challenge string derived from code. + * The padding of the result base64 string is stripped per [RFC 7636]. + * + * [RFC 7636]: https://datatracker.ietf.org/doc/html/rfc7636#section-4.2 */ - (db: DB, executor: Executor): (BaseBuilder) + (code: string): string } - interface BaseBuilder { + interface md5 { /** - * DB returns the DB instance that this builder is associated with. + * MD5 creates md5 hash from the provided plain text. */ - db(): (DB) + (text: string): string } - interface BaseBuilder { + interface sha256 { /** - * Executor returns the executor object (a DB instance or a transaction) for executing SQL statements. + * SHA256 creates sha256 hash as defined in FIPS 180-4 from the provided text. */ - executor(): Executor + (text: string): string } - interface BaseBuilder { + interface sha512 { /** - * NewQuery creates a new Query object with the given SQL statement. - * The SQL statement may contain parameter placeholders which can be bound with actual parameter - * values before the statement is executed. + * SHA512 creates sha512 hash as defined in FIPS 180-4 from the provided text. */ - newQuery(sql: string): (Query) + (text: string): string } - interface BaseBuilder { + interface hs256 { /** - * GeneratePlaceholder generates an anonymous parameter placeholder with the given parameter ID. + * HS256 creates a HMAC hash with sha256 digest algorithm. */ - generatePlaceholder(_arg0: number): string + (text: string, secret: string): string } - interface BaseBuilder { + interface hs512 { /** - * Quote quotes a string so that it can be embedded in a SQL statement as a string value. + * HS512 creates a HMAC hash with sha512 digest algorithm. */ - quote(s: string): string + (text: string, secret: string): string } - interface BaseBuilder { + interface equal { /** - * QuoteSimpleTableName quotes a simple table name. - * A simple table name does not contain any schema prefix. + * Equal compares two hash strings for equality without leaking timing information. */ - quoteSimpleTableName(s: string): string + (hash1: string, hash2: string): boolean } - interface BaseBuilder { + // @ts-ignore + import crand = rand + interface encrypt { /** - * QuoteSimpleColumnName quotes a simple column name. - * A simple column name does not contain any table prefix. + * Encrypt encrypts "data" with the specified "key" (must be valid 32 char AES key). + * + * This method uses AES-256-GCM block cypher mode. */ - quoteSimpleColumnName(s: string): string + (data: string|Array, key: string): string } - interface BaseBuilder { + interface decrypt { /** - * Insert creates a Query that represents an INSERT SQL statement. - * The keys of cols are the column names, while the values of cols are the corresponding column - * values to be inserted. + * Decrypt decrypts encrypted text with key (must be valid 32 chars AES key). + * + * This method uses AES-256-GCM block cypher mode. */ - insert(table: string, cols: Params): (Query) + (cipherText: string, key: string): string|Array } - interface BaseBuilder { + interface parseUnverifiedJWT { /** - * Upsert creates a Query that represents an UPSERT SQL statement. - * Upsert inserts a row into the table if the primary key or unique index is not found. - * Otherwise it will update the row with the new values. - * The keys of cols are the column names, while the values of cols are the corresponding column - * values to be inserted. + * ParseUnverifiedJWT parses JWT and returns its claims + * but DOES NOT verify the signature. + * + * It verifies only the exp, iat and nbf claims. */ - upsert(table: string, cols: Params, ...constraints: string[]): (Query) + (token: string): jwt.MapClaims } - interface BaseBuilder { + interface parseJWT { /** - * Update creates a Query that represents an UPDATE SQL statement. - * The keys of cols are the column names, while the values of cols are the corresponding new column - * values. If the "where" expression is nil, the UPDATE SQL statement will have no WHERE clause - * (be careful in this case as the SQL statement will update ALL rows in the table). + * ParseJWT verifies and parses JWT and returns its claims. */ - update(table: string, cols: Params, where: Expression): (Query) - } - interface BaseBuilder { - /** - * Delete creates a Query that represents a DELETE SQL statement. - * If the "where" expression is nil, the DELETE SQL statement will have no WHERE clause - * (be careful in this case as the SQL statement will delete ALL rows in the table). - */ - delete(table: string, where: Expression): (Query) + (token: string, verificationKey: string): jwt.MapClaims } - interface BaseBuilder { + interface newJWT { /** - * CreateTable creates a Query that represents a CREATE TABLE SQL statement. - * The keys of cols are the column names, while the values of cols are the corresponding column types. - * The optional "options" parameters will be appended to the generated SQL statement. + * NewJWT generates and returns new HS256 signed JWT. */ - createTable(table: string, cols: _TygojaDict, ...options: string[]): (Query) + (payload: jwt.MapClaims, signingKey: string, duration: time.Duration): string } - interface BaseBuilder { + // @ts-ignore + import cryptoRand = rand + // @ts-ignore + import mathRand = rand + interface randomString { /** - * RenameTable creates a Query that can be used to rename a table. + * RandomString generates a cryptographically random string with the specified length. + * + * The generated string matches [A-Za-z0-9]+ and it's transparent to URL-encoding. */ - renameTable(oldName: string, newName: string): (Query) + (length: number): string } - interface BaseBuilder { + interface randomStringWithAlphabet { /** - * DropTable creates a Query that can be used to drop a table. + * RandomStringWithAlphabet generates a cryptographically random string + * with the specified length and characters set. + * + * It panics if for some reason rand.Int returns a non-nil error. */ - dropTable(table: string): (Query) + (length: number, alphabet: string): string } - interface BaseBuilder { + interface pseudorandomString { /** - * TruncateTable creates a Query that can be used to truncate a table. + * PseudorandomString generates a pseudorandom string with the specified length. + * + * The generated string matches [A-Za-z0-9]+ and it's transparent to URL-encoding. + * + * For a cryptographically random string (but a little bit slower) use RandomString instead. */ - truncateTable(table: string): (Query) + (length: number): string } - interface BaseBuilder { + interface pseudorandomStringWithAlphabet { /** - * AddColumn creates a Query that can be used to add a column to a table. + * PseudorandomStringWithAlphabet generates a pseudorandom string + * with the specified length and characters set. + * + * For a cryptographically random (but a little bit slower) use RandomStringWithAlphabet instead. */ - addColumn(table: string, col: string, typ: string): (Query) + (length: number, alphabet: string): string } - interface BaseBuilder { + interface randomStringByRegex { /** - * DropColumn creates a Query that can be used to drop a column from a table. + * RandomStringByRegex generates a random string matching the regex pattern. + * If optFlags is not set, fallbacks to [syntax.Perl]. + * + * NB! While the source of the randomness comes from [crypto/rand] this method + * is not recommended to be used on its own in critical secure contexts because + * the generated length could vary too much on the used pattern and may not be + * as secure as simply calling [security.RandomString]. + * If you still insist on using it for such purposes, consider at least + * a large enough minimum length for the generated string, e.g. `[a-z0-9]{30}`. + * + * This function is inspired by github.com/pipe01/revregexp, github.com/lucasjones/reggen and other similar packages. */ - dropColumn(table: string, col: string): (Query) + (pattern: string, ...optFlags: syntax.Flags[]): string } - interface BaseBuilder { - /** - * RenameColumn creates a Query that can be used to rename a column in a table. - */ - renameColumn(table: string, oldName: string, newName: string): (Query) +} + +namespace filesystem { + /** + * FileReader defines an interface for a file resource reader. + */ + interface FileReader { + [key:string]: any; + open(): io.ReadSeekCloser } - interface BaseBuilder { - /** - * AlterColumn creates a Query that can be used to change the definition of a table column. - */ - alterColumn(table: string, col: string, typ: string): (Query) + /** + * File defines a single file [io.ReadSeekCloser] resource. + * + * The file could be from a local path, multipart/form-data header, etc. + */ + interface File { + reader: FileReader + name: string + originalName: string + size: number } - interface BaseBuilder { + interface File { /** - * AddPrimaryKey creates a Query that can be used to specify primary key(s) for a table. - * The "name" parameter specifies the name of the primary key constraint. + * AsMap implements [core.mapExtractor] and returns a value suitable + * to be used in an API rule expression. */ - addPrimaryKey(table: string, name: string, ...cols: string[]): (Query) + asMap(): _TygojaDict } - interface BaseBuilder { + interface newFileFromPath { /** - * DropPrimaryKey creates a Query that can be used to remove the named primary key constraint from a table. + * NewFileFromPath creates a new File instance from the provided local file path. */ - dropPrimaryKey(table: string, name: string): (Query) + (path: string): (File) } - interface BaseBuilder { + interface newFileFromBytes { /** - * AddForeignKey creates a Query that can be used to add a foreign key constraint to a table. - * The length of cols and refCols must be the same as they refer to the primary and referential columns. - * The optional "options" parameters will be appended to the SQL statement. They can be used to - * specify options such as "ON DELETE CASCADE". + * NewFileFromBytes creates a new File instance from the provided byte slice. */ - addForeignKey(table: string, name: string, cols: Array, refCols: Array, refTable: string, ...options: string[]): (Query) + (b: string|Array, name: string): (File) } - interface BaseBuilder { + interface newFileFromMultipart { /** - * DropForeignKey creates a Query that can be used to remove the named foreign key constraint from a table. + * NewFileFromMultipart creates a new File from the provided multipart header. */ - dropForeignKey(table: string, name: string): (Query) + (mh: multipart.FileHeader): (File) } - interface BaseBuilder { + interface newFileFromURL { /** - * CreateIndex creates a Query that can be used to create an index for a table. + * NewFileFromURL creates a new File from the provided url by + * downloading the resource and load it as BytesReader. + * + * Example + * + * ``` + * ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + * defer cancel() + * + * file, err := filesystem.NewFileFromURL(ctx, "https://example.com/image.png") + * ``` */ - createIndex(table: string, name: string, ...cols: string[]): (Query) + (ctx: context.Context, url: string): (File) } - interface BaseBuilder { - /** - * CreateUniqueIndex creates a Query that can be used to create a unique index for a table. - */ - createUniqueIndex(table: string, name: string, ...cols: string[]): (Query) + /** + * MultipartReader defines a FileReader from [multipart.FileHeader]. + */ + interface MultipartReader { + header?: multipart.FileHeader } - interface BaseBuilder { + interface MultipartReader { /** - * DropIndex creates a Query that can be used to remove the named index from a table. + * Open implements the [filesystem.FileReader] interface. */ - dropIndex(table: string, name: string): (Query) + open(): io.ReadSeekCloser } /** - * MssqlBuilder is the builder for SQL Server databases. + * PathReader defines a FileReader from a local file path. */ - type _swcntDE = BaseBuilder - interface MssqlBuilder extends _swcntDE { + interface PathReader { + path: string + } + interface PathReader { + /** + * Open implements the [filesystem.FileReader] interface. + */ + open(): io.ReadSeekCloser } /** - * MssqlQueryBuilder is the query builder for SQL Server databases. + * BytesReader defines a FileReader from bytes content. */ - type _snJOAqT = BaseQueryBuilder - interface MssqlQueryBuilder extends _snJOAqT { + interface BytesReader { + bytes: string|Array } - interface newMssqlBuilder { + interface BytesReader { /** - * NewMssqlBuilder creates a new MssqlBuilder instance. + * Open implements the [filesystem.FileReader] interface. */ - (db: DB, executor: Executor): Builder + open(): io.ReadSeekCloser } - interface MssqlBuilder { + type _sCEnkWI = bytes.Reader + interface bytesReadSeekCloser extends _sCEnkWI { + } + interface bytesReadSeekCloser { /** - * QueryBuilder returns the query builder supporting the current DB. + * Close implements the [io.ReadSeekCloser] interface. */ - queryBuilder(): QueryBuilder + close(): void } - interface MssqlBuilder { + /** + * openFuncAsReader defines a FileReader from a bare Open function. + */ + interface openFuncAsReader {(): io.ReadSeekCloser } + interface openFuncAsReader { /** - * Select returns a new SelectQuery object that can be used to build a SELECT statement. - * The parameters to this method should be the list column names to be selected. - * A column name may have an optional alias name. For example, Select("id", "my_name AS name"). + * Open implements the [filesystem.FileReader] interface. */ - select(...cols: string[]): (SelectQuery) + open(): io.ReadSeekCloser } - interface MssqlBuilder { + type _stpekXo = hook.Event + interface DeleteEvent extends _stpekXo { + filesystem?: System + fileKey: string + } + type _sFDeFFj = hook.Event + interface NewWriterEvent extends _sFDeFFj { + filesystem?: System + fileKey: string + options?: blob.WriterOptions + writer?: blob.Writer // filled only after e.Next() + } + interface System { + } + interface newS3 { /** - * Model returns a new ModelQuery object that can be used to perform model-based DB operations. - * The model passed to this method should be a pointer to a model struct. + * NewS3 initializes a new S3 filesystem instance. + * + * NB! Make sure to call `Close()` after you are done working with it. */ - model(model: { - }): (ModelQuery) + (bucketName: string, region: string, endpoint: string, accessKey: string, secretKey: string, s3ForcePathStyle: boolean): (System) } - interface MssqlBuilder { + interface newLocal { /** - * QuoteSimpleTableName quotes a simple table name. - * A simple table name does not contain any schema prefix. + * NewLocal initializes a new local filesystem instance. + * + * NB! Make sure to call `Close()` after you are done working with it. */ - quoteSimpleTableName(s: string): string + (dirPath: string): (System) } - interface MssqlBuilder { + interface System { /** - * QuoteSimpleColumnName quotes a simple column name. - * A simple column name does not contain any table prefix. + * SetContext assigns the specified context to the current filesystem. */ - quoteSimpleColumnName(s: string): string + setContext(ctx: context.Context): void } - interface MssqlBuilder { + interface System { /** - * RenameTable creates a Query that can be used to rename a table. + * Close releases any resources used for the related filesystem. */ - renameTable(oldName: string, newName: string): (Query) + close(): void } - interface MssqlBuilder { + interface System { /** - * RenameColumn creates a Query that can be used to rename a column in a table. + * OnNewWriter is a low level hook that is triggered on every new writer initialization + * (aka. when attempting to create a new file with [system.NewWriter] or [system.Upload]). + * + * Note that currently it doesn't trigger on [System.Copy] but this may change in future releases. */ - renameColumn(table: string, oldName: string, newName: string): (Query) + onNewWriter(): (hook.Hook) } - interface MssqlBuilder { + interface System { /** - * AlterColumn creates a Query that can be used to change the definition of a table column. - */ - alterColumn(table: string, col: string, typ: string): (Query) - } - interface MssqlQueryBuilder { - /** - * BuildOrderByAndLimit generates the ORDER BY and LIMIT clauses. - */ - buildOrderByAndLimit(sql: string, cols: Array, limit: number, offset: number): string - } - /** - * MysqlBuilder is the builder for MySQL databases. - */ - type _sSBDQlh = BaseBuilder - interface MysqlBuilder extends _sSBDQlh { - } - interface newMysqlBuilder { - /** - * NewMysqlBuilder creates a new MysqlBuilder instance. - */ - (db: DB, executor: Executor): Builder - } - interface MysqlBuilder { - /** - * QueryBuilder returns the query builder supporting the current DB. - */ - queryBuilder(): QueryBuilder - } - interface MysqlBuilder { - /** - * Select returns a new SelectQuery object that can be used to build a SELECT statement. - * The parameters to this method should be the list column names to be selected. - * A column name may have an optional alias name. For example, Select("id", "my_name AS name"). + * OnDelete is a low level hook that is triggered on every [System.Delete] call. + * + * Note that the hook doesn't fire when a file is being overwritten + * by a new one, because in that case [System.Delete] is not invoked. */ - select(...cols: string[]): (SelectQuery) + onDelete(): (hook.Hook) } - interface MysqlBuilder { + interface System { /** - * Model returns a new ModelQuery object that can be used to perform model-based DB operations. - * The model passed to this method should be a pointer to a model struct. + * Exists checks if file with fileKey path exists or not. */ - model(model: { - }): (ModelQuery) + exists(fileKey: string): boolean } - interface MysqlBuilder { + interface System { /** - * QuoteSimpleTableName quotes a simple table name. - * A simple table name does not contain any schema prefix. + * Attributes returns the attributes for the file with fileKey path. + * + * If the file doesn't exist it returns ErrNotFound. */ - quoteSimpleTableName(s: string): string + attributes(fileKey: string): (blob.Attributes) } - interface MysqlBuilder { + interface System { /** - * QuoteSimpleColumnName quotes a simple column name. - * A simple column name does not contain any table prefix. + * GetReader returns a file content reader for the given fileKey. + * + * NB! Make sure to call Close() on the file after you are done working with it. + * + * If the file doesn't exist returns ErrNotFound. */ - quoteSimpleColumnName(s: string): string + getReader(fileKey: string): (blob.Reader) } - interface MysqlBuilder { + interface System { /** - * Upsert creates a Query that represents an UPSERT SQL statement. - * Upsert inserts a row into the table if the primary key or unique index is not found. - * Otherwise it will update the row with the new values. - * The keys of cols are the column names, while the values of cols are the corresponding column - * values to be inserted. + * Deprecated: Please use GetReader(fileKey) instead. */ - upsert(table: string, cols: Params, ...constraints: string[]): (Query) + getFile(fileKey: string): (blob.Reader) } - interface MysqlBuilder { + interface System { /** - * RenameColumn creates a Query that can be used to rename a column in a table. + * GetReuploadableFile constructs a new reuploadable File value + * from the associated fileKey blob.Reader. + * + * If preserveName is false then the returned File.Name will have + * a new randomly generated suffix, otherwise it will reuse the original one. + * + * This method could be useful in case you want to clone an existing + * Record file and assign it to a new Record (e.g. in a Record duplicate action). + * + * If you simply want to copy an existing file to a new location you + * could check the Copy(srcKey, dstKey) method. */ - renameColumn(table: string, oldName: string, newName: string): (Query) + getReuploadableFile(fileKey: string, preserveName: boolean): (File) } - interface MysqlBuilder { + interface System { /** - * DropPrimaryKey creates a Query that can be used to remove the named primary key constraint from a table. + * Copy copies the file stored at srcKey to dstKey. + * + * If srcKey file doesn't exist, it returns ErrNotFound. + * + * If dstKey file already exists, it is overwritten. */ - dropPrimaryKey(table: string, name: string): (Query) + copy(srcKey: string, dstKey: string): void } - interface MysqlBuilder { + interface System { /** - * DropForeignKey creates a Query that can be used to remove the named foreign key constraint from a table. + * List returns a flat list with info for all files under the specified prefix. */ - dropForeignKey(table: string, name: string): (Query) - } - /** - * OciBuilder is the builder for Oracle databases. - */ - type _srFluux = BaseBuilder - interface OciBuilder extends _srFluux { - } - /** - * OciQueryBuilder is the query builder for Oracle databases. - */ - type _smKxGcw = BaseQueryBuilder - interface OciQueryBuilder extends _smKxGcw { + list(prefix: string): Array<(blob.ListObject | undefined)> } - interface newOciBuilder { + interface System { /** - * NewOciBuilder creates a new OciBuilder instance. + * Upload writes content into the fileKey location. */ - (db: DB, executor: Executor): Builder + upload(content: string|Array, fileKey: string): void } - interface OciBuilder { + interface System { /** - * Select returns a new SelectQuery object that can be used to build a SELECT statement. - * The parameters to this method should be the list column names to be selected. - * A column name may have an optional alias name. For example, Select("id", "my_name AS name"). + * UploadFile uploads the provided File to the fileKey location. */ - select(...cols: string[]): (SelectQuery) + uploadFile(file: File, fileKey: string): void } - interface OciBuilder { + interface System { /** - * Model returns a new ModelQuery object that can be used to perform model-based DB operations. - * The model passed to this method should be a pointer to a model struct. + * UploadMultipart uploads the provided multipart file to the fileKey location. */ - model(model: { - }): (ModelQuery) + uploadMultipart(fh: multipart.FileHeader, fileKey: string): void } - interface OciBuilder { + interface System { /** - * GeneratePlaceholder generates an anonymous parameter placeholder with the given parameter ID. + * NewWriter returns a new blob.Writer instance allowing direct file + * create from an io.Reader value. + * + * If a file with the specified fileKey already exists, it will be replaced. + * + * NB! Make sure to call `Close()` on the resulting writer after you are done working with it. + * + * Note: If you have a bytes slice, [filesystem.File], or a multipart header value, + * you can check also the Upload* related methods as they are more user-friendly. + * + * Example: + * + * ``` + * content := strings.NewReader("Lorem ipsum dolor sit amet...") + * + * fsys, _ := filesystem.NewLocal("dir") + * defer fsys.Close() + * + * w, _ := fsys.NewWriter("example/file/key", nil) + * w.ReadFrom(content) + * w.Close() + * ``` */ - generatePlaceholder(i: number): string + newWriter(fileKey: string, opts: blob.WriterOptions): (blob.Writer) } - interface OciBuilder { + interface System { /** - * QueryBuilder returns the query builder supporting the current DB. + * Delete deletes stored file at fileKey location. + * + * If the file doesn't exist returns ErrNotFound. */ - queryBuilder(): QueryBuilder + delete(fileKey: string): void } - interface OciBuilder { + interface System { /** - * DropIndex creates a Query that can be used to remove the named index from a table. + * DeletePrefix deletes everything starting with the specified prefix. + * + * The prefix could be subpath (ex. "/a/b/") or filename prefix (ex. "/a/b/file_"). */ - dropIndex(table: string, name: string): (Query) + deletePrefix(prefix: string): Array } - interface OciBuilder { + interface System { /** - * RenameTable creates a Query that can be used to rename a table. + * Checks if the provided dir prefix doesn't have any files. + * + * A trailing slash will be appended to a non-empty dir string argument + * to ensure that the checked prefix is a "directory". + * + * Returns "false" in case it has at least one file, otherwise - "true". */ - renameTable(oldName: string, newName: string): (Query) + isEmptyDir(dir: string): boolean } - interface OciBuilder { + interface System { /** - * AlterColumn creates a Query that can be used to change the definition of a table column. + * Serve serves the file at fileKey location to an HTTP response. + * + * If the `download` query parameter is used the file will be always served for + * download no matter of its type (aka. with "Content-Disposition: attachment"). + * + * Internally this method uses [http.ServeContent] so Range requests, + * If-Match, If-Unmodified-Since, etc. headers are handled transparently. */ - alterColumn(table: string, col: string, typ: string): (Query) + serve(res: http.ResponseWriter, req: http.Request, fileKey: string, name: string): void } - interface OciQueryBuilder { + interface System { /** - * BuildOrderByAndLimit generates the ORDER BY and LIMIT clauses. + * CreateThumb creates a new thumb image for the file at originalKey location. + * The new thumb file is stored at thumbKey location. + * + * thumbSize is in the format: + * - 0xH (eg. 0x100) - resize to H height preserving the aspect ratio + * - Wx0 (eg. 300x0) - resize to W width preserving the aspect ratio + * - WxH (eg. 300x100) - resize and crop to WxH viewbox (from center) + * - WxHt (eg. 300x100t) - resize and crop to WxH viewbox (from top) + * - WxHb (eg. 300x100b) - resize and crop to WxH viewbox (from bottom) + * - WxHf (eg. 300x100f) - fit inside a WxH viewbox (without cropping) */ - buildOrderByAndLimit(sql: string, cols: Array, limit: number, offset: number): string + createThumb(originalKey: string, thumbKey: string, thumbSize: string): void } +} + +/** + * Package dbx provides a set of DB-agnostic and easy-to-use query building methods for relational databases. + */ +namespace dbx { /** - * PgsqlBuilder is the builder for PostgreSQL databases. + * Builder supports building SQL statements in a DB-agnostic way. + * Builder mainly provides two sets of query building methods: those building SELECT statements + * and those manipulating DB data or schema (e.g. INSERT statements, CREATE TABLE statements). */ - type _syjFlMY = BaseBuilder - interface PgsqlBuilder extends _syjFlMY { - } - interface newPgsqlBuilder { + interface Builder { + [key:string]: any; /** - * NewPgsqlBuilder creates a new PgsqlBuilder instance. + * NewQuery creates a new Query object with the given SQL statement. + * The SQL statement may contain parameter placeholders which can be bound with actual parameter + * values before the statement is executed. */ - (db: DB, executor: Executor): Builder - } - interface PgsqlBuilder { + newQuery(_arg0: string): (Query) /** * Select returns a new SelectQuery object that can be used to build a SELECT statement. * The parameters to this method should be the list column names to be selected. * A column name may have an optional alias name. For example, Select("id", "my_name AS name"). */ - select(...cols: string[]): (SelectQuery) - } - interface PgsqlBuilder { + select(..._arg0: string[]): (SelectQuery) /** - * Model returns a new ModelQuery object that can be used to perform model-based DB operations. - * The model passed to this method should be a pointer to a model struct. + * ModelQuery returns a new ModelQuery object that can be used to perform model insertion, update, and deletion. + * The parameter to this method should be a pointer to the model struct that needs to be inserted, updated, or deleted. */ - model(model: { - }): (ModelQuery) - } - interface PgsqlBuilder { + model(_arg0: { + }): (ModelQuery) /** * GeneratePlaceholder generates an anonymous parameter placeholder with the given parameter ID. */ - generatePlaceholder(i: number): string - } - interface PgsqlBuilder { + generatePlaceholder(_arg0: number): string + /** + * Quote quotes a string so that it can be embedded in a SQL statement as a string value. + */ + quote(_arg0: string): string + /** + * QuoteSimpleTableName quotes a simple table name. + * A simple table name does not contain any schema prefix. + */ + quoteSimpleTableName(_arg0: string): string + /** + * QuoteSimpleColumnName quotes a simple column name. + * A simple column name does not contain any table prefix. + */ + quoteSimpleColumnName(_arg0: string): string /** * QueryBuilder returns the query builder supporting the current DB. */ queryBuilder(): QueryBuilder - } - interface PgsqlBuilder { + /** + * Insert creates a Query that represents an INSERT SQL statement. + * The keys of cols are the column names, while the values of cols are the corresponding column + * values to be inserted. + */ + insert(table: string, cols: Params): (Query) /** * Upsert creates a Query that represents an UPSERT SQL statement. * Upsert inserts a row into the table if the primary key or unique index is not found. @@ -3614,133 +3922,242 @@ namespace dbx { * values to be inserted. */ upsert(table: string, cols: Params, ...constraints: string[]): (Query) - } - interface PgsqlBuilder { /** - * DropIndex creates a Query that can be used to remove the named index from a table. + * Update creates a Query that represents an UPDATE SQL statement. + * The keys of cols are the column names, while the values of cols are the corresponding new column + * values. If the "where" expression is nil, the UPDATE SQL statement will have no WHERE clause + * (be careful in this case as the SQL statement will update ALL rows in the table). */ - dropIndex(table: string, name: string): (Query) - } - interface PgsqlBuilder { + update(table: string, cols: Params, where: Expression): (Query) + /** + * Delete creates a Query that represents a DELETE SQL statement. + * If the "where" expression is nil, the DELETE SQL statement will have no WHERE clause + * (be careful in this case as the SQL statement will delete ALL rows in the table). + */ + delete(table: string, where: Expression): (Query) + /** + * CreateTable creates a Query that represents a CREATE TABLE SQL statement. + * The keys of cols are the column names, while the values of cols are the corresponding column types. + * The optional "options" parameters will be appended to the generated SQL statement. + */ + createTable(table: string, cols: _TygojaDict, ...options: string[]): (Query) /** * RenameTable creates a Query that can be used to rename a table. */ renameTable(oldName: string, newName: string): (Query) - } - interface PgsqlBuilder { + /** + * DropTable creates a Query that can be used to drop a table. + */ + dropTable(table: string): (Query) + /** + * TruncateTable creates a Query that can be used to truncate a table. + */ + truncateTable(table: string): (Query) + /** + * AddColumn creates a Query that can be used to add a column to a table. + */ + addColumn(table: string, col: string, typ: string): (Query) + /** + * DropColumn creates a Query that can be used to drop a column from a table. + */ + dropColumn(table: string, col: string): (Query) + /** + * RenameColumn creates a Query that can be used to rename a column in a table. + */ + renameColumn(table: string, oldName: string, newName: string): (Query) /** * AlterColumn creates a Query that can be used to change the definition of a table column. */ alterColumn(table: string, col: string, typ: string): (Query) + /** + * AddPrimaryKey creates a Query that can be used to specify primary key(s) for a table. + * The "name" parameter specifies the name of the primary key constraint. + */ + addPrimaryKey(table: string, name: string, ...cols: string[]): (Query) + /** + * DropPrimaryKey creates a Query that can be used to remove the named primary key constraint from a table. + */ + dropPrimaryKey(table: string, name: string): (Query) + /** + * AddForeignKey creates a Query that can be used to add a foreign key constraint to a table. + * The length of cols and refCols must be the same as they refer to the primary and referential columns. + * The optional "options" parameters will be appended to the SQL statement. They can be used to + * specify options such as "ON DELETE CASCADE". + */ + addForeignKey(table: string, name: string, cols: Array, refCols: Array, refTable: string, ...options: string[]): (Query) + /** + * DropForeignKey creates a Query that can be used to remove the named foreign key constraint from a table. + */ + dropForeignKey(table: string, name: string): (Query) + /** + * CreateIndex creates a Query that can be used to create an index for a table. + */ + createIndex(table: string, name: string, ...cols: string[]): (Query) + /** + * CreateUniqueIndex creates a Query that can be used to create a unique index for a table. + */ + createUniqueIndex(table: string, name: string, ...cols: string[]): (Query) + /** + * DropIndex creates a Query that can be used to remove the named index from a table. + */ + dropIndex(table: string, name: string): (Query) } /** - * SqliteQueryBuilder is the query builder for SQLite databases. + * BaseBuilder provides a basic implementation of the Builder interface. */ - type _sDHUMAL = BaseQueryBuilder - interface SqliteQueryBuilder extends _sDHUMAL { + interface BaseBuilder { } - interface SqliteQueryBuilder { + interface newBaseBuilder { /** - * BuildUnion generates a UNION clause from the given union information. - * - * This is similar to BaseQueryBuilder.BuildUnion but without the parenthesis wrapping. + * NewBaseBuilder creates a new BaseBuilder instance. */ - buildUnion(unions: Array, params: Params): string + (db: DB, executor: Executor): (BaseBuilder) } - interface SqliteQueryBuilder { + interface BaseBuilder { /** - * CombineUnion combines the nonempty unionClause with the provided sql string. - * - * This is similar to BaseQueryBuilder.CombineUnion but without the parenthesis wrapping. + * DB returns the DB instance that this builder is associated with. */ - combineUnion(sql: string, unionClause: string): string - } - /** - * SqliteBuilder is the builder for SQLite databases. - */ - type _sEfwqAY = BaseBuilder - interface SqliteBuilder extends _sEfwqAY { + db(): (DB) } - interface newSqliteBuilder { + interface BaseBuilder { /** - * NewSqliteBuilder creates a new SqliteBuilder instance. + * Executor returns the executor object (a DB instance or a transaction) for executing SQL statements. */ - (db: DB, executor: Executor): Builder + executor(): Executor } - interface SqliteBuilder { + interface BaseBuilder { /** - * QueryBuilder returns the query builder supporting the current DB. + * NewQuery creates a new Query object with the given SQL statement. + * The SQL statement may contain parameter placeholders which can be bound with actual parameter + * values before the statement is executed. */ - queryBuilder(): QueryBuilder + newQuery(sql: string): (Query) } - interface SqliteBuilder { + interface BaseBuilder { /** - * Select returns a new SelectQuery object that can be used to build a SELECT statement. - * The parameters to this method should be the list column names to be selected. - * A column name may have an optional alias name. For example, Select("id", "my_name AS name"). + * GeneratePlaceholder generates an anonymous parameter placeholder with the given parameter ID. */ - select(...cols: string[]): (SelectQuery) + generatePlaceholder(_arg0: number): string } - interface SqliteBuilder { + interface BaseBuilder { /** - * Model returns a new ModelQuery object that can be used to perform model-based DB operations. - * The model passed to this method should be a pointer to a model struct. + * Quote quotes a string so that it can be embedded in a SQL statement as a string value. */ - model(model: { - }): (ModelQuery) + quote(s: string): string } - interface SqliteBuilder { + interface BaseBuilder { /** * QuoteSimpleTableName quotes a simple table name. * A simple table name does not contain any schema prefix. */ quoteSimpleTableName(s: string): string } - interface SqliteBuilder { + interface BaseBuilder { /** * QuoteSimpleColumnName quotes a simple column name. * A simple column name does not contain any table prefix. */ quoteSimpleColumnName(s: string): string } - interface SqliteBuilder { + interface BaseBuilder { /** - * DropIndex creates a Query that can be used to remove the named index from a table. + * Insert creates a Query that represents an INSERT SQL statement. + * The keys of cols are the column names, while the values of cols are the corresponding column + * values to be inserted. */ - dropIndex(table: string, name: string): (Query) + insert(table: string, cols: Params): (Query) } - interface SqliteBuilder { + interface BaseBuilder { /** - * TruncateTable creates a Query that can be used to truncate a table. + * Upsert creates a Query that represents an UPSERT SQL statement. + * Upsert inserts a row into the table if the primary key or unique index is not found. + * Otherwise it will update the row with the new values. + * The keys of cols are the column names, while the values of cols are the corresponding column + * values to be inserted. */ - truncateTable(table: string): (Query) + upsert(table: string, cols: Params, ...constraints: string[]): (Query) } - interface SqliteBuilder { + interface BaseBuilder { + /** + * Update creates a Query that represents an UPDATE SQL statement. + * The keys of cols are the column names, while the values of cols are the corresponding new column + * values. If the "where" expression is nil, the UPDATE SQL statement will have no WHERE clause + * (be careful in this case as the SQL statement will update ALL rows in the table). + */ + update(table: string, cols: Params, where: Expression): (Query) + } + interface BaseBuilder { + /** + * Delete creates a Query that represents a DELETE SQL statement. + * If the "where" expression is nil, the DELETE SQL statement will have no WHERE clause + * (be careful in this case as the SQL statement will delete ALL rows in the table). + */ + delete(table: string, where: Expression): (Query) + } + interface BaseBuilder { + /** + * CreateTable creates a Query that represents a CREATE TABLE SQL statement. + * The keys of cols are the column names, while the values of cols are the corresponding column types. + * The optional "options" parameters will be appended to the generated SQL statement. + */ + createTable(table: string, cols: _TygojaDict, ...options: string[]): (Query) + } + interface BaseBuilder { /** * RenameTable creates a Query that can be used to rename a table. */ renameTable(oldName: string, newName: string): (Query) } - interface SqliteBuilder { + interface BaseBuilder { + /** + * DropTable creates a Query that can be used to drop a table. + */ + dropTable(table: string): (Query) + } + interface BaseBuilder { + /** + * TruncateTable creates a Query that can be used to truncate a table. + */ + truncateTable(table: string): (Query) + } + interface BaseBuilder { + /** + * AddColumn creates a Query that can be used to add a column to a table. + */ + addColumn(table: string, col: string, typ: string): (Query) + } + interface BaseBuilder { + /** + * DropColumn creates a Query that can be used to drop a column from a table. + */ + dropColumn(table: string, col: string): (Query) + } + interface BaseBuilder { + /** + * RenameColumn creates a Query that can be used to rename a column in a table. + */ + renameColumn(table: string, oldName: string, newName: string): (Query) + } + interface BaseBuilder { /** * AlterColumn creates a Query that can be used to change the definition of a table column. */ alterColumn(table: string, col: string, typ: string): (Query) } - interface SqliteBuilder { + interface BaseBuilder { /** * AddPrimaryKey creates a Query that can be used to specify primary key(s) for a table. * The "name" parameter specifies the name of the primary key constraint. */ addPrimaryKey(table: string, name: string, ...cols: string[]): (Query) } - interface SqliteBuilder { + interface BaseBuilder { /** * DropPrimaryKey creates a Query that can be used to remove the named primary key constraint from a table. */ dropPrimaryKey(table: string, name: string): (Query) } - interface SqliteBuilder { + interface BaseBuilder { /** * AddForeignKey creates a Query that can be used to add a foreign key constraint to a table. * The length of cols and refCols must be the same as they refer to the primary and referential columns. @@ -3749,31 +4166,55 @@ namespace dbx { */ addForeignKey(table: string, name: string, cols: Array, refCols: Array, refTable: string, ...options: string[]): (Query) } - interface SqliteBuilder { + interface BaseBuilder { /** * DropForeignKey creates a Query that can be used to remove the named foreign key constraint from a table. */ dropForeignKey(table: string, name: string): (Query) } - /** - * StandardBuilder is the builder that is used by DB for an unknown driver. - */ - type _ssbrLtO = BaseBuilder - interface StandardBuilder extends _ssbrLtO { - } - interface newStandardBuilder { + interface BaseBuilder { /** - * NewStandardBuilder creates a new StandardBuilder instance. + * CreateIndex creates a Query that can be used to create an index for a table. */ - (db: DB, executor: Executor): Builder + createIndex(table: string, name: string, ...cols: string[]): (Query) } - interface StandardBuilder { + interface BaseBuilder { /** - * QueryBuilder returns the query builder supporting the current DB. + * CreateUniqueIndex creates a Query that can be used to create a unique index for a table. + */ + createUniqueIndex(table: string, name: string, ...cols: string[]): (Query) + } + interface BaseBuilder { + /** + * DropIndex creates a Query that can be used to remove the named index from a table. + */ + dropIndex(table: string, name: string): (Query) + } + /** + * MssqlBuilder is the builder for SQL Server databases. + */ + type _sTrYvtS = BaseBuilder + interface MssqlBuilder extends _sTrYvtS { + } + /** + * MssqlQueryBuilder is the query builder for SQL Server databases. + */ + type _skVixHw = BaseQueryBuilder + interface MssqlQueryBuilder extends _skVixHw { + } + interface newMssqlBuilder { + /** + * NewMssqlBuilder creates a new MssqlBuilder instance. + */ + (db: DB, executor: Executor): Builder + } + interface MssqlBuilder { + /** + * QueryBuilder returns the query builder supporting the current DB. */ queryBuilder(): QueryBuilder } - interface StandardBuilder { + interface MssqlBuilder { /** * Select returns a new SelectQuery object that can be used to build a SELECT statement. * The parameters to this method should be the list column names to be selected. @@ -3781,7 +4222,7 @@ namespace dbx { */ select(...cols: string[]): (SelectQuery) } - interface StandardBuilder { + interface MssqlBuilder { /** * Model returns a new ModelQuery object that can be used to perform model-based DB operations. * The model passed to this method should be a pointer to a model struct. @@ -3789,574 +4230,466 @@ namespace dbx { model(model: { }): (ModelQuery) } - /** - * LogFunc logs a message for each SQL statement being executed. - * This method takes one or multiple parameters. If a single parameter - * is provided, it will be treated as the log message. If multiple parameters - * are provided, they will be passed to fmt.Sprintf() to generate the log message. - */ - interface LogFunc {(format: string, ...a: { - }[]): void } - /** - * PerfFunc is called when a query finishes execution. - * The query execution time is passed to this function so that the DB performance - * can be profiled. The "ns" parameter gives the number of nanoseconds that the - * SQL statement takes to execute, while the "execute" parameter indicates whether - * the SQL statement is executed or queried (usually SELECT statements). - */ - interface PerfFunc {(ns: number, sql: string, execute: boolean): void } - /** - * QueryLogFunc is called each time when performing a SQL query. - * The "t" parameter gives the time that the SQL statement takes to execute, - * while rows and err are the result of the query. - */ - interface QueryLogFunc {(ctx: context.Context, t: time.Duration, sql: string, rows: sql.Rows, err: Error): void } - /** - * ExecLogFunc is called each time when a SQL statement is executed. - * The "t" parameter gives the time that the SQL statement takes to execute, - * while result and err refer to the result of the execution. - */ - interface ExecLogFunc {(ctx: context.Context, t: time.Duration, sql: string, result: sql.Result, err: Error): void } - /** - * BuilderFunc creates a Builder instance using the given DB instance and Executor. - */ - interface BuilderFunc {(_arg0: DB, _arg1: Executor): Builder } - /** - * DB enhances sql.DB by providing a set of DB-agnostic query building methods. - * DB allows easier query building and population of data into Go variables. - */ - type _sDtvvOV = Builder - interface DB extends _sDtvvOV { + interface MssqlBuilder { /** - * FieldMapper maps struct fields to DB columns. Defaults to DefaultFieldMapFunc. + * QuoteSimpleTableName quotes a simple table name. + * A simple table name does not contain any schema prefix. */ - fieldMapper: FieldMapFunc + quoteSimpleTableName(s: string): string + } + interface MssqlBuilder { /** - * TableMapper maps structs to table names. Defaults to GetTableName. + * QuoteSimpleColumnName quotes a simple column name. + * A simple column name does not contain any table prefix. */ - tableMapper: TableMapFunc + quoteSimpleColumnName(s: string): string + } + interface MssqlBuilder { /** - * LogFunc logs the SQL statements being executed. Defaults to nil, meaning no logging. + * RenameTable creates a Query that can be used to rename a table. */ - logFunc: LogFunc + renameTable(oldName: string, newName: string): (Query) + } + interface MssqlBuilder { /** - * PerfFunc logs the SQL execution time. Defaults to nil, meaning no performance profiling. - * Deprecated: Please use QueryLogFunc and ExecLogFunc instead. + * RenameColumn creates a Query that can be used to rename a column in a table. */ - perfFunc: PerfFunc + renameColumn(table: string, oldName: string, newName: string): (Query) + } + interface MssqlBuilder { /** - * QueryLogFunc is called each time when performing a SQL query that returns data. + * AlterColumn creates a Query that can be used to change the definition of a table column. */ - queryLogFunc: QueryLogFunc + alterColumn(table: string, col: string, typ: string): (Query) + } + interface MssqlQueryBuilder { /** - * ExecLogFunc is called each time when a SQL statement is executed. + * BuildOrderByAndLimit generates the ORDER BY and LIMIT clauses. */ - execLogFunc: ExecLogFunc + buildOrderByAndLimit(sql: string, cols: Array, limit: number, offset: number): string } /** - * Errors represents a list of errors. + * MysqlBuilder is the builder for MySQL databases. */ - interface Errors extends Array{} - interface newFromDB { + type _sqfAveJ = BaseBuilder + interface MysqlBuilder extends _sqfAveJ { + } + interface newMysqlBuilder { /** - * NewFromDB encapsulates an existing database connection. + * NewMysqlBuilder creates a new MysqlBuilder instance. */ - (sqlDB: sql.DB, driverName: string): (DB) + (db: DB, executor: Executor): Builder } - interface open { + interface MysqlBuilder { /** - * Open opens a database specified by a driver name and data source name (DSN). - * Note that Open does not check if DSN is specified correctly. It doesn't try to establish a DB connection either. - * Please refer to sql.Open() for more information. + * QueryBuilder returns the query builder supporting the current DB. */ - (driverName: string, dsn: string): (DB) + queryBuilder(): QueryBuilder } - interface mustOpen { + interface MysqlBuilder { /** - * MustOpen opens a database and establishes a connection to it. - * Please refer to sql.Open() and sql.Ping() for more information. + * Select returns a new SelectQuery object that can be used to build a SELECT statement. + * The parameters to this method should be the list column names to be selected. + * A column name may have an optional alias name. For example, Select("id", "my_name AS name"). */ - (driverName: string, dsn: string): (DB) + select(...cols: string[]): (SelectQuery) } - interface DB { + interface MysqlBuilder { /** - * Clone makes a shallow copy of DB. + * Model returns a new ModelQuery object that can be used to perform model-based DB operations. + * The model passed to this method should be a pointer to a model struct. */ - clone(): (DB) + model(model: { + }): (ModelQuery) } - interface DB { + interface MysqlBuilder { /** - * WithContext returns a new instance of DB associated with the given context. + * QuoteSimpleTableName quotes a simple table name. + * A simple table name does not contain any schema prefix. */ - withContext(ctx: context.Context): (DB) + quoteSimpleTableName(s: string): string } - interface DB { + interface MysqlBuilder { /** - * Context returns the context associated with the DB instance. - * It returns nil if no context is associated. + * QuoteSimpleColumnName quotes a simple column name. + * A simple column name does not contain any table prefix. */ - context(): context.Context + quoteSimpleColumnName(s: string): string } - interface DB { + interface MysqlBuilder { /** - * DB returns the sql.DB instance encapsulated by dbx.DB. + * Upsert creates a Query that represents an UPSERT SQL statement. + * Upsert inserts a row into the table if the primary key or unique index is not found. + * Otherwise it will update the row with the new values. + * The keys of cols are the column names, while the values of cols are the corresponding column + * values to be inserted. */ - db(): (sql.DB) + upsert(table: string, cols: Params, ...constraints: string[]): (Query) } - interface DB { + interface MysqlBuilder { /** - * Close closes the database, releasing any open resources. - * It is rare to Close a DB, as the DB handle is meant to be - * long-lived and shared between many goroutines. + * RenameColumn creates a Query that can be used to rename a column in a table. */ - close(): void + renameColumn(table: string, oldName: string, newName: string): (Query) } - interface DB { + interface MysqlBuilder { /** - * Begin starts a transaction. + * DropPrimaryKey creates a Query that can be used to remove the named primary key constraint from a table. */ - begin(): (Tx) + dropPrimaryKey(table: string, name: string): (Query) } - interface DB { + interface MysqlBuilder { /** - * BeginTx starts a transaction with the given context and transaction options. + * DropForeignKey creates a Query that can be used to remove the named foreign key constraint from a table. */ - beginTx(ctx: context.Context, opts: sql.TxOptions): (Tx) + dropForeignKey(table: string, name: string): (Query) } - interface DB { + /** + * OciBuilder is the builder for Oracle databases. + */ + type _smUgthB = BaseBuilder + interface OciBuilder extends _smUgthB { + } + /** + * OciQueryBuilder is the query builder for Oracle databases. + */ + type _sXsczQY = BaseQueryBuilder + interface OciQueryBuilder extends _sXsczQY { + } + interface newOciBuilder { /** - * Wrap encapsulates an existing transaction. + * NewOciBuilder creates a new OciBuilder instance. */ - wrap(sqlTx: sql.Tx): (Tx) + (db: DB, executor: Executor): Builder } - interface DB { + interface OciBuilder { /** - * Transactional starts a transaction and executes the given function. - * If the function returns an error, the transaction will be rolled back. - * Otherwise, the transaction will be committed. + * Select returns a new SelectQuery object that can be used to build a SELECT statement. + * The parameters to this method should be the list column names to be selected. + * A column name may have an optional alias name. For example, Select("id", "my_name AS name"). */ - transactional(f: (_arg0: Tx) => void): void + select(...cols: string[]): (SelectQuery) } - interface DB { + interface OciBuilder { /** - * TransactionalContext starts a transaction and executes the given function with the given context and transaction options. - * If the function returns an error, the transaction will be rolled back. - * Otherwise, the transaction will be committed. + * Model returns a new ModelQuery object that can be used to perform model-based DB operations. + * The model passed to this method should be a pointer to a model struct. */ - transactionalContext(ctx: context.Context, opts: sql.TxOptions, f: (_arg0: Tx) => void): void + model(model: { + }): (ModelQuery) } - interface DB { + interface OciBuilder { /** - * DriverName returns the name of the DB driver. + * GeneratePlaceholder generates an anonymous parameter placeholder with the given parameter ID. */ - driverName(): string + generatePlaceholder(i: number): string } - interface DB { + interface OciBuilder { /** - * QuoteTableName quotes the given table name appropriately. - * If the table name contains DB schema prefix, it will be handled accordingly. - * This method will do nothing if the table name is already quoted or if it contains parenthesis. + * QueryBuilder returns the query builder supporting the current DB. */ - quoteTableName(s: string): string + queryBuilder(): QueryBuilder } - interface DB { + interface OciBuilder { /** - * QuoteColumnName quotes the given column name appropriately. - * If the table name contains table name prefix, it will be handled accordingly. - * This method will do nothing if the column name is already quoted or if it contains parenthesis. + * DropIndex creates a Query that can be used to remove the named index from a table. */ - quoteColumnName(s: string): string + dropIndex(table: string, name: string): (Query) } - interface Errors { + interface OciBuilder { /** - * Error returns the error string of Errors. + * RenameTable creates a Query that can be used to rename a table. */ - error(): string + renameTable(oldName: string, newName: string): (Query) } - /** - * Expression represents a DB expression that can be embedded in a SQL statement. - */ - interface Expression { - [key:string]: any; + interface OciBuilder { /** - * Build converts an expression into a SQL fragment. - * If the expression contains binding parameters, they will be added to the given Params. + * AlterColumn creates a Query that can be used to change the definition of a table column. */ - build(_arg0: DB, _arg1: Params): string + alterColumn(table: string, col: string, typ: string): (Query) + } + interface OciQueryBuilder { + /** + * BuildOrderByAndLimit generates the ORDER BY and LIMIT clauses. + */ + buildOrderByAndLimit(sql: string, cols: Array, limit: number, offset: number): string } /** - * HashExp represents a hash expression. - * - * A hash expression is a map whose keys are DB column names which need to be filtered according - * to the corresponding values. For example, HashExp{"level": 2, "dept": 10} will generate - * the SQL: "level"=2 AND "dept"=10. - * - * HashExp also handles nil values and slice values. For example, HashExp{"level": []interface{}{1, 2}, "dept": nil} - * will generate: "level" IN (1, 2) AND "dept" IS NULL. + * PgsqlBuilder is the builder for PostgreSQL databases. */ - interface HashExp extends _TygojaDict{} - interface newExp { + type _sRgqaXj = BaseBuilder + interface PgsqlBuilder extends _sRgqaXj { + } + interface newPgsqlBuilder { /** - * NewExp generates an expression with the specified SQL fragment and the optional binding parameters. + * NewPgsqlBuilder creates a new PgsqlBuilder instance. */ - (e: string, ...params: Params[]): Expression + (db: DB, executor: Executor): Builder } - interface not { + interface PgsqlBuilder { /** - * Not generates a NOT expression which prefixes "NOT" to the specified expression. + * Select returns a new SelectQuery object that can be used to build a SELECT statement. + * The parameters to this method should be the list column names to be selected. + * A column name may have an optional alias name. For example, Select("id", "my_name AS name"). */ - (e: Expression): Expression + select(...cols: string[]): (SelectQuery) } - interface and { + interface PgsqlBuilder { /** - * And generates an AND expression which concatenates the given expressions with "AND". + * Model returns a new ModelQuery object that can be used to perform model-based DB operations. + * The model passed to this method should be a pointer to a model struct. */ - (...exps: Expression[]): Expression + model(model: { + }): (ModelQuery) } - interface or { + interface PgsqlBuilder { /** - * Or generates an OR expression which concatenates the given expressions with "OR". + * GeneratePlaceholder generates an anonymous parameter placeholder with the given parameter ID. */ - (...exps: Expression[]): Expression + generatePlaceholder(i: number): string } - interface _in { + interface PgsqlBuilder { /** - * In generates an IN expression for the specified column and the list of allowed values. - * If values is empty, a SQL "0=1" will be generated which represents a false expression. + * QueryBuilder returns the query builder supporting the current DB. */ - (col: string, ...values: { - }[]): Expression + queryBuilder(): QueryBuilder } - interface notIn { + interface PgsqlBuilder { /** - * NotIn generates an NOT IN expression for the specified column and the list of disallowed values. - * If values is empty, an empty string will be returned indicating a true expression. + * Upsert creates a Query that represents an UPSERT SQL statement. + * Upsert inserts a row into the table if the primary key or unique index is not found. + * Otherwise it will update the row with the new values. + * The keys of cols are the column names, while the values of cols are the corresponding column + * values to be inserted. */ - (col: string, ...values: { - }[]): Expression + upsert(table: string, cols: Params, ...constraints: string[]): (Query) } - interface like { + interface PgsqlBuilder { /** - * Like generates a LIKE expression for the specified column and the possible strings that the column should be like. - * If multiple values are present, the column should be like *all* of them. For example, Like("name", "key", "word") - * will generate a SQL expression: "name" LIKE "%key%" AND "name" LIKE "%word%". - * - * By default, each value will be surrounded by "%" to enable partial matching. If a value contains special characters - * such as "%", "\", "_", they will also be properly escaped. - * - * You may call Escape() and/or Match() to change the default behavior. For example, Like("name", "key").Match(false, true) - * generates "name" LIKE "key%". + * DropIndex creates a Query that can be used to remove the named index from a table. */ - (col: string, ...values: string[]): (LikeExp) + dropIndex(table: string, name: string): (Query) } - interface notLike { + interface PgsqlBuilder { /** - * NotLike generates a NOT LIKE expression. - * For example, NotLike("name", "key", "word") will generate a SQL expression: - * "name" NOT LIKE "%key%" AND "name" NOT LIKE "%word%". Please see Like() for more details. + * RenameTable creates a Query that can be used to rename a table. */ - (col: string, ...values: string[]): (LikeExp) + renameTable(oldName: string, newName: string): (Query) } - interface orLike { + interface PgsqlBuilder { /** - * OrLike generates an OR LIKE expression. - * This is similar to Like() except that the column should be like one of the possible values. - * For example, OrLike("name", "key", "word") will generate a SQL expression: - * "name" LIKE "%key%" OR "name" LIKE "%word%". Please see Like() for more details. + * AlterColumn creates a Query that can be used to change the definition of a table column. */ - (col: string, ...values: string[]): (LikeExp) + alterColumn(table: string, col: string, typ: string): (Query) } - interface orNotLike { + /** + * SqliteQueryBuilder is the query builder for SQLite databases. + */ + type _sAxEutQ = BaseQueryBuilder + interface SqliteQueryBuilder extends _sAxEutQ { + } + interface SqliteQueryBuilder { /** - * OrNotLike generates an OR NOT LIKE expression. - * For example, OrNotLike("name", "key", "word") will generate a SQL expression: - * "name" NOT LIKE "%key%" OR "name" NOT LIKE "%word%". Please see Like() for more details. + * BuildUnion generates a UNION clause from the given union information. + * + * This is similar to BaseQueryBuilder.BuildUnion but without the parenthesis wrapping. */ - (col: string, ...values: string[]): (LikeExp) + buildUnion(unions: Array, params: Params): string } - interface exists { + interface SqliteQueryBuilder { /** - * Exists generates an EXISTS expression by prefixing "EXISTS" to the given expression. + * CombineUnion combines the nonempty unionClause with the provided sql string. + * + * This is similar to BaseQueryBuilder.CombineUnion but without the parenthesis wrapping. */ - (exp: Expression): Expression + combineUnion(sql: string, unionClause: string): string } - interface notExists { + /** + * SqliteBuilder is the builder for SQLite databases. + */ + type _sOcKIiu = BaseBuilder + interface SqliteBuilder extends _sOcKIiu { + } + interface newSqliteBuilder { /** - * NotExists generates an EXISTS expression by prefixing "NOT EXISTS" to the given expression. + * NewSqliteBuilder creates a new SqliteBuilder instance. */ - (exp: Expression): Expression + (db: DB, executor: Executor): Builder } - interface between { + interface SqliteBuilder { /** - * Between generates a BETWEEN expression. - * For example, Between("age", 10, 30) generates: "age" BETWEEN 10 AND 30 + * QueryBuilder returns the query builder supporting the current DB. */ - (col: string, from: { - }, to: { - }): Expression + queryBuilder(): QueryBuilder } - interface notBetween { + interface SqliteBuilder { /** - * NotBetween generates a NOT BETWEEN expression. - * For example, NotBetween("age", 10, 30) generates: "age" NOT BETWEEN 10 AND 30 + * Select returns a new SelectQuery object that can be used to build a SELECT statement. + * The parameters to this method should be the list column names to be selected. + * A column name may have an optional alias name. For example, Select("id", "my_name AS name"). */ - (col: string, from: { - }, to: { - }): Expression - } - /** - * Exp represents an expression with a SQL fragment and a list of optional binding parameters. - */ - interface Exp { + select(...cols: string[]): (SelectQuery) } - interface Exp { + interface SqliteBuilder { /** - * Build converts an expression into a SQL fragment. + * Model returns a new ModelQuery object that can be used to perform model-based DB operations. + * The model passed to this method should be a pointer to a model struct. */ - build(db: DB, params: Params): string + model(model: { + }): (ModelQuery) } - interface HashExp { + interface SqliteBuilder { /** - * Build converts an expression into a SQL fragment. + * QuoteSimpleTableName quotes a simple table name. + * A simple table name does not contain any schema prefix. */ - build(db: DB, params: Params): string - } - /** - * NotExp represents an expression that should prefix "NOT" to a specified expression. - */ - interface NotExp { + quoteSimpleTableName(s: string): string } - interface NotExp { + interface SqliteBuilder { /** - * Build converts an expression into a SQL fragment. + * QuoteSimpleColumnName quotes a simple column name. + * A simple column name does not contain any table prefix. */ - build(db: DB, params: Params): string + quoteSimpleColumnName(s: string): string } - /** - * AndOrExp represents an expression that concatenates multiple expressions using either "AND" or "OR". - */ - interface AndOrExp { + interface SqliteBuilder { + /** + * DropIndex creates a Query that can be used to remove the named index from a table. + */ + dropIndex(table: string, name: string): (Query) } - interface AndOrExp { + interface SqliteBuilder { /** - * Build converts an expression into a SQL fragment. + * TruncateTable creates a Query that can be used to truncate a table. */ - build(db: DB, params: Params): string + truncateTable(table: string): (Query) } - /** - * InExp represents an "IN" or "NOT IN" expression. - */ - interface InExp { + interface SqliteBuilder { + /** + * RenameTable creates a Query that can be used to rename a table. + */ + renameTable(oldName: string, newName: string): (Query) } - interface InExp { + interface SqliteBuilder { /** - * Build converts an expression into a SQL fragment. + * AlterColumn creates a Query that can be used to change the definition of a table column. */ - build(db: DB, params: Params): string + alterColumn(table: string, col: string, typ: string): (Query) } - /** - * LikeExp represents a variant of LIKE expressions. - */ - interface LikeExp { + interface SqliteBuilder { /** - * Like stores the LIKE operator. It can be "LIKE", "NOT LIKE". - * It may also be customized as something like "ILIKE". + * AddPrimaryKey creates a Query that can be used to specify primary key(s) for a table. + * The "name" parameter specifies the name of the primary key constraint. */ - like: string + addPrimaryKey(table: string, name: string, ...cols: string[]): (Query) } - interface LikeExp { + interface SqliteBuilder { /** - * Escape specifies how a LIKE expression should be escaped. - * Each string at position 2i represents a special character and the string at position 2i+1 is - * the corresponding escaped version. + * DropPrimaryKey creates a Query that can be used to remove the named primary key constraint from a table. */ - escape(...chars: string[]): (LikeExp) + dropPrimaryKey(table: string, name: string): (Query) } - interface LikeExp { + interface SqliteBuilder { /** - * Match specifies whether to do wildcard matching on the left and/or right of given strings. + * AddForeignKey creates a Query that can be used to add a foreign key constraint to a table. + * The length of cols and refCols must be the same as they refer to the primary and referential columns. + * The optional "options" parameters will be appended to the SQL statement. They can be used to + * specify options such as "ON DELETE CASCADE". */ - match(left: boolean, right: boolean): (LikeExp) + addForeignKey(table: string, name: string, cols: Array, refCols: Array, refTable: string, ...options: string[]): (Query) } - interface LikeExp { + interface SqliteBuilder { /** - * Build converts an expression into a SQL fragment. + * DropForeignKey creates a Query that can be used to remove the named foreign key constraint from a table. */ - build(db: DB, params: Params): string + dropForeignKey(table: string, name: string): (Query) } /** - * ExistsExp represents an EXISTS or NOT EXISTS expression. + * StandardBuilder is the builder that is used by DB for an unknown driver. */ - interface ExistsExp { + type _sKcLglG = BaseBuilder + interface StandardBuilder extends _sKcLglG { } - interface ExistsExp { + interface newStandardBuilder { /** - * Build converts an expression into a SQL fragment. + * NewStandardBuilder creates a new StandardBuilder instance. */ - build(db: DB, params: Params): string + (db: DB, executor: Executor): Builder } - /** - * BetweenExp represents a BETWEEN or a NOT BETWEEN expression. - */ - interface BetweenExp { - } - interface BetweenExp { - /** - * Build converts an expression into a SQL fragment. - */ - build(db: DB, params: Params): string - } - interface enclose { - /** - * Enclose surrounds the provided nonempty expression with parenthesis "()". - */ - (exp: Expression): Expression - } - /** - * EncloseExp represents a parenthesis enclosed expression. - */ - interface EncloseExp { - } - interface EncloseExp { - /** - * Build converts an expression into a SQL fragment. - */ - build(db: DB, params: Params): string - } - /** - * TableModel is the interface that should be implemented by models which have unconventional table names. - */ - interface TableModel { - [key:string]: any; - tableName(): string - } - /** - * ModelQuery represents a query associated with a struct model. - */ - interface ModelQuery { - } - interface newModelQuery { - (model: { - }, fieldMapFunc: FieldMapFunc, db: DB, builder: Builder): (ModelQuery) - } - interface ModelQuery { - /** - * Context returns the context associated with the query. - */ - context(): context.Context - } - interface ModelQuery { - /** - * WithContext associates a context with the query. - */ - withContext(ctx: context.Context): (ModelQuery) - } - interface ModelQuery { - /** - * Exclude excludes the specified struct fields from being inserted/updated into the DB table. - */ - exclude(...attrs: string[]): (ModelQuery) - } - interface ModelQuery { + interface StandardBuilder { /** - * Insert inserts a row in the table using the struct model associated with this query. - * - * By default, it inserts *all* public fields into the table, including those nil or empty ones. - * You may pass a list of the fields to this method to indicate that only those fields should be inserted. - * You may also call Exclude to exclude some fields from being inserted. - * - * If a model has an empty primary key, it is considered auto-incremental and the corresponding struct - * field will be filled with the generated primary key value after a successful insertion. + * QueryBuilder returns the query builder supporting the current DB. */ - insert(...attrs: string[]): void + queryBuilder(): QueryBuilder } - interface ModelQuery { + interface StandardBuilder { /** - * Update updates a row in the table using the struct model associated with this query. - * The row being updated has the same primary key as specified by the model. - * - * By default, it updates *all* public fields in the table, including those nil or empty ones. - * You may pass a list of the fields to this method to indicate that only those fields should be updated. - * You may also call Exclude to exclude some fields from being updated. + * Select returns a new SelectQuery object that can be used to build a SELECT statement. + * The parameters to this method should be the list column names to be selected. + * A column name may have an optional alias name. For example, Select("id", "my_name AS name"). */ - update(...attrs: string[]): void + select(...cols: string[]): (SelectQuery) } - interface ModelQuery { + interface StandardBuilder { /** - * Delete deletes a row in the table using the primary key specified by the struct model associated with this query. + * Model returns a new ModelQuery object that can be used to perform model-based DB operations. + * The model passed to this method should be a pointer to a model struct. */ - delete(): void + model(model: { + }): (ModelQuery) } /** - * ExecHookFunc executes before op allowing custom handling like auto fail/retry. + * LogFunc logs a message for each SQL statement being executed. + * This method takes one or multiple parameters. If a single parameter + * is provided, it will be treated as the log message. If multiple parameters + * are provided, they will be passed to fmt.Sprintf() to generate the log message. */ - interface ExecHookFunc {(q: Query, op: () => void): void } + interface LogFunc {(format: string, ...a: { + }[]): void } /** - * OneHookFunc executes right before the query populate the row result from One() call (aka. op). + * PerfFunc is called when a query finishes execution. + * The query execution time is passed to this function so that the DB performance + * can be profiled. The "ns" parameter gives the number of nanoseconds that the + * SQL statement takes to execute, while the "execute" parameter indicates whether + * the SQL statement is executed or queried (usually SELECT statements). */ - interface OneHookFunc {(q: Query, a: { - }, op: (b: { - }) => void): void } + interface PerfFunc {(ns: number, sql: string, execute: boolean): void } /** - * AllHookFunc executes right before the query populate the row result from All() call (aka. op). + * QueryLogFunc is called each time when performing a SQL query. + * The "t" parameter gives the time that the SQL statement takes to execute, + * while rows and err are the result of the query. */ - interface AllHookFunc {(q: Query, sliceA: { - }, op: (sliceB: { - }) => void): void } + interface QueryLogFunc {(ctx: context.Context, t: time.Duration, sql: string, rows: sql.Rows, err: Error): void } /** - * Params represents a list of parameter values to be bound to a SQL statement. - * The map keys are the parameter names while the map values are the corresponding parameter values. + * ExecLogFunc is called each time when a SQL statement is executed. + * The "t" parameter gives the time that the SQL statement takes to execute, + * while result and err refer to the result of the execution. */ - interface Params extends _TygojaDict{} + interface ExecLogFunc {(ctx: context.Context, t: time.Duration, sql: string, result: sql.Result, err: Error): void } /** - * Executor prepares, executes, or queries a SQL statement. + * BuilderFunc creates a Builder instance using the given DB instance and Executor. */ - interface Executor { - [key:string]: any; - /** - * Exec executes a SQL statement - */ - exec(query: string, ...args: { - }[]): sql.Result - /** - * ExecContext executes a SQL statement with the given context - */ - execContext(ctx: context.Context, query: string, ...args: { - }[]): sql.Result - /** - * Query queries a SQL statement - */ - query(query: string, ...args: { - }[]): (sql.Rows) - /** - * QueryContext queries a SQL statement with the given context - */ - queryContext(ctx: context.Context, query: string, ...args: { - }[]): (sql.Rows) - /** - * Prepare creates a prepared statement - */ - prepare(query: string): (sql.Stmt) - } + interface BuilderFunc {(_arg0: DB, _arg1: Executor): Builder } /** - * Query represents a SQL statement to be executed. + * DB enhances sql.DB by providing a set of DB-agnostic query building methods. + * DB allows easier query building and population of data into Go variables. */ - interface Query { + type _syqLKzO = Builder + interface DB extends _syqLKzO { /** - * FieldMapper maps struct field names to DB column names. + * FieldMapper maps struct fields to DB columns. Defaults to DefaultFieldMapFunc. */ fieldMapper: FieldMapFunc /** - * LastError contains the last error (if any) of the query. - * LastError is cleared by Execute(), Row(), Rows(), One(), and All(). + * TableMapper maps structs to table names. Defaults to GetTableName. */ - lastError: Error + tableMapper: TableMapFunc /** - * LogFunc is used to log the SQL statement being executed. + * LogFunc logs the SQL statements being executed. Defaults to nil, meaning no logging. */ logFunc: LogFunc /** - * PerfFunc is used to log the SQL execution time. It is ignored if nil. + * PerfFunc logs the SQL execution time. Defaults to nil, meaning no performance profiling. * Deprecated: Please use QueryLogFunc and ExecLogFunc instead. */ perfFunc: PerfFunc @@ -4369,1571 +4702,1239 @@ namespace dbx { */ execLogFunc: ExecLogFunc } - interface newQuery { + /** + * Errors represents a list of errors. + */ + interface Errors extends Array{} + interface newFromDB { /** - * NewQuery creates a new Query with the given SQL statement. + * NewFromDB encapsulates an existing database connection. */ - (db: DB, executor: Executor, sql: string): (Query) + (sqlDB: sql.DB, driverName: string): (DB) } - interface Query { + interface open { /** - * SQL returns the original SQL used to create the query. - * The actual SQL (RawSQL) being executed is obtained by replacing the named - * parameter placeholders with anonymous ones. + * Open opens a database specified by a driver name and data source name (DSN). + * Note that Open does not check if DSN is specified correctly. It doesn't try to establish a DB connection either. + * Please refer to sql.Open() for more information. */ - sql(): string + (driverName: string, dsn: string): (DB) } - interface Query { + interface mustOpen { /** - * Context returns the context associated with the query. + * MustOpen opens a database and establishes a connection to it. + * Please refer to sql.Open() and sql.Ping() for more information. */ - context(): context.Context + (driverName: string, dsn: string): (DB) } - interface Query { + interface DB { /** - * WithContext associates a context with the query. + * Clone makes a shallow copy of DB. */ - withContext(ctx: context.Context): (Query) + clone(): (DB) } - interface Query { + interface DB { /** - * WithExecHook associates the provided exec hook function with the query. - * - * It is called for every Query resolver (Execute(), One(), All(), Row(), Column()), - * allowing you to implement auto fail/retry or any other additional handling. + * WithContext returns a new instance of DB associated with the given context. */ - withExecHook(fn: ExecHookFunc): (Query) + withContext(ctx: context.Context): (DB) } - interface Query { + interface DB { /** - * WithOneHook associates the provided hook function with the query, - * called on q.One(), allowing you to implement custom struct scan based - * on the One() argument and/or result. + * Context returns the context associated with the DB instance. + * It returns nil if no context is associated. */ - withOneHook(fn: OneHookFunc): (Query) + context(): context.Context } - interface Query { + interface DB { /** - * WithOneHook associates the provided hook function with the query, - * called on q.All(), allowing you to implement custom slice scan based - * on the All() argument and/or result. + * DB returns the sql.DB instance encapsulated by dbx.DB. */ - withAllHook(fn: AllHookFunc): (Query) + db(): (sql.DB) } - interface Query { + interface DB { /** - * Params returns the parameters to be bound to the SQL statement represented by this query. + * Close closes the database, releasing any open resources. + * It is rare to Close a DB, as the DB handle is meant to be + * long-lived and shared between many goroutines. */ - params(): Params + close(): void } - interface Query { + interface DB { /** - * Prepare creates a prepared statement for later queries or executions. - * Close() should be called after finishing all queries. + * Begin starts a transaction. */ - prepare(): (Query) + begin(): (Tx) } - interface Query { + interface DB { /** - * Close closes the underlying prepared statement. - * Close does nothing if the query has not been prepared before. + * BeginTx starts a transaction with the given context and transaction options. */ - close(): void + beginTx(ctx: context.Context, opts: sql.TxOptions): (Tx) } - interface Query { + interface DB { /** - * Bind sets the parameters that should be bound to the SQL statement. - * The parameter placeholders in the SQL statement are in the format of "{:ParamName}". + * Wrap encapsulates an existing transaction. */ - bind(params: Params): (Query) + wrap(sqlTx: sql.Tx): (Tx) } - interface Query { + interface DB { /** - * Execute executes the SQL statement without retrieving data. + * Transactional starts a transaction and executes the given function. + * If the function returns an error, the transaction will be rolled back. + * Otherwise, the transaction will be committed. */ - execute(): sql.Result + transactional(f: (_arg0: Tx) => void): void } - interface Query { + interface DB { /** - * One executes the SQL statement and populates the first row of the result into a struct or NullStringMap. - * Refer to Rows.ScanStruct() and Rows.ScanMap() for more details on how to specify - * the variable to be populated. - * Note that when the query has no rows in the result set, an sql.ErrNoRows will be returned. + * TransactionalContext starts a transaction and executes the given function with the given context and transaction options. + * If the function returns an error, the transaction will be rolled back. + * Otherwise, the transaction will be committed. */ - one(a: { - }): void + transactionalContext(ctx: context.Context, opts: sql.TxOptions, f: (_arg0: Tx) => void): void } - interface Query { + interface DB { /** - * All executes the SQL statement and populates all the resulting rows into a slice of struct or NullStringMap. - * The slice must be given as a pointer. Each slice element must be either a struct or a NullStringMap. - * Refer to Rows.ScanStruct() and Rows.ScanMap() for more details on how each slice element can be. - * If the query returns no row, the slice will be an empty slice (not nil). + * DriverName returns the name of the DB driver. */ - all(slice: { - }): void + driverName(): string } - interface Query { + interface DB { /** - * Row executes the SQL statement and populates the first row of the result into a list of variables. - * Note that the number of the variables should match to that of the columns in the query result. - * Note that when the query has no rows in the result set, an sql.ErrNoRows will be returned. + * QuoteTableName quotes the given table name appropriately. + * If the table name contains DB schema prefix, it will be handled accordingly. + * This method will do nothing if the table name is already quoted or if it contains parenthesis. */ - row(...a: { - }[]): void + quoteTableName(s: string): string } - interface Query { + interface DB { /** - * Column executes the SQL statement and populates the first column of the result into a slice. - * Note that the parameter must be a pointer to a slice. + * QuoteColumnName quotes the given column name appropriately. + * If the table name contains table name prefix, it will be handled accordingly. + * This method will do nothing if the column name is already quoted or if it contains parenthesis. */ - column(a: { - }): void + quoteColumnName(s: string): string } - interface Query { + interface Errors { /** - * Rows executes the SQL statement and returns a Rows object to allow retrieving data row by row. + * Error returns the error string of Errors. */ - rows(): (Rows) + error(): string } /** - * QueryBuilder builds different clauses for a SELECT SQL statement. + * Expression represents a DB expression that can be embedded in a SQL statement. */ - interface QueryBuilder { + interface Expression { [key:string]: any; /** - * BuildSelect generates a SELECT clause from the given selected column names. - */ - buildSelect(cols: Array, distinct: boolean, option: string): string - /** - * BuildFrom generates a FROM clause from the given tables. + * Build converts an expression into a SQL fragment. + * If the expression contains binding parameters, they will be added to the given Params. */ - buildFrom(tables: Array): string + build(_arg0: DB, _arg1: Params): string + } + /** + * HashExp represents a hash expression. + * + * A hash expression is a map whose keys are DB column names which need to be filtered according + * to the corresponding values. For example, HashExp{"level": 2, "dept": 10} will generate + * the SQL: "level"=2 AND "dept"=10. + * + * HashExp also handles nil values and slice values. For example, HashExp{"level": []interface{}{1, 2}, "dept": nil} + * will generate: "level" IN (1, 2) AND "dept" IS NULL. + */ + interface HashExp extends _TygojaDict{} + interface newExp { /** - * BuildGroupBy generates a GROUP BY clause from the given group-by columns. + * NewExp generates an expression with the specified SQL fragment and the optional binding parameters. */ - buildGroupBy(cols: Array): string + (e: string, ...params: Params[]): Expression + } + interface not { /** - * BuildJoin generates a JOIN clause from the given join information. + * Not generates a NOT expression which prefixes "NOT" to the specified expression. */ - buildJoin(_arg0: Array, _arg1: Params): string + (e: Expression): Expression + } + interface and { /** - * BuildWhere generates a WHERE clause from the given expression. + * And generates an AND expression which concatenates the given expressions with "AND". */ - buildWhere(_arg0: Expression, _arg1: Params): string + (...exps: Expression[]): Expression + } + interface or { /** - * BuildHaving generates a HAVING clause from the given expression. + * Or generates an OR expression which concatenates the given expressions with "OR". */ - buildHaving(_arg0: Expression, _arg1: Params): string + (...exps: Expression[]): Expression + } + interface _in { /** - * BuildOrderByAndLimit generates the ORDER BY and LIMIT clauses. + * In generates an IN expression for the specified column and the list of allowed values. + * If values is empty, a SQL "0=1" will be generated which represents a false expression. */ - buildOrderByAndLimit(_arg0: string, _arg1: Array, _arg2: number, _arg3: number): string + (col: string, ...values: { + }[]): Expression + } + interface notIn { /** - * BuildUnion generates a UNION clause from the given union information. + * NotIn generates an NOT IN expression for the specified column and the list of disallowed values. + * If values is empty, an empty string will be returned indicating a true expression. */ - buildUnion(_arg0: Array, _arg1: Params): string + (col: string, ...values: { + }[]): Expression + } + interface like { /** - * CombineUnion combines the nonempty unionClause with the provided sql string. + * Like generates a LIKE expression for the specified column and the possible strings that the column should be like. + * If multiple values are present, the column should be like *all* of them. For example, Like("name", "key", "word") + * will generate a SQL expression: "name" LIKE "%key%" AND "name" LIKE "%word%". * - * The unionClause is expected to be the result of BuildUnion. - * If the unionClause is an empty string it returns the sql argument unmodified. + * By default, each value will be surrounded by "%" to enable partial matching. If a value contains special characters + * such as "%", "\", "_", they will also be properly escaped. * - * This method exists as a workaround to minimize breaking changes - * and to allow different SQL builders to specify for example whether - * they support parenthesis around the UNION SQL queries - * (SQLite for example will throw a SyntaxError if the UNION parts are wrapped in parenthesis). - */ - combineUnion(sql: string, unionClause: string): string - } - /** - * BaseQueryBuilder provides a basic implementation of QueryBuilder. - */ - interface BaseQueryBuilder { - } - interface newBaseQueryBuilder { - /** - * NewBaseQueryBuilder creates a new BaseQueryBuilder instance. + * You may call Escape() and/or Match() to change the default behavior. For example, Like("name", "key").Match(false, true) + * generates "name" LIKE "key%". */ - (db: DB): (BaseQueryBuilder) + (col: string, ...values: string[]): (LikeExp) } - interface BaseQueryBuilder { + interface notLike { /** - * DB returns the DB instance associated with the query builder. + * NotLike generates a NOT LIKE expression. + * For example, NotLike("name", "key", "word") will generate a SQL expression: + * "name" NOT LIKE "%key%" AND "name" NOT LIKE "%word%". Please see Like() for more details. */ - db(): (DB) + (col: string, ...values: string[]): (LikeExp) } - interface BaseQueryBuilder { + interface orLike { /** - * BuildSelect generates a SELECT clause from the given selected column names. + * OrLike generates an OR LIKE expression. + * This is similar to Like() except that the column should be like one of the possible values. + * For example, OrLike("name", "key", "word") will generate a SQL expression: + * "name" LIKE "%key%" OR "name" LIKE "%word%". Please see Like() for more details. */ - buildSelect(cols: Array, distinct: boolean, option: string): string + (col: string, ...values: string[]): (LikeExp) } - interface BaseQueryBuilder { + interface orNotLike { /** - * BuildFrom generates a FROM clause from the given tables. + * OrNotLike generates an OR NOT LIKE expression. + * For example, OrNotLike("name", "key", "word") will generate a SQL expression: + * "name" NOT LIKE "%key%" OR "name" NOT LIKE "%word%". Please see Like() for more details. */ - buildFrom(tables: Array): string + (col: string, ...values: string[]): (LikeExp) } - interface BaseQueryBuilder { + interface exists { /** - * BuildJoin generates a JOIN clause from the given join information. + * Exists generates an EXISTS expression by prefixing "EXISTS" to the given expression. */ - buildJoin(joins: Array, params: Params): string + (exp: Expression): Expression } - interface BaseQueryBuilder { + interface notExists { /** - * BuildWhere generates a WHERE clause from the given expression. + * NotExists generates an EXISTS expression by prefixing "NOT EXISTS" to the given expression. */ - buildWhere(e: Expression, params: Params): string + (exp: Expression): Expression } - interface BaseQueryBuilder { + interface between { /** - * BuildHaving generates a HAVING clause from the given expression. + * Between generates a BETWEEN expression. + * For example, Between("age", 10, 30) generates: "age" BETWEEN 10 AND 30 */ - buildHaving(e: Expression, params: Params): string + (col: string, from: { + }, to: { + }): Expression } - interface BaseQueryBuilder { + interface notBetween { /** - * BuildGroupBy generates a GROUP BY clause from the given group-by columns. + * NotBetween generates a NOT BETWEEN expression. + * For example, NotBetween("age", 10, 30) generates: "age" NOT BETWEEN 10 AND 30 */ - buildGroupBy(cols: Array): string + (col: string, from: { + }, to: { + }): Expression } - interface BaseQueryBuilder { - /** - * BuildOrderByAndLimit generates the ORDER BY and LIMIT clauses. - */ - buildOrderByAndLimit(sql: string, cols: Array, limit: number, offset: number): string + /** + * Exp represents an expression with a SQL fragment and a list of optional binding parameters. + */ + interface Exp { } - interface BaseQueryBuilder { + interface Exp { /** - * BuildUnion generates a UNION clause from the given union information. + * Build converts an expression into a SQL fragment. */ - buildUnion(unions: Array, params: Params): string + build(db: DB, params: Params): string } - interface BaseQueryBuilder { + interface HashExp { /** - * CombineUnion combines the nonempty unionClause with the provided sql string. - * - * The unionClause is expected to be the result of BuildUnion. - * If the unionClause is an empty string it returns the sql argument unmodified. - * - * This method exists as a workaround to minimize breaking changes - * and to allow different SQL builders to specify for example whether - * they support parenthesis around the UNION SQL queries - * (SQLite for example will throw a SyntaxError if the UNION parts are wrapped in parenthesis). + * Build converts an expression into a SQL fragment. */ - combineUnion(sql: string, unionClause: string): string + build(db: DB, params: Params): string } - interface BaseQueryBuilder { - /** - * BuildOrderBy generates the ORDER BY clause. - */ - buildOrderBy(cols: Array): string + /** + * NotExp represents an expression that should prefix "NOT" to a specified expression. + */ + interface NotExp { } - interface BaseQueryBuilder { + interface NotExp { /** - * BuildLimit generates the LIMIT clause. + * Build converts an expression into a SQL fragment. */ - buildLimit(limit: number, offset: number): string + build(db: DB, params: Params): string } /** - * VarTypeError indicates a variable type error when trying to populating a variable with DB result. + * AndOrExp represents an expression that concatenates multiple expressions using either "AND" or "OR". */ - interface VarTypeError extends String{} - interface VarTypeError { + interface AndOrExp { + } + interface AndOrExp { /** - * Error returns the error message. + * Build converts an expression into a SQL fragment. */ - error(): string + build(db: DB, params: Params): string } /** - * NullStringMap is a map of sql.NullString that can be used to hold DB query result. - * The map keys correspond to the DB column names, while the map values are their corresponding column values. + * InExp represents an "IN" or "NOT IN" expression. */ - interface NullStringMap extends _TygojaDict{} + interface InExp { + } + interface InExp { + /** + * Build converts an expression into a SQL fragment. + */ + build(db: DB, params: Params): string + } /** - * Rows enhances sql.Rows by providing additional data query methods. - * Rows can be obtained by calling Query.Rows(). It is mainly used to populate data row by row. + * LikeExp represents a variant of LIKE expressions. */ - type _sMYwxsv = sql.Rows - interface Rows extends _sMYwxsv { + interface LikeExp { + /** + * Like stores the LIKE operator. It can be "LIKE", "NOT LIKE". + * It may also be customized as something like "ILIKE". + */ + like: string } - interface Rows { + interface LikeExp { /** - * ScanMap populates the current row of data into a NullStringMap. - * Note that the NullStringMap must not be nil, or it will panic. - * The NullStringMap will be populated using column names as keys and their values as - * the corresponding element values. + * Escape specifies how a LIKE expression should be escaped. + * Each string at position 2i represents a special character and the string at position 2i+1 is + * the corresponding escaped version. */ - scanMap(a: NullStringMap): void + escape(...chars: string[]): (LikeExp) } - interface Rows { + interface LikeExp { /** - * ScanStruct populates the current row of data into a struct. - * The struct must be given as a pointer. - * - * ScanStruct associates struct fields with DB table columns through a field mapping function. - * It populates a struct field with the data of its associated column. - * Note that only exported struct fields will be populated. - * - * By default, DefaultFieldMapFunc() is used to map struct fields to table columns. - * This function separates each word in a field name with a underscore and turns every letter into lower case. - * For example, "LastName" is mapped to "last_name", "MyID" is mapped to "my_id", and so on. - * To change the default behavior, set DB.FieldMapper with your custom mapping function. - * You may also set Query.FieldMapper to change the behavior for particular queries. + * Match specifies whether to do wildcard matching on the left and/or right of given strings. */ - scanStruct(a: { - }): void + match(left: boolean, right: boolean): (LikeExp) + } + interface LikeExp { + /** + * Build converts an expression into a SQL fragment. + */ + build(db: DB, params: Params): string } /** - * BuildHookFunc defines a callback function that is executed on Query creation. + * ExistsExp represents an EXISTS or NOT EXISTS expression. */ - interface BuildHookFunc {(q: Query): void } + interface ExistsExp { + } + interface ExistsExp { + /** + * Build converts an expression into a SQL fragment. + */ + build(db: DB, params: Params): string + } /** - * SelectQuery represents a DB-agnostic SELECT query. - * It can be built into a DB-specific query by calling the Build() method. + * BetweenExp represents a BETWEEN or a NOT BETWEEN expression. */ - interface SelectQuery { + interface BetweenExp { + } + interface BetweenExp { /** - * FieldMapper maps struct field names to DB column names. + * Build converts an expression into a SQL fragment. */ - fieldMapper: FieldMapFunc + build(db: DB, params: Params): string + } + interface enclose { /** - * TableMapper maps structs to DB table names. + * Enclose surrounds the provided nonempty expression with parenthesis "()". */ - tableMapper: TableMapFunc + (exp: Expression): Expression } /** - * JoinInfo contains the specification for a JOIN clause. + * EncloseExp represents a parenthesis enclosed expression. */ - interface JoinInfo { - join: string - table: string - on: Expression + interface EncloseExp { + } + interface EncloseExp { + /** + * Build converts an expression into a SQL fragment. + */ + build(db: DB, params: Params): string } /** - * UnionInfo contains the specification for a UNION clause. + * TableModel is the interface that should be implemented by models which have unconventional table names. */ - interface UnionInfo { - all: boolean - query?: Query + interface TableModel { + [key:string]: any; + tableName(): string } - interface newSelectQuery { - /** - * NewSelectQuery creates a new SelectQuery instance. - */ - (builder: Builder, db: DB): (SelectQuery) + /** + * ModelQuery represents a query associated with a struct model. + */ + interface ModelQuery { } - interface SelectQuery { - /** - * WithBuildHook runs the provided hook function with the query created on Build(). - */ - withBuildHook(fn: BuildHookFunc): (SelectQuery) + interface newModelQuery { + (model: { + }, fieldMapFunc: FieldMapFunc, db: DB, builder: Builder): (ModelQuery) } - interface SelectQuery { + interface ModelQuery { /** * Context returns the context associated with the query. */ context(): context.Context } - interface SelectQuery { + interface ModelQuery { /** * WithContext associates a context with the query. */ - withContext(ctx: context.Context): (SelectQuery) + withContext(ctx: context.Context): (ModelQuery) } - interface SelectQuery { + interface ModelQuery { /** - * PreFragment sets SQL fragment that should be prepended before the select query (e.g. WITH clause). + * Exclude excludes the specified struct fields from being inserted/updated into the DB table. */ - preFragment(fragment: string): (SelectQuery) + exclude(...attrs: string[]): (ModelQuery) } - interface SelectQuery { + interface ModelQuery { /** - * PostFragment sets SQL fragment that should be appended at the end of the main select query. + * Insert inserts a row in the table using the struct model associated with this query. * - * If there is "UNION"/"UNION ALL" clause then the extra UNION queries - * are appended after the PostFragment. + * By default, it inserts *all* public fields into the table, including those nil or empty ones. + * You may pass a list of the fields to this method to indicate that only those fields should be inserted. + * You may also call Exclude to exclude some fields from being inserted. + * + * If a model has an empty primary key, it is considered auto-incremental and the corresponding struct + * field will be filled with the generated primary key value after a successful insertion. */ - postFragment(fragment: string): (SelectQuery) + insert(...attrs: string[]): void } - interface SelectQuery { + interface ModelQuery { /** - * Select specifies the columns to be selected. - * Column names will be automatically quoted. + * Update updates a row in the table using the struct model associated with this query. + * The row being updated has the same primary key as specified by the model. + * + * By default, it updates *all* public fields in the table, including those nil or empty ones. + * You may pass a list of the fields to this method to indicate that only those fields should be updated. + * You may also call Exclude to exclude some fields from being updated. */ - select(...cols: string[]): (SelectQuery) + update(...attrs: string[]): void } - interface SelectQuery { + interface ModelQuery { /** - * AndSelect adds additional columns to be selected. - * Column names will be automatically quoted. + * Delete deletes a row in the table using the primary key specified by the struct model associated with this query. */ - andSelect(...cols: string[]): (SelectQuery) + delete(): void } - interface SelectQuery { + /** + * ExecHookFunc executes before op allowing custom handling like auto fail/retry. + */ + interface ExecHookFunc {(q: Query, op: () => void): void } + /** + * OneHookFunc executes right before the query populate the row result from One() call (aka. op). + */ + interface OneHookFunc {(q: Query, a: { + }, op: (b: { + }) => void): void } + /** + * AllHookFunc executes right before the query populate the row result from All() call (aka. op). + */ + interface AllHookFunc {(q: Query, sliceA: { + }, op: (sliceB: { + }) => void): void } + /** + * Params represents a list of parameter values to be bound to a SQL statement. + * The map keys are the parameter names while the map values are the corresponding parameter values. + */ + interface Params extends _TygojaDict{} + /** + * Executor prepares, executes, or queries a SQL statement. + */ + interface Executor { + [key:string]: any; /** - * Distinct specifies whether to select columns distinctively. - * By default, distinct is false. + * Exec executes a SQL statement */ - distinct(v: boolean): (SelectQuery) - } - interface SelectQuery { + exec(query: string, ...args: { + }[]): sql.Result /** - * SelectOption specifies additional option that should be append to "SELECT". + * ExecContext executes a SQL statement with the given context */ - selectOption(option: string): (SelectQuery) - } - interface SelectQuery { + execContext(ctx: context.Context, query: string, ...args: { + }[]): sql.Result /** - * From specifies which tables to select from. - * Table names will be automatically quoted. + * Query queries a SQL statement */ - from(...tables: string[]): (SelectQuery) - } - interface SelectQuery { + query(query: string, ...args: { + }[]): (sql.Rows) /** - * Where specifies the WHERE condition. + * QueryContext queries a SQL statement with the given context */ - where(e: Expression): (SelectQuery) - } - interface SelectQuery { + queryContext(ctx: context.Context, query: string, ...args: { + }[]): (sql.Rows) /** - * AndWhere concatenates a new WHERE condition with the existing one (if any) using "AND". + * Prepare creates a prepared statement */ - andWhere(e: Expression): (SelectQuery) + prepare(query: string): (sql.Stmt) } - interface SelectQuery { + /** + * Query represents a SQL statement to be executed. + */ + interface Query { /** - * OrWhere concatenates a new WHERE condition with the existing one (if any) using "OR". + * FieldMapper maps struct field names to DB column names. */ - orWhere(e: Expression): (SelectQuery) - } - interface SelectQuery { + fieldMapper: FieldMapFunc /** - * Join specifies a JOIN clause. - * The "typ" parameter specifies the JOIN type (e.g. "INNER JOIN", "LEFT JOIN"). + * LastError contains the last error (if any) of the query. + * LastError is cleared by Execute(), Row(), Rows(), One(), and All(). */ - join(typ: string, table: string, on: Expression): (SelectQuery) - } - interface SelectQuery { + lastError: Error /** - * InnerJoin specifies an INNER JOIN clause. - * This is a shortcut method for Join. - */ - innerJoin(table: string, on: Expression): (SelectQuery) - } - interface SelectQuery { - /** - * LeftJoin specifies a LEFT JOIN clause. - * This is a shortcut method for Join. + * LogFunc is used to log the SQL statement being executed. */ - leftJoin(table: string, on: Expression): (SelectQuery) - } - interface SelectQuery { + logFunc: LogFunc /** - * RightJoin specifies a RIGHT JOIN clause. - * This is a shortcut method for Join. + * PerfFunc is used to log the SQL execution time. It is ignored if nil. + * Deprecated: Please use QueryLogFunc and ExecLogFunc instead. */ - rightJoin(table: string, on: Expression): (SelectQuery) - } - interface SelectQuery { + perfFunc: PerfFunc /** - * OrderBy specifies the ORDER BY clause. - * Column names will be properly quoted. A column name can contain "ASC" or "DESC" to indicate its ordering direction. + * QueryLogFunc is called each time when performing a SQL query that returns data. */ - orderBy(...cols: string[]): (SelectQuery) - } - interface SelectQuery { + queryLogFunc: QueryLogFunc /** - * AndOrderBy appends additional columns to the existing ORDER BY clause. - * Column names will be properly quoted. A column name can contain "ASC" or "DESC" to indicate its ordering direction. + * ExecLogFunc is called each time when a SQL statement is executed. */ - andOrderBy(...cols: string[]): (SelectQuery) + execLogFunc: ExecLogFunc } - interface SelectQuery { + interface newQuery { /** - * GroupBy specifies the GROUP BY clause. - * Column names will be properly quoted. + * NewQuery creates a new Query with the given SQL statement. */ - groupBy(...cols: string[]): (SelectQuery) + (db: DB, executor: Executor, sql: string): (Query) } - interface SelectQuery { + interface Query { /** - * AndGroupBy appends additional columns to the existing GROUP BY clause. - * Column names will be properly quoted. + * SQL returns the original SQL used to create the query. + * The actual SQL (RawSQL) being executed is obtained by replacing the named + * parameter placeholders with anonymous ones. */ - andGroupBy(...cols: string[]): (SelectQuery) + sql(): string } - interface SelectQuery { + interface Query { /** - * Having specifies the HAVING clause. + * Context returns the context associated with the query. */ - having(e: Expression): (SelectQuery) + context(): context.Context } - interface SelectQuery { + interface Query { /** - * AndHaving concatenates a new HAVING condition with the existing one (if any) using "AND". + * WithContext associates a context with the query. */ - andHaving(e: Expression): (SelectQuery) + withContext(ctx: context.Context): (Query) } - interface SelectQuery { + interface Query { /** - * OrHaving concatenates a new HAVING condition with the existing one (if any) using "OR". + * WithExecHook associates the provided exec hook function with the query. + * + * It is called for every Query resolver (Execute(), One(), All(), Row(), Column()), + * allowing you to implement auto fail/retry or any other additional handling. */ - orHaving(e: Expression): (SelectQuery) + withExecHook(fn: ExecHookFunc): (Query) } - interface SelectQuery { + interface Query { /** - * Union specifies a UNION clause. + * WithOneHook associates the provided hook function with the query, + * called on q.One(), allowing you to implement custom struct scan based + * on the One() argument and/or result. */ - union(q: Query): (SelectQuery) + withOneHook(fn: OneHookFunc): (Query) } - interface SelectQuery { + interface Query { /** - * UnionAll specifies a UNION ALL clause. + * WithOneHook associates the provided hook function with the query, + * called on q.All(), allowing you to implement custom slice scan based + * on the All() argument and/or result. */ - unionAll(q: Query): (SelectQuery) + withAllHook(fn: AllHookFunc): (Query) } - interface SelectQuery { + interface Query { /** - * Limit specifies the LIMIT clause. - * A negative limit means no limit. + * Params returns the parameters to be bound to the SQL statement represented by this query. */ - limit(limit: number): (SelectQuery) + params(): Params } - interface SelectQuery { + interface Query { /** - * Offset specifies the OFFSET clause. - * A negative offset means no offset. + * Prepare creates a prepared statement for later queries or executions. + * Close() should be called after finishing all queries. */ - offset(offset: number): (SelectQuery) + prepare(): (Query) } - interface SelectQuery { + interface Query { /** - * Bind specifies the parameter values to be bound to the query. + * Close closes the underlying prepared statement. + * Close does nothing if the query has not been prepared before. */ - bind(params: Params): (SelectQuery) + close(): void } - interface SelectQuery { + interface Query { /** - * AndBind appends additional parameters to be bound to the query. + * Bind sets the parameters that should be bound to the SQL statement. + * The parameter placeholders in the SQL statement are in the format of "{:ParamName}". */ - andBind(params: Params): (SelectQuery) + bind(params: Params): (Query) } - interface SelectQuery { + interface Query { /** - * Build builds the SELECT query and returns an executable Query object. + * Execute executes the SQL statement without retrieving data. */ - build(): (Query) + execute(): sql.Result } - interface SelectQuery { + interface Query { /** - * One executes the SELECT query and populates the first row of the result into the specified variable. - * - * If the query does not specify a "from" clause, the method will try to infer the name of the table - * to be selected from by calling getTableName() which will return either the variable type name - * or the TableName() method if the variable implements the TableModel interface. - * + * One executes the SQL statement and populates the first row of the result into a struct or NullStringMap. + * Refer to Rows.ScanStruct() and Rows.ScanMap() for more details on how to specify + * the variable to be populated. * Note that when the query has no rows in the result set, an sql.ErrNoRows will be returned. */ one(a: { }): void } - interface SelectQuery { - /** - * Model selects the row with the specified primary key and populates the model with the row data. - * - * The model variable should be a pointer to a struct. If the query does not specify a "from" clause, - * it will use the model struct to determine which table to select data from. It will also use the model - * to infer the name of the primary key column. Only simple primary key is supported. For composite primary keys, - * please use Where() to specify the filtering condition. - */ - model(pk: { - }, model: { - }): void - } - interface SelectQuery { + interface Query { /** - * All executes the SELECT query and populates all rows of the result into a slice. - * - * Note that the slice must be passed in as a pointer. - * - * If the query does not specify a "from" clause, the method will try to infer the name of the table - * to be selected from by calling getTableName() which will return either the type name of the slice elements - * or the TableName() method if the slice element implements the TableModel interface. + * All executes the SQL statement and populates all the resulting rows into a slice of struct or NullStringMap. + * The slice must be given as a pointer. Each slice element must be either a struct or a NullStringMap. + * Refer to Rows.ScanStruct() and Rows.ScanMap() for more details on how each slice element can be. + * If the query returns no row, the slice will be an empty slice (not nil). */ all(slice: { }): void } - interface SelectQuery { - /** - * Rows builds and executes the SELECT query and returns a Rows object for data retrieval purpose. - * This is a shortcut to SelectQuery.Build().Rows() - */ - rows(): (Rows) - } - interface SelectQuery { + interface Query { /** - * Row builds and executes the SELECT query and populates the first row of the result into the specified variables. - * This is a shortcut to SelectQuery.Build().Row() + * Row executes the SQL statement and populates the first row of the result into a list of variables. + * Note that the number of the variables should match to that of the columns in the query result. + * Note that when the query has no rows in the result set, an sql.ErrNoRows will be returned. */ row(...a: { }[]): void } - interface SelectQuery { + interface Query { /** - * Column builds and executes the SELECT statement and populates the first column of the result into a slice. + * Column executes the SQL statement and populates the first column of the result into a slice. * Note that the parameter must be a pointer to a slice. - * This is a shortcut to SelectQuery.Build().Column() */ column(a: { }): void } - /** - * QueryInfo represents a debug/info struct with exported SelectQuery fields. - */ - interface QueryInfo { - preFragment: string - postFragment: string - builder: Builder - selects: Array - distinct: boolean - selectOption: string - from: Array - where: Expression - join: Array - orderBy: Array - groupBy: Array - having: Expression - union: Array - limit: number - offset: number - params: Params - context: context.Context - buildHook: BuildHookFunc - } - interface SelectQuery { + interface Query { /** - * Info exports common SelectQuery fields allowing to inspect the - * current select query options. + * Rows executes the SQL statement and returns a Rows object to allow retrieving data row by row. */ - info(): (QueryInfo) - } - /** - * FieldMapFunc converts a struct field name into a DB column name. - */ - interface FieldMapFunc {(_arg0: string): string } - /** - * TableMapFunc converts a sample struct into a DB table name. - */ - interface TableMapFunc {(a: { - }): string } - interface structInfo { - } - type _sOzUeAW = structInfo - interface structValue extends _sOzUeAW { - } - interface fieldInfo { - } - interface structInfoMapKey { + rows(): (Rows) } /** - * PostScanner is an optional interface used by ScanStruct. + * QueryBuilder builds different clauses for a SELECT SQL statement. */ - interface PostScanner { + interface QueryBuilder { [key:string]: any; /** - * PostScan executes right after the struct has been populated - * with the DB values, allowing you to further normalize or validate - * the loaded data. + * BuildSelect generates a SELECT clause from the given selected column names. */ - postScan(): void - } - interface defaultFieldMapFunc { + buildSelect(cols: Array, distinct: boolean, option: string): string /** - * DefaultFieldMapFunc maps a field name to a DB column name. - * The mapping rule set by this method is that words in a field name will be separated by underscores - * and the name will be turned into lower case. For example, "FirstName" maps to "first_name", and "MyID" becomes "my_id". - * See DB.FieldMapper for more details. + * BuildFrom generates a FROM clause from the given tables. */ - (f: string): string - } - interface getTableName { + buildFrom(tables: Array): string /** - * GetTableName implements the default way of determining the table name corresponding to the given model struct - * or slice of structs. To get the actual table name for a model, you should use DB.TableMapFunc() instead. - * Do not call this method in a model's TableName() method because it will cause infinite loop. + * BuildGroupBy generates a GROUP BY clause from the given group-by columns. */ - (a: { - }): string - } - /** - * Tx enhances sql.Tx with additional querying methods. - */ - type _sSyBQus = Builder - interface Tx extends _sSyBQus { - } - interface Tx { + buildGroupBy(cols: Array): string /** - * Commit commits the transaction. + * BuildJoin generates a JOIN clause from the given join information. */ - commit(): void - } - interface Tx { + buildJoin(_arg0: Array, _arg1: Params): string /** - * Rollback aborts the transaction. + * BuildWhere generates a WHERE clause from the given expression. */ - rollback(): void - } -} - -/** - * Package filepath implements utility routines for manipulating filename paths - * in a way compatible with the target operating system-defined file paths. - * - * The filepath package uses either forward slashes or backslashes, - * depending on the operating system. To process paths such as URLs - * that always use forward slashes regardless of the operating - * system, see the [path] package. - */ -namespace filepath { - interface match { + buildWhere(_arg0: Expression, _arg1: Params): string /** - * Match reports whether name matches the shell file name pattern. - * The pattern syntax is: - * - * ``` - * pattern: - * { term } - * term: - * '*' matches any sequence of non-Separator characters - * '?' matches any single non-Separator character - * '[' [ '^' ] { character-range } ']' - * character class (must be non-empty) - * c matches character c (c != '*', '?', '\\', '[') - * '\\' c matches character c (except on Windows) - * - * character-range: - * c matches character c (c != '\\', '-', ']') - * '\\' c matches character c (except on Windows) - * lo '-' hi matches character c for lo <= c <= hi - * ``` - * - * Path segments in the pattern must be separated by [Separator]. - * - * Match requires pattern to match all of name, not just a substring. - * The only possible returned error is [ErrBadPattern], when pattern - * is malformed. - * - * On Windows, escaping is disabled. Instead, '\\' is treated as - * path separator. + * BuildHaving generates a HAVING clause from the given expression. */ - (pattern: string, name: string): boolean - } - interface glob { + buildHaving(_arg0: Expression, _arg1: Params): string /** - * Glob returns the names of all files matching pattern or nil - * if there is no matching file. The syntax of patterns is the same - * as in [Match]. The pattern may describe hierarchical names such as - * /usr/*\/bin/ed (assuming the [Separator] is '/'). - * - * Glob ignores file system errors such as I/O errors reading directories. - * The only possible returned error is [ErrBadPattern], when pattern - * is malformed. + * BuildOrderByAndLimit generates the ORDER BY and LIMIT clauses. */ - (pattern: string): Array - } - interface clean { + buildOrderByAndLimit(_arg0: string, _arg1: Array, _arg2: number, _arg3: number): string /** - * Clean returns the shortest path name equivalent to path - * by purely lexical processing. It applies the following rules - * iteratively until no further processing can be done: - * - * 1. Replace multiple [Separator] elements with a single one. - * 2. Eliminate each . path name element (the current directory). - * 3. Eliminate each inner .. path name element (the parent directory) - * ``` - * along with the non-.. element that precedes it. - * ``` - * 4. Eliminate .. elements that begin a rooted path: - * ``` - * that is, replace "/.." by "/" at the beginning of a path, - * assuming Separator is '/'. - * ``` - * - * The returned path ends in a slash only if it represents a root directory, - * such as "/" on Unix or `C:\` on Windows. - * - * Finally, any occurrences of slash are replaced by Separator. - * - * If the result of this process is an empty string, Clean - * returns the string ".". - * - * On Windows, Clean does not modify the volume name other than to replace - * occurrences of "/" with `\`. - * For example, Clean("//host/share/../x") returns `\\host\share\x`. - * - * See also Rob Pike, “Lexical File Names in Plan 9 or - * Getting Dot-Dot Right,” - * https://9p.io/sys/doc/lexnames.html + * BuildUnion generates a UNION clause from the given union information. */ - (path: string): string - } - interface isLocal { + buildUnion(_arg0: Array, _arg1: Params): string /** - * IsLocal reports whether path, using lexical analysis only, has all of these properties: - * - * ``` - * - is within the subtree rooted at the directory in which path is evaluated - * - is not an absolute path - * - is not empty - * - on Windows, is not a reserved name such as "NUL" - * ``` + * CombineUnion combines the nonempty unionClause with the provided sql string. * - * If IsLocal(path) returns true, then - * Join(base, path) will always produce a path contained within base and - * Clean(path) will always produce an unrooted path with no ".." path elements. + * The unionClause is expected to be the result of BuildUnion. + * If the unionClause is an empty string it returns the sql argument unmodified. * - * IsLocal is a purely lexical operation. - * In particular, it does not account for the effect of any symbolic links - * that may exist in the filesystem. + * This method exists as a workaround to minimize breaking changes + * and to allow different SQL builders to specify for example whether + * they support parenthesis around the UNION SQL queries + * (SQLite for example will throw a SyntaxError if the UNION parts are wrapped in parenthesis). */ - (path: string): boolean + combineUnion(sql: string, unionClause: string): string } - interface localize { + /** + * BaseQueryBuilder provides a basic implementation of QueryBuilder. + */ + interface BaseQueryBuilder { + } + interface newBaseQueryBuilder { /** - * Localize converts a slash-separated path into an operating system path. - * The input path must be a valid path as reported by [io/fs.ValidPath]. - * - * Localize returns an error if the path cannot be represented by the operating system. - * For example, the path a\b is rejected on Windows, on which \ is a separator - * character and cannot be part of a filename. - * - * The path returned by Localize will always be local, as reported by IsLocal. + * NewBaseQueryBuilder creates a new BaseQueryBuilder instance. */ - (path: string): string + (db: DB): (BaseQueryBuilder) } - interface toSlash { + interface BaseQueryBuilder { /** - * ToSlash returns the result of replacing each separator character - * in path with a slash ('/') character. Multiple separators are - * replaced by multiple slashes. + * DB returns the DB instance associated with the query builder. */ - (path: string): string + db(): (DB) } - interface fromSlash { + interface BaseQueryBuilder { /** - * FromSlash returns the result of replacing each slash ('/') character - * in path with a separator character. Multiple slashes are replaced - * by multiple separators. - * - * See also the Localize function, which converts a slash-separated path - * as used by the io/fs package to an operating system path. + * BuildSelect generates a SELECT clause from the given selected column names. */ - (path: string): string + buildSelect(cols: Array, distinct: boolean, option: string): string } - interface splitList { + interface BaseQueryBuilder { /** - * SplitList splits a list of paths joined by the OS-specific [ListSeparator], - * usually found in PATH or GOPATH environment variables. - * Unlike strings.Split, SplitList returns an empty slice when passed an empty - * string. + * BuildFrom generates a FROM clause from the given tables. */ - (path: string): Array + buildFrom(tables: Array): string } - interface split { + interface BaseQueryBuilder { /** - * Split splits path immediately following the final [Separator], - * separating it into a directory and file name component. - * If there is no Separator in path, Split returns an empty dir - * and file set to path. - * The returned values have the property that path = dir+file. + * BuildJoin generates a JOIN clause from the given join information. */ - (path: string): [string, string] + buildJoin(joins: Array, params: Params): string } - interface join { + interface BaseQueryBuilder { /** - * Join joins any number of path elements into a single path, - * separating them with an OS specific [Separator]. Empty elements - * are ignored. The result is Cleaned. However, if the argument - * list is empty or all its elements are empty, Join returns - * an empty string. - * On Windows, the result will only be a UNC path if the first - * non-empty element is a UNC path. + * BuildWhere generates a WHERE clause from the given expression. */ - (...elem: string[]): string + buildWhere(e: Expression, params: Params): string } - interface ext { + interface BaseQueryBuilder { /** - * Ext returns the file name extension used by path. - * The extension is the suffix beginning at the final dot - * in the final element of path; it is empty if there is - * no dot. + * BuildHaving generates a HAVING clause from the given expression. */ - (path: string): string + buildHaving(e: Expression, params: Params): string } - interface evalSymlinks { + interface BaseQueryBuilder { /** - * EvalSymlinks returns the path name after the evaluation of any symbolic - * links. - * If path is relative the result will be relative to the current directory, - * unless one of the components is an absolute symbolic link. - * EvalSymlinks calls [Clean] on the result. + * BuildGroupBy generates a GROUP BY clause from the given group-by columns. */ - (path: string): string + buildGroupBy(cols: Array): string } - interface isAbs { + interface BaseQueryBuilder { /** - * IsAbs reports whether the path is absolute. + * BuildOrderByAndLimit generates the ORDER BY and LIMIT clauses. */ - (path: string): boolean + buildOrderByAndLimit(sql: string, cols: Array, limit: number, offset: number): string } - interface abs { + interface BaseQueryBuilder { /** - * Abs returns an absolute representation of path. - * If the path is not absolute it will be joined with the current - * working directory to turn it into an absolute path. The absolute - * path name for a given file is not guaranteed to be unique. - * Abs calls [Clean] on the result. + * BuildUnion generates a UNION clause from the given union information. */ - (path: string): string + buildUnion(unions: Array, params: Params): string } - interface rel { + interface BaseQueryBuilder { /** - * Rel returns a relative path that is lexically equivalent to targPath when - * joined to basePath with an intervening separator. That is, - * [Join](basePath, Rel(basePath, targPath)) is equivalent to targPath itself. + * CombineUnion combines the nonempty unionClause with the provided sql string. * - * The returned path will always be relative to basePath, even if basePath and - * targPath share no elements. Rel calls [Clean] on the result. + * The unionClause is expected to be the result of BuildUnion. + * If the unionClause is an empty string it returns the sql argument unmodified. * - * An error is returned if targPath can't be made relative to basePath - * or if knowing the current working directory would be necessary to compute it. + * This method exists as a workaround to minimize breaking changes + * and to allow different SQL builders to specify for example whether + * they support parenthesis around the UNION SQL queries + * (SQLite for example will throw a SyntaxError if the UNION parts are wrapped in parenthesis). */ - (basePath: string, targPath: string): string + combineUnion(sql: string, unionClause: string): string } - /** - * WalkFunc is the type of the function called by [Walk] to visit each - * file or directory. - * - * The path argument contains the argument to Walk as a prefix. - * That is, if Walk is called with root argument "dir" and finds a file - * named "a" in that directory, the walk function will be called with - * argument "dir/a". - * - * The directory and file are joined with Join, which may clean the - * directory name: if Walk is called with the root argument "x/../dir" - * and finds a file named "a" in that directory, the walk function will - * be called with argument "dir/a", not "x/../dir/a". - * - * The info argument is the fs.FileInfo for the named path. - * - * The error result returned by the function controls how Walk continues. - * If the function returns the special value [SkipDir], Walk skips the - * current directory (path if info.IsDir() is true, otherwise path's - * parent directory). If the function returns the special value [SkipAll], - * Walk skips all remaining files and directories. Otherwise, if the function - * returns a non-nil error, Walk stops entirely and returns that error. - * - * The err argument reports an error related to path, signaling that Walk - * will not walk into that directory. The function can decide how to - * handle that error; as described earlier, returning the error will - * cause Walk to stop walking the entire tree. - * - * Walk calls the function with a non-nil err argument in two cases. - * - * First, if an [os.Lstat] on the root directory or any directory or file - * in the tree fails, Walk calls the function with path set to that - * directory or file's path, info set to nil, and err set to the error - * from os.Lstat. - * - * Second, if a directory's Readdirnames method fails, Walk calls the - * function with path set to the directory's path, info, set to an - * [fs.FileInfo] describing the directory, and err set to the error from - * Readdirnames. - */ - interface WalkFunc {(path: string, info: fs.FileInfo, err: Error): void } - interface walkDir { + interface BaseQueryBuilder { /** - * WalkDir walks the file tree rooted at root, calling fn for each file or - * directory in the tree, including root. - * - * All errors that arise visiting files and directories are filtered by fn: - * see the [fs.WalkDirFunc] documentation for details. - * - * The files are walked in lexical order, which makes the output deterministic - * but requires WalkDir to read an entire directory into memory before proceeding - * to walk that directory. - * - * WalkDir does not follow symbolic links. - * - * WalkDir calls fn with paths that use the separator character appropriate - * for the operating system. This is unlike [io/fs.WalkDir], which always - * uses slash separated paths. + * BuildOrderBy generates the ORDER BY clause. */ - (root: string, fn: fs.WalkDirFunc): void + buildOrderBy(cols: Array): string } - interface walk { + interface BaseQueryBuilder { /** - * Walk walks the file tree rooted at root, calling fn for each file or - * directory in the tree, including root. - * - * All errors that arise visiting files and directories are filtered by fn: - * see the [WalkFunc] documentation for details. - * - * The files are walked in lexical order, which makes the output deterministic - * but requires Walk to read an entire directory into memory before proceeding - * to walk that directory. - * - * Walk does not follow symbolic links. - * - * Walk is less efficient than [WalkDir], introduced in Go 1.16, - * which avoids calling os.Lstat on every visited file or directory. + * BuildLimit generates the LIMIT clause. */ - (root: string, fn: WalkFunc): void + buildLimit(limit: number, offset: number): string } - interface base { + /** + * VarTypeError indicates a variable type error when trying to populating a variable with DB result. + */ + interface VarTypeError extends String{} + interface VarTypeError { /** - * Base returns the last element of path. - * Trailing path separators are removed before extracting the last element. - * If the path is empty, Base returns ".". - * If the path consists entirely of separators, Base returns a single separator. + * Error returns the error message. */ - (path: string): string + error(): string } - interface dir { - /** - * Dir returns all but the last element of path, typically the path's directory. - * After dropping the final element, Dir calls [Clean] on the path and trailing - * slashes are removed. - * If the path is empty, Dir returns ".". - * If the path consists entirely of separators, Dir returns a single separator. - * The returned path does not end in a separator unless it is the root directory. - * - * On Windows, given a volume-only name such as "C:", Dir returns "C:.", - * the current directory on drive C. To obtain the drive's root "C:\", - * use [VolumeName] combined with a separator. - */ - (path: string): string + /** + * NullStringMap is a map of sql.NullString that can be used to hold DB query result. + * The map keys correspond to the DB column names, while the map values are their corresponding column values. + */ + interface NullStringMap extends _TygojaDict{} + /** + * Rows enhances sql.Rows by providing additional data query methods. + * Rows can be obtained by calling Query.Rows(). It is mainly used to populate data row by row. + */ + type _sEcbkDd = sql.Rows + interface Rows extends _sEcbkDd { } - interface volumeName { + interface Rows { /** - * VolumeName returns leading volume name. - * Given "C:\foo\bar" it returns "C:" on Windows. - * Given "\\host\share\foo" it returns "\\host\share". - * On other platforms it returns "". + * ScanMap populates the current row of data into a NullStringMap. + * Note that the NullStringMap must not be nil, or it will panic. + * The NullStringMap will be populated using column names as keys and their values as + * the corresponding element values. */ - (path: string): string + scanMap(a: NullStringMap): void } - interface hasPrefix { + interface Rows { /** - * HasPrefix exists for historical compatibility and should not be used. + * ScanStruct populates the current row of data into a struct. + * The struct must be given as a pointer. * - * Deprecated: HasPrefix does not respect path boundaries and - * does not ignore case when required. + * ScanStruct associates struct fields with DB table columns through a field mapping function. + * It populates a struct field with the data of its associated column. + * Note that only exported struct fields will be populated. + * + * By default, DefaultFieldMapFunc() is used to map struct fields to table columns. + * This function separates each word in a field name with a underscore and turns every letter into lower case. + * For example, "LastName" is mapped to "last_name", "MyID" is mapped to "my_id", and so on. + * To change the default behavior, set DB.FieldMapper with your custom mapping function. + * You may also set Query.FieldMapper to change the behavior for particular queries. */ - (p: string, prefix: string): boolean + scanStruct(a: { + }): void } -} - -namespace security { - interface s256Challenge { + /** + * BuildHookFunc defines a callback function that is executed on Query creation. + */ + interface BuildHookFunc {(q: Query): void } + /** + * SelectQuery represents a DB-agnostic SELECT query. + * It can be built into a DB-specific query by calling the Build() method. + */ + interface SelectQuery { /** - * S256Challenge creates base64 encoded sha256 challenge string derived from code. - * The padding of the result base64 string is stripped per [RFC 7636]. - * - * [RFC 7636]: https://datatracker.ietf.org/doc/html/rfc7636#section-4.2 + * FieldMapper maps struct field names to DB column names. */ - (code: string): string - } - interface md5 { + fieldMapper: FieldMapFunc /** - * MD5 creates md5 hash from the provided plain text. + * TableMapper maps structs to DB table names. */ - (text: string): string + tableMapper: TableMapFunc } - interface sha256 { + /** + * JoinInfo contains the specification for a JOIN clause. + */ + interface JoinInfo { + join: string + table: string + on: Expression + } + /** + * UnionInfo contains the specification for a UNION clause. + */ + interface UnionInfo { + all: boolean + query?: Query + } + interface newSelectQuery { /** - * SHA256 creates sha256 hash as defined in FIPS 180-4 from the provided text. + * NewSelectQuery creates a new SelectQuery instance. */ - (text: string): string + (builder: Builder, db: DB): (SelectQuery) } - interface sha512 { + interface SelectQuery { /** - * SHA512 creates sha512 hash as defined in FIPS 180-4 from the provided text. + * WithBuildHook runs the provided hook function with the query created on Build(). */ - (text: string): string + withBuildHook(fn: BuildHookFunc): (SelectQuery) } - interface hs256 { + interface SelectQuery { /** - * HS256 creates a HMAC hash with sha256 digest algorithm. + * Context returns the context associated with the query. */ - (text: string, secret: string): string + context(): context.Context } - interface hs512 { + interface SelectQuery { /** - * HS512 creates a HMAC hash with sha512 digest algorithm. + * WithContext associates a context with the query. */ - (text: string, secret: string): string + withContext(ctx: context.Context): (SelectQuery) } - interface equal { + interface SelectQuery { /** - * Equal compares two hash strings for equality without leaking timing information. + * PreFragment sets SQL fragment that should be prepended before the select query (e.g. WITH clause). */ - (hash1: string, hash2: string): boolean + preFragment(fragment: string): (SelectQuery) } - // @ts-ignore - import crand = rand - interface encrypt { + interface SelectQuery { /** - * Encrypt encrypts "data" with the specified "key" (must be valid 32 char AES key). + * PostFragment sets SQL fragment that should be appended at the end of the main select query. * - * This method uses AES-256-GCM block cypher mode. + * If there is "UNION"/"UNION ALL" clause then the extra UNION queries + * are appended after the PostFragment. */ - (data: string|Array, key: string): string + postFragment(fragment: string): (SelectQuery) } - interface decrypt { + interface SelectQuery { /** - * Decrypt decrypts encrypted text with key (must be valid 32 chars AES key). - * - * This method uses AES-256-GCM block cypher mode. + * Select specifies the columns to be selected. + * Column names will be automatically quoted. */ - (cipherText: string, key: string): string|Array + select(...cols: string[]): (SelectQuery) } - interface parseUnverifiedJWT { + interface SelectQuery { /** - * ParseUnverifiedJWT parses JWT and returns its claims - * but DOES NOT verify the signature. - * - * It verifies only the exp, iat and nbf claims. + * AndSelect adds additional columns to be selected. + * Column names will be automatically quoted. */ - (token: string): jwt.MapClaims + andSelect(...cols: string[]): (SelectQuery) } - interface parseJWT { + interface SelectQuery { /** - * ParseJWT verifies and parses JWT and returns its claims. + * Distinct specifies whether to select columns distinctively. + * By default, distinct is false. */ - (token: string, verificationKey: string): jwt.MapClaims + distinct(v: boolean): (SelectQuery) } - interface newJWT { + interface SelectQuery { /** - * NewJWT generates and returns new HS256 signed JWT. + * SelectOption specifies additional option that should be append to "SELECT". */ - (payload: jwt.MapClaims, signingKey: string, duration: time.Duration): string + selectOption(option: string): (SelectQuery) } - // @ts-ignore - import cryptoRand = rand - // @ts-ignore - import mathRand = rand - interface randomString { + interface SelectQuery { /** - * RandomString generates a cryptographically random string with the specified length. - * - * The generated string matches [A-Za-z0-9]+ and it's transparent to URL-encoding. + * From specifies which tables to select from. + * Table names will be automatically quoted. */ - (length: number): string + from(...tables: string[]): (SelectQuery) } - interface randomStringWithAlphabet { + interface SelectQuery { /** - * RandomStringWithAlphabet generates a cryptographically random string - * with the specified length and characters set. - * - * It panics if for some reason rand.Int returns a non-nil error. + * Where specifies the WHERE condition. */ - (length: number, alphabet: string): string + where(e: Expression): (SelectQuery) } - interface pseudorandomString { + interface SelectQuery { /** - * PseudorandomString generates a pseudorandom string with the specified length. - * - * The generated string matches [A-Za-z0-9]+ and it's transparent to URL-encoding. - * - * For a cryptographically random string (but a little bit slower) use RandomString instead. + * AndWhere concatenates a new WHERE condition with the existing one (if any) using "AND". */ - (length: number): string + andWhere(e: Expression): (SelectQuery) } - interface pseudorandomStringWithAlphabet { + interface SelectQuery { /** - * PseudorandomStringWithAlphabet generates a pseudorandom string - * with the specified length and characters set. - * - * For a cryptographically random (but a little bit slower) use RandomStringWithAlphabet instead. + * OrWhere concatenates a new WHERE condition with the existing one (if any) using "OR". */ - (length: number, alphabet: string): string + orWhere(e: Expression): (SelectQuery) } - interface randomStringByRegex { + interface SelectQuery { /** - * RandomStringByRegex generates a random string matching the regex pattern. - * If optFlags is not set, fallbacks to [syntax.Perl]. - * - * NB! While the source of the randomness comes from [crypto/rand] this method - * is not recommended to be used on its own in critical secure contexts because - * the generated length could vary too much on the used pattern and may not be - * as secure as simply calling [security.RandomString]. - * If you still insist on using it for such purposes, consider at least - * a large enough minimum length for the generated string, e.g. `[a-z0-9]{30}`. - * - * This function is inspired by github.com/pipe01/revregexp, github.com/lucasjones/reggen and other similar packages. + * Join specifies a JOIN clause. + * The "typ" parameter specifies the JOIN type (e.g. "INNER JOIN", "LEFT JOIN"). */ - (pattern: string, ...optFlags: syntax.Flags[]): string - } -} - -namespace filesystem { - /** - * FileReader defines an interface for a file resource reader. - */ - interface FileReader { - [key:string]: any; - open(): io.ReadSeekCloser - } - /** - * File defines a single file [io.ReadSeekCloser] resource. - * - * The file could be from a local path, multipart/form-data header, etc. - */ - interface File { - reader: FileReader - name: string - originalName: string - size: number + join(typ: string, table: string, on: Expression): (SelectQuery) } - interface File { + interface SelectQuery { /** - * AsMap implements [core.mapExtractor] and returns a value suitable - * to be used in an API rule expression. + * InnerJoin specifies an INNER JOIN clause. + * This is a shortcut method for Join. */ - asMap(): _TygojaDict + innerJoin(table: string, on: Expression): (SelectQuery) } - interface newFileFromPath { + interface SelectQuery { /** - * NewFileFromPath creates a new File instance from the provided local file path. + * LeftJoin specifies a LEFT JOIN clause. + * This is a shortcut method for Join. */ - (path: string): (File) + leftJoin(table: string, on: Expression): (SelectQuery) } - interface newFileFromBytes { + interface SelectQuery { /** - * NewFileFromBytes creates a new File instance from the provided byte slice. + * RightJoin specifies a RIGHT JOIN clause. + * This is a shortcut method for Join. */ - (b: string|Array, name: string): (File) + rightJoin(table: string, on: Expression): (SelectQuery) } - interface newFileFromMultipart { + interface SelectQuery { /** - * NewFileFromMultipart creates a new File from the provided multipart header. + * OrderBy specifies the ORDER BY clause. + * Column names will be properly quoted. A column name can contain "ASC" or "DESC" to indicate its ordering direction. */ - (mh: multipart.FileHeader): (File) + orderBy(...cols: string[]): (SelectQuery) } - interface newFileFromURL { + interface SelectQuery { /** - * NewFileFromURL creates a new File from the provided url by - * downloading the resource and load it as BytesReader. - * - * Example - * - * ``` - * ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - * defer cancel() - * - * file, err := filesystem.NewFileFromURL(ctx, "https://example.com/image.png") - * ``` + * AndOrderBy appends additional columns to the existing ORDER BY clause. + * Column names will be properly quoted. A column name can contain "ASC" or "DESC" to indicate its ordering direction. */ - (ctx: context.Context, url: string): (File) - } - /** - * MultipartReader defines a FileReader from [multipart.FileHeader]. - */ - interface MultipartReader { - header?: multipart.FileHeader + andOrderBy(...cols: string[]): (SelectQuery) } - interface MultipartReader { + interface SelectQuery { /** - * Open implements the [filesystem.FileReader] interface. + * GroupBy specifies the GROUP BY clause. + * Column names will be properly quoted. */ - open(): io.ReadSeekCloser - } - /** - * PathReader defines a FileReader from a local file path. - */ - interface PathReader { - path: string + groupBy(...cols: string[]): (SelectQuery) } - interface PathReader { + interface SelectQuery { /** - * Open implements the [filesystem.FileReader] interface. + * AndGroupBy appends additional columns to the existing GROUP BY clause. + * Column names will be properly quoted. */ - open(): io.ReadSeekCloser - } - /** - * BytesReader defines a FileReader from bytes content. - */ - interface BytesReader { - bytes: string|Array + andGroupBy(...cols: string[]): (SelectQuery) } - interface BytesReader { + interface SelectQuery { /** - * Open implements the [filesystem.FileReader] interface. + * Having specifies the HAVING clause. */ - open(): io.ReadSeekCloser - } - type _sbNoBcY = bytes.Reader - interface bytesReadSeekCloser extends _sbNoBcY { + having(e: Expression): (SelectQuery) } - interface bytesReadSeekCloser { + interface SelectQuery { /** - * Close implements the [io.ReadSeekCloser] interface. + * AndHaving concatenates a new HAVING condition with the existing one (if any) using "AND". */ - close(): void + andHaving(e: Expression): (SelectQuery) } - /** - * openFuncAsReader defines a FileReader from a bare Open function. - */ - interface openFuncAsReader {(): io.ReadSeekCloser } - interface openFuncAsReader { + interface SelectQuery { /** - * Open implements the [filesystem.FileReader] interface. + * OrHaving concatenates a new HAVING condition with the existing one (if any) using "OR". */ - open(): io.ReadSeekCloser - } - type _sLIcpce = hook.Event - interface DeleteEvent extends _sLIcpce { - filesystem?: System - fileKey: string - } - type _sgtQhTO = hook.Event - interface NewWriterEvent extends _sgtQhTO { - filesystem?: System - fileKey: string - options?: blob.WriterOptions - writer?: blob.Writer // filled only after e.Next() - } - interface System { + orHaving(e: Expression): (SelectQuery) } - interface newS3 { + interface SelectQuery { /** - * NewS3 initializes a new S3 filesystem instance. - * - * NB! Make sure to call `Close()` after you are done working with it. + * Union specifies a UNION clause. */ - (bucketName: string, region: string, endpoint: string, accessKey: string, secretKey: string, s3ForcePathStyle: boolean): (System) + union(q: Query): (SelectQuery) } - interface newLocal { + interface SelectQuery { /** - * NewLocal initializes a new local filesystem instance. - * - * NB! Make sure to call `Close()` after you are done working with it. + * UnionAll specifies a UNION ALL clause. */ - (dirPath: string): (System) + unionAll(q: Query): (SelectQuery) } - interface System { + interface SelectQuery { /** - * SetContext assigns the specified context to the current filesystem. + * Limit specifies the LIMIT clause. + * A negative limit means no limit. */ - setContext(ctx: context.Context): void + limit(limit: number): (SelectQuery) } - interface System { + interface SelectQuery { /** - * Close releases any resources used for the related filesystem. + * Offset specifies the OFFSET clause. + * A negative offset means no offset. */ - close(): void + offset(offset: number): (SelectQuery) } - interface System { + interface SelectQuery { /** - * OnNewWriter is a low level hook that is triggered on every new writer initialization - * (aka. when attempting to create a new file with [system.NewWriter] or [system.Upload]). - * - * Note that currently it doesn't trigger on [System.Copy] but this may change in future releases. + * Bind specifies the parameter values to be bound to the query. */ - onNewWriter(): (hook.Hook) + bind(params: Params): (SelectQuery) } - interface System { + interface SelectQuery { /** - * OnDelete is a low level hook that is triggered on every [System.Delete] call. - * - * Note that the hook doesn't fire when a file is being overwritten - * by a new one, because in that case [System.Delete] is not invoked. + * AndBind appends additional parameters to be bound to the query. */ - onDelete(): (hook.Hook) + andBind(params: Params): (SelectQuery) } - interface System { + interface SelectQuery { /** - * Exists checks if file with fileKey path exists or not. + * Build builds the SELECT query and returns an executable Query object. */ - exists(fileKey: string): boolean + build(): (Query) } - interface System { + interface SelectQuery { /** - * Attributes returns the attributes for the file with fileKey path. + * One executes the SELECT query and populates the first row of the result into the specified variable. * - * If the file doesn't exist it returns ErrNotFound. + * If the query does not specify a "from" clause, the method will try to infer the name of the table + * to be selected from by calling getTableName() which will return either the variable type name + * or the TableName() method if the variable implements the TableModel interface. + * + * Note that when the query has no rows in the result set, an sql.ErrNoRows will be returned. */ - attributes(fileKey: string): (blob.Attributes) - } - interface System { - /** - * GetReader returns a file content reader for the given fileKey. - * - * NB! Make sure to call Close() on the file after you are done working with it. - * - * If the file doesn't exist returns ErrNotFound. - */ - getReader(fileKey: string): (blob.Reader) - } - interface System { - /** - * Deprecated: Please use GetReader(fileKey) instead. - */ - getFile(fileKey: string): (blob.Reader) + one(a: { + }): void } - interface System { + interface SelectQuery { /** - * GetReuploadableFile constructs a new reuploadable File value - * from the associated fileKey blob.Reader. - * - * If preserveName is false then the returned File.Name will have - * a new randomly generated suffix, otherwise it will reuse the original one. - * - * This method could be useful in case you want to clone an existing - * Record file and assign it to a new Record (e.g. in a Record duplicate action). + * Model selects the row with the specified primary key and populates the model with the row data. * - * If you simply want to copy an existing file to a new location you - * could check the Copy(srcKey, dstKey) method. + * The model variable should be a pointer to a struct. If the query does not specify a "from" clause, + * it will use the model struct to determine which table to select data from. It will also use the model + * to infer the name of the primary key column. Only simple primary key is supported. For composite primary keys, + * please use Where() to specify the filtering condition. */ - getReuploadableFile(fileKey: string, preserveName: boolean): (File) + model(pk: { + }, model: { + }): void } - interface System { + interface SelectQuery { /** - * Copy copies the file stored at srcKey to dstKey. + * All executes the SELECT query and populates all rows of the result into a slice. * - * If srcKey file doesn't exist, it returns ErrNotFound. + * Note that the slice must be passed in as a pointer. * - * If dstKey file already exists, it is overwritten. + * If the query does not specify a "from" clause, the method will try to infer the name of the table + * to be selected from by calling getTableName() which will return either the type name of the slice elements + * or the TableName() method if the slice element implements the TableModel interface. */ - copy(srcKey: string, dstKey: string): void + all(slice: { + }): void } - interface System { + interface SelectQuery { /** - * List returns a flat list with info for all files under the specified prefix. + * Rows builds and executes the SELECT query and returns a Rows object for data retrieval purpose. + * This is a shortcut to SelectQuery.Build().Rows() */ - list(prefix: string): Array<(blob.ListObject | undefined)> + rows(): (Rows) } - interface System { + interface SelectQuery { /** - * Upload writes content into the fileKey location. + * Row builds and executes the SELECT query and populates the first row of the result into the specified variables. + * This is a shortcut to SelectQuery.Build().Row() */ - upload(content: string|Array, fileKey: string): void + row(...a: { + }[]): void } - interface System { + interface SelectQuery { /** - * UploadFile uploads the provided File to the fileKey location. + * Column builds and executes the SELECT statement and populates the first column of the result into a slice. + * Note that the parameter must be a pointer to a slice. + * This is a shortcut to SelectQuery.Build().Column() */ - uploadFile(file: File, fileKey: string): void + column(a: { + }): void } - interface System { - /** - * UploadMultipart uploads the provided multipart file to the fileKey location. - */ - uploadMultipart(fh: multipart.FileHeader, fileKey: string): void + /** + * QueryInfo represents a debug/info struct with exported SelectQuery fields. + */ + interface QueryInfo { + preFragment: string + postFragment: string + builder: Builder + selects: Array + distinct: boolean + selectOption: string + from: Array + where: Expression + join: Array + orderBy: Array + groupBy: Array + having: Expression + union: Array + limit: number + offset: number + params: Params + context: context.Context + buildHook: BuildHookFunc } - interface System { + interface SelectQuery { /** - * NewWriter returns a new blob.Writer instance allowing direct file - * create from an io.Reader value. - * - * If a file with the specified fileKey already exists, it will be replaced. - * - * NB! Make sure to call `Close()` on the resulting writer after you are done working with it. - * - * Note: If you have a bytes slice, [filesystem.File], or a multipart header value, - * you can check also the Upload* related methods as they are more user-friendly. - * - * Example: - * - * ``` - * content := strings.NewReader("Lorem ipsum dolor sit amet...") - * - * fsys, _ := filesystem.NewLocal("dir") - * defer fsys.Close() - * - * w, _ := fsys.NewWriter("example/file/key", nil) - * w.ReadFrom(content) - * w.Close() - * ``` + * Info exports common SelectQuery fields allowing to inspect the + * current select query options. */ - newWriter(fileKey: string, opts: blob.WriterOptions): (blob.Writer) + info(): (QueryInfo) } - interface System { + /** + * FieldMapFunc converts a struct field name into a DB column name. + */ + interface FieldMapFunc {(_arg0: string): string } + /** + * TableMapFunc converts a sample struct into a DB table name. + */ + interface TableMapFunc {(a: { + }): string } + interface structInfo { + } + type _sUavKsn = structInfo + interface structValue extends _sUavKsn { + } + interface fieldInfo { + } + interface structInfoMapKey { + } + /** + * PostScanner is an optional interface used by ScanStruct. + */ + interface PostScanner { + [key:string]: any; /** - * Delete deletes stored file at fileKey location. - * - * If the file doesn't exist returns ErrNotFound. + * PostScan executes right after the struct has been populated + * with the DB values, allowing you to further normalize or validate + * the loaded data. */ - delete(fileKey: string): void + postScan(): void } - interface System { + interface defaultFieldMapFunc { /** - * DeletePrefix deletes everything starting with the specified prefix. - * - * The prefix could be subpath (ex. "/a/b/") or filename prefix (ex. "/a/b/file_"). + * DefaultFieldMapFunc maps a field name to a DB column name. + * The mapping rule set by this method is that words in a field name will be separated by underscores + * and the name will be turned into lower case. For example, "FirstName" maps to "first_name", and "MyID" becomes "my_id". + * See DB.FieldMapper for more details. */ - deletePrefix(prefix: string): Array + (f: string): string } - interface System { + interface getTableName { /** - * Checks if the provided dir prefix doesn't have any files. - * - * A trailing slash will be appended to a non-empty dir string argument - * to ensure that the checked prefix is a "directory". - * - * Returns "false" in case it has at least one file, otherwise - "true". + * GetTableName implements the default way of determining the table name corresponding to the given model struct + * or slice of structs. To get the actual table name for a model, you should use DB.TableMapFunc() instead. + * Do not call this method in a model's TableName() method because it will cause infinite loop. */ - isEmptyDir(dir: string): boolean + (a: { + }): string } - interface System { + /** + * Tx enhances sql.Tx with additional querying methods. + */ + type _sPGHMum = Builder + interface Tx extends _sPGHMum { + } + interface Tx { /** - * Serve serves the file at fileKey location to an HTTP response. - * - * If the `download` query parameter is used the file will be always served for - * download no matter of its type (aka. with "Content-Disposition: attachment"). - * - * Internally this method uses [http.ServeContent] so Range requests, - * If-Match, If-Unmodified-Since, etc. headers are handled transparently. + * Commit commits the transaction. */ - serve(res: http.ResponseWriter, req: http.Request, fileKey: string, name: string): void + commit(): void } - interface System { + interface Tx { /** - * CreateThumb creates a new thumb image for the file at originalKey location. - * The new thumb file is stored at thumbKey location. - * - * thumbSize is in the format: - * - 0xH (eg. 0x100) - resize to H height preserving the aspect ratio - * - Wx0 (eg. 300x0) - resize to W width preserving the aspect ratio - * - WxH (eg. 300x100) - resize and crop to WxH viewbox (from center) - * - WxHt (eg. 300x100t) - resize and crop to WxH viewbox (from top) - * - WxHb (eg. 300x100b) - resize and crop to WxH viewbox (from bottom) - * - WxHf (eg. 300x100f) - fit inside a WxH viewbox (without cropping) + * Rollback aborts the transaction. */ - createThumb(originalKey: string, thumbKey: string, thumbSize: string): void - } -} - -/** - * Package validation provides configurable and extensible rules for validating data of various types. - */ -namespace ozzo_validation { - /** - * Error interface represents an validation error - */ - interface Error { - [key:string]: any; - error(): string - code(): string - message(): string - setMessage(_arg0: string): Error - params(): _TygojaDict - setParams(_arg0: _TygojaDict): Error + rollback(): void } } @@ -6115,12 +6116,18 @@ namespace core { * Bootstrap initializes the application * (aka. create data dir, open db connections, load settings, etc.). * - * It will call ResetBootstrapState() if the application was already bootstrapped. + * It calls ClearBootstrap() if the application was already bootstrapped. */ bootstrap(): void /** - * ResetBootstrapState releases the initialized core app resources + * ClearBootstrap releases the initialized core app resources * (closing db connections, stopping cron ticker, etc.). + * + * This method is no-op if the application is not bootstrapped yet. + */ + clearBootstrap(): void + /** + * Deprecated: use ClearBootstrap(). */ resetBootstrapState(): void /** @@ -6857,6 +6864,11 @@ namespace core { * resources (db, app settings, etc). */ onBootstrap(): (hook.Hook) + /** + * OnClearBootstrap hook is triggered on unsetting the main application + * resources (db, app settings, etc) to their initial nil/empty value. + */ + onClearBootstrap(): (hook.Hook) /** * OnServe hook is triggered when the app web server is started * (after starting the TCP listener but before initializing the blocking serve task), @@ -7746,8 +7758,8 @@ namespace core { /** * AuthOrigin defines a Record proxy for working with the authOrigins collection. */ - type _skUTTOQ = Record - interface AuthOrigin extends _skUTTOQ { + type _sfTdFVS = Record + interface AuthOrigin extends _sfTdFVS { } interface newAuthOrigin { /** @@ -8043,20 +8055,24 @@ namespace core { * Bootstrap initializes the application * (aka. create data dir, open db connections, load settings, etc.). * - * It will call ResetBootstrapState() if the application was already bootstrapped. + * It calls ClearBootstrap() if the application was already bootstrapped. */ bootstrap(): void } - interface closer { - [key:string]: any; - close(): void + interface BaseApp { + /** + * Deprecated: use [ClearBootstrap]. + */ + resetBootstrapState(): void } interface BaseApp { /** - * ResetBootstrapState releases the initialized core app resources + * ClearBootstrap releases the initialized core app resources * (closing db connections, stopping cron ticker, etc.). + * + * This method is no-op if the application is not bootstrapped yet. */ - resetBootstrapState(): void + clearBootstrap(): void } interface BaseApp { /** @@ -8249,6 +8265,9 @@ namespace core { interface BaseApp { onBootstrap(): (hook.Hook) } + interface BaseApp { + onClearBootstrap(): (hook.Hook) + } interface BaseApp { onServe(): (hook.Hook) } @@ -8518,8 +8537,8 @@ namespace core { * @todo experiment eventually replacing the rules *string with a struct? * @todo consider changing the Indexes field to a "getter" for the sqlite_master table? */ - type _sRZkQBb = BaseModel - interface baseCollection extends _sRZkQBb { + type _sMrSXio = BaseModel + interface baseCollection extends _sMrSXio { listRule?: string viewRule?: string createRule?: string @@ -8546,8 +8565,8 @@ namespace core { /** * Collection defines the table, fields and various options related to a set of records. */ - type _sVCSHXH = baseCollection&collectionAuthOptions&collectionViewOptions - interface Collection extends _sVCSHXH { + type _sPhWjYb = baseCollection&collectionAuthOptions&collectionViewOptions + interface Collection extends _sPhWjYb { } interface newCollection { /** @@ -9569,8 +9588,8 @@ namespace core { /** * RequestEvent defines the PocketBase router handler event. */ - type _sHkEkYp = router.Event - interface RequestEvent extends _sHkEkYp { + type _sAixdDf = router.Event + interface RequestEvent extends _sAixdDf { app: App auth?: Record } @@ -9630,8 +9649,8 @@ namespace core { */ clone(): (RequestInfo) } - type _sVXRxMa = hook.Event&RequestEvent - interface BatchRequestEvent extends _sVXRxMa { + type _saEgHbx = hook.Event&RequestEvent + interface BatchRequestEvent extends _saEgHbx { batch: Array<(InternalRequest | undefined)> } interface InternalRequest { @@ -9673,24 +9692,24 @@ namespace core { */ tags(): Array } - type _sdxMSqt = hook.Event - interface BootstrapEvent extends _sdxMSqt { + type _szuccpV = hook.Event + interface BootstrapEvent extends _szuccpV { app: App } - type _sqLfYeT = hook.Event - interface TerminateEvent extends _sqLfYeT { + type _svmPUZl = hook.Event + interface TerminateEvent extends _svmPUZl { app: App isRestart: boolean } - type _sOaKOTX = hook.Event - interface BackupEvent extends _sOaKOTX { + type _syWkYGa = hook.Event + interface BackupEvent extends _syWkYGa { app: App context: context.Context name: string // the name of the backup to create/restore. exclude: Array // list of dir entries to exclude from the backup create/restore. } - type _salbcgr = hook.Event - interface ServeEvent extends _salbcgr { + type _snplGol = hook.Event + interface ServeEvent extends _snplGol { app: App router?: router.Router server?: http.Server @@ -9737,39 +9756,39 @@ namespace core { */ fs: fs.FS } - type _syMCPRb = hook.Event&RequestEvent - interface SettingsListRequestEvent extends _syMCPRb { + type _sTXxUSj = hook.Event&RequestEvent + interface SettingsListRequestEvent extends _sTXxUSj { settings?: Settings } - type _sqpIEBm = hook.Event&RequestEvent - interface SettingsUpdateRequestEvent extends _sqpIEBm { + type _sFcVVYW = hook.Event&RequestEvent + interface SettingsUpdateRequestEvent extends _sFcVVYW { oldSettings?: Settings newSettings?: Settings } - type _sIkzIda = hook.Event - interface SettingsReloadEvent extends _sIkzIda { + type _sTEmlDD = hook.Event + interface SettingsReloadEvent extends _sTEmlDD { app: App } - type _sbBRJSa = hook.Event - interface MailerEvent extends _sbBRJSa { + type _soJSiyF = hook.Event + interface MailerEvent extends _soJSiyF { app: App mailer: mailer.Mailer message?: mailer.Message } - type _sVWOUZa = MailerEvent&baseRecordEventData - interface MailerRecordEvent extends _sVWOUZa { + type _sIlXQHk = MailerEvent&baseRecordEventData + interface MailerRecordEvent extends _sIlXQHk { meta: _TygojaDict } - type _sXHptlc = hook.Event&filesystem.NewWriterEvent - interface FilesystemNewWriterEvent extends _sXHptlc { + type _sVrhoAZ = hook.Event&filesystem.NewWriterEvent + interface FilesystemNewWriterEvent extends _sVrhoAZ { app: App } - type _sasEdrD = hook.Event&filesystem.DeleteEvent - interface FilesystemDeleteEvent extends _sasEdrD { + type _sOEnBQs = hook.Event&filesystem.DeleteEvent + interface FilesystemDeleteEvent extends _sOEnBQs { app: App } - type _sHLlOfS = hook.Event&baseModelEventData - interface ModelEvent extends _sHLlOfS { + type _sdPrXLi = hook.Event&baseModelEventData + interface ModelEvent extends _sdPrXLi { app: App context: context.Context /** @@ -9781,12 +9800,12 @@ namespace core { */ type: string } - type _saIXSlj = ModelEvent - interface ModelErrorEvent extends _saIXSlj { + type _shdTPyX = ModelEvent + interface ModelErrorEvent extends _shdTPyX { error: Error } - type _siDFCDs = hook.Event&baseRecordEventData - interface RecordEvent extends _siDFCDs { + type _sPaTJwN = hook.Event&baseRecordEventData + interface RecordEvent extends _sPaTJwN { app: App context: context.Context /** @@ -9798,12 +9817,12 @@ namespace core { */ type: string } - type _sNeIyFn = RecordEvent - interface RecordErrorEvent extends _sNeIyFn { + type _sSOjMag = RecordEvent + interface RecordErrorEvent extends _sSOjMag { error: Error } - type _satfxiI = hook.Event&baseCollectionEventData - interface CollectionEvent extends _satfxiI { + type _sKGZzNg = hook.Event&baseCollectionEventData + interface CollectionEvent extends _sKGZzNg { app: App context: context.Context /** @@ -9815,16 +9834,16 @@ namespace core { */ type: string } - type _seQvQwl = CollectionEvent - interface CollectionErrorEvent extends _seQvQwl { + type _sRhBsCo = CollectionEvent + interface CollectionErrorEvent extends _sRhBsCo { error: Error } - type _sELEntR = hook.Event&RequestEvent&baseRecordEventData - interface FileTokenRequestEvent extends _sELEntR { + type _suRFPwQ = hook.Event&RequestEvent&baseRecordEventData + interface FileTokenRequestEvent extends _suRFPwQ { token: string } - type _sMbHtMV = hook.Event&RequestEvent&baseCollectionEventData - interface FileDownloadRequestEvent extends _sMbHtMV { + type _sMWQElu = hook.Event&RequestEvent&baseCollectionEventData + interface FileDownloadRequestEvent extends _sMWQElu { record?: Record fileField?: FileField servedPath: string @@ -9838,21 +9857,21 @@ namespace core { */ thumbError: Error } - type _savwOak = hook.Event&RequestEvent - interface CollectionsListRequestEvent extends _savwOak { + type _skaeskq = hook.Event&RequestEvent + interface CollectionsListRequestEvent extends _skaeskq { collections: Array<(Collection | undefined)> result?: search.Result } - type _slwOFAf = hook.Event&RequestEvent - interface CollectionsImportRequestEvent extends _slwOFAf { + type _sIvwrMR = hook.Event&RequestEvent + interface CollectionsImportRequestEvent extends _sIvwrMR { collectionsData: Array<_TygojaDict> deleteMissing: boolean } - type _sYHYhOQ = hook.Event&RequestEvent&baseCollectionEventData - interface CollectionRequestEvent extends _sYHYhOQ { + type _sGUIvvo = hook.Event&RequestEvent&baseCollectionEventData + interface CollectionRequestEvent extends _sGUIvvo { } - type _sMwDzja = hook.Event&RequestEvent - interface RealtimeConnectRequestEvent extends _sMwDzja { + type _sVlsaAU = hook.Event&RequestEvent + interface RealtimeConnectRequestEvent extends _sVlsaAU { client: subscriptions.Client /** * IdleTimeout specifies the max duration to wait for a new message @@ -9876,59 +9895,59 @@ namespace core { */ maxTimeout: time.Duration } - type _sJZEyAl = hook.Event&RequestEvent - interface RealtimeMessageEvent extends _sJZEyAl { + type _sWINXaH = hook.Event&RequestEvent + interface RealtimeMessageEvent extends _sWINXaH { client: subscriptions.Client message?: subscriptions.Message } - type _sMEZZwx = hook.Event&RequestEvent - interface RealtimeSubscribeRequestEvent extends _sMEZZwx { + type _sFqJZoj = hook.Event&RequestEvent + interface RealtimeSubscribeRequestEvent extends _sFqJZoj { client: subscriptions.Client subscriptions: Array } - type _sOEioim = hook.Event&RequestEvent&baseCollectionEventData - interface RecordsListRequestEvent extends _sOEioim { + type _sqxcTwT = hook.Event&RequestEvent&baseCollectionEventData + interface RecordsListRequestEvent extends _sqxcTwT { /** * @todo consider removing and maybe add as generic to the search.Result? */ records: Array<(Record | undefined)> result?: search.Result } - type _sYBQkRT = hook.Event&RequestEvent&baseCollectionEventData - interface RecordRequestEvent extends _sYBQkRT { + type _sEBcDLS = hook.Event&RequestEvent&baseCollectionEventData + interface RecordRequestEvent extends _sEBcDLS { record?: Record } - type _sSFyFCB = hook.Event&baseRecordEventData - interface RecordEnrichEvent extends _sSFyFCB { + type _sHFrNWM = hook.Event&baseRecordEventData + interface RecordEnrichEvent extends _sHFrNWM { app: App requestInfo?: RequestInfo } - type _smuxffh = hook.Event&RequestEvent&baseCollectionEventData - interface RecordCreateOTPRequestEvent extends _smuxffh { + type _sRJBbXV = hook.Event&RequestEvent&baseCollectionEventData + interface RecordCreateOTPRequestEvent extends _sRJBbXV { record?: Record password: string } - type _sZUkggv = hook.Event&RequestEvent&baseCollectionEventData - interface RecordAuthWithOTPRequestEvent extends _sZUkggv { + type _sSFOEUQ = hook.Event&RequestEvent&baseCollectionEventData + interface RecordAuthWithOTPRequestEvent extends _sSFOEUQ { record?: Record otp?: OTP } - type _sRMmVNR = hook.Event&RequestEvent&baseCollectionEventData - interface RecordAuthRequestEvent extends _sRMmVNR { + type _sNPfQBP = hook.Event&RequestEvent&baseCollectionEventData + interface RecordAuthRequestEvent extends _sNPfQBP { record?: Record token: string meta: any authMethod: string } - type _siHqObM = hook.Event&RequestEvent&baseCollectionEventData - interface RecordAuthWithPasswordRequestEvent extends _siHqObM { + type _sffXoQl = hook.Event&RequestEvent&baseCollectionEventData + interface RecordAuthWithPasswordRequestEvent extends _sffXoQl { record?: Record identity: string identityField: string password: string } - type _sNmEWPY = hook.Event&RequestEvent&baseCollectionEventData - interface RecordAuthWithOAuth2RequestEvent extends _sNmEWPY { + type _sAjODFE = hook.Event&RequestEvent&baseCollectionEventData + interface RecordAuthWithOAuth2RequestEvent extends _sAjODFE { providerName: string providerClient: auth.Provider record?: Record @@ -9936,41 +9955,41 @@ namespace core { createData: _TygojaDict isNewRecord: boolean } - type _sNpgBcw = hook.Event&RequestEvent&baseCollectionEventData - interface RecordAuthRefreshRequestEvent extends _sNpgBcw { + type _sbscBPU = hook.Event&RequestEvent&baseCollectionEventData + interface RecordAuthRefreshRequestEvent extends _sbscBPU { record?: Record } - type _sjZAPbR = hook.Event&RequestEvent&baseCollectionEventData - interface RecordRequestPasswordResetRequestEvent extends _sjZAPbR { + type _sziHdKA = hook.Event&RequestEvent&baseCollectionEventData + interface RecordRequestPasswordResetRequestEvent extends _sziHdKA { record?: Record } - type _sDxRako = hook.Event&RequestEvent&baseCollectionEventData - interface RecordConfirmPasswordResetRequestEvent extends _sDxRako { + type _sUsRGlx = hook.Event&RequestEvent&baseCollectionEventData + interface RecordConfirmPasswordResetRequestEvent extends _sUsRGlx { record?: Record } - type _skmVfkI = hook.Event&RequestEvent&baseCollectionEventData - interface RecordRequestVerificationRequestEvent extends _skmVfkI { + type _sfFwZII = hook.Event&RequestEvent&baseCollectionEventData + interface RecordRequestVerificationRequestEvent extends _sfFwZII { record?: Record } - type _soludsJ = hook.Event&RequestEvent&baseCollectionEventData - interface RecordConfirmVerificationRequestEvent extends _soludsJ { + type _sxVpkkX = hook.Event&RequestEvent&baseCollectionEventData + interface RecordConfirmVerificationRequestEvent extends _sxVpkkX { record?: Record } - type _snewJpv = hook.Event&RequestEvent&baseCollectionEventData - interface RecordRequestEmailChangeRequestEvent extends _snewJpv { + type _svZZCHI = hook.Event&RequestEvent&baseCollectionEventData + interface RecordRequestEmailChangeRequestEvent extends _svZZCHI { record?: Record newEmail: string } - type _sBQDVcU = hook.Event&RequestEvent&baseCollectionEventData - interface RecordConfirmEmailChangeRequestEvent extends _sBQDVcU { + type _sxWUmMi = hook.Event&RequestEvent&baseCollectionEventData + interface RecordConfirmEmailChangeRequestEvent extends _sxWUmMi { record?: Record newEmail: string } /** * ExternalAuth defines a Record proxy for working with the externalAuths collection. */ - type _sxwOsja = Record - interface ExternalAuth extends _sxwOsja { + type _sDmvgWd = Record + interface ExternalAuth extends _sDmvgWd { } interface newExternalAuth { /** @@ -12513,8 +12532,8 @@ namespace core { interface onlyFieldType { type: string } - type _sobXxBx = Field - interface fieldWithType extends _sobXxBx { + type _scTsMAP = Field + interface fieldWithType extends _scTsMAP { type: string } interface fieldWithType { @@ -12546,8 +12565,8 @@ namespace core { */ scan(value: any): void } - type _scHkwNm = BaseModel - interface Log extends _scHkwNm { + type _spdLkQF = BaseModel + interface Log extends _spdLkQF { created: types.DateTime data: types.JSONMap message: string @@ -12602,8 +12621,8 @@ namespace core { /** * MFA defines a Record proxy for working with the mfas collection. */ - type _sMkWfDf = Record - interface MFA extends _sMkWfDf { + type _sHTLAbI = Record + interface MFA extends _sHTLAbI { } interface newMFA { /** @@ -12825,8 +12844,8 @@ namespace core { /** * OTP defines a Record proxy for working with the otps collection. */ - type _sfRGgyY = Record - interface OTP extends _sfRGgyY { + type _suFJxap = Record + interface OTP extends _suFJxap { } interface newOTP { /** @@ -13062,8 +13081,8 @@ namespace core { } interface runner { } - type _sRQHOmG = BaseModel - interface Record extends _sRQHOmG { + type _sMomDaG = BaseModel + interface Record extends _sMomDaG { } interface newRecord { /** @@ -13544,8 +13563,8 @@ namespace core { * BaseRecordProxy implements the [RecordProxy] interface and it is intended * to be used as embed to custom user provided Record proxy structs. */ - type _sOhfTQZ = Record - interface BaseRecordProxy extends _sOhfTQZ { + type _sDCPhWs = Record + interface BaseRecordProxy extends _sDCPhWs { } interface BaseRecordProxy { /** @@ -13799,8 +13818,8 @@ namespace core { /** * Settings defines the PocketBase app settings. */ - type _sDIkKCd = settings - interface Settings extends _sDIkKCd { + type _skpmbuj = settings + interface Settings extends _skpmbuj { } interface Settings { /** @@ -14115,8 +14134,8 @@ namespace core { */ string(): string } - type _sGHjOtf = BaseModel - interface Param extends _sGHjOtf { + type _sBhNrOD = BaseModel + interface Param extends _sBhNrOD { created: types.DateTime updated: types.DateTime value: types.JSONRaw @@ -14662,8 +14681,8 @@ namespace apis { * rereads and doesn't try to prematurely close the related response * to allow consequent middlewares to operate correctly. */ - type _sMwllhP = io.ReadCloser - interface maxBytesReader extends _sMwllhP { + type _sWbUFnM = io.ReadCloser + interface maxBytesReader extends _sWbUFnM { } interface maxBytesReader { read(b: string|Array): number @@ -14817,8 +14836,8 @@ namespace apis { */ (config: GzipConfig): (hook.Handler) } - type _sFnHZmO = http.ResponseWriter&io.Writer - interface gzipResponseWriter extends _sFnHZmO { + type _sQtUTgE = http.ResponseWriter&io.Writer + interface gzipResponseWriter extends _sQtUTgE { } interface gzipResponseWriter { writeHeader(code: number): void @@ -14838,16 +14857,16 @@ namespace apis { interface gzipResponseWriter { unwrap(): http.ResponseWriter } - type _spUUQeD = sync.RWMutex - interface rateLimiter extends _spUUQeD { + type _sHNxbTf = sync.RWMutex + interface rateLimiter extends _sHNxbTf { } /** * @todo evaluate swiching to sliding window with approximation counter similar to Cloudflare. * * rateClient implements fixed window rate limit strategy. */ - type _sjiUSpY = sync.Mutex - interface rateClient extends _sjiUSpY { + type _sYQpESX = sync.Mutex + interface rateClient extends _sYQpESX { } interface realtimeSubscribeForm { clientId: string @@ -15107,8 +15126,8 @@ namespace pocketbase { * It implements [CoreApp] via embedding and all of the app interface methods * could be accessed directly through the instance (eg. PocketBase.DataDir()). */ - type _soNkBgo = CoreApp - interface PocketBase extends _soNkBgo { + type _sXwYdQP = CoreApp + interface PocketBase extends _sXwYdQP { /** * RootCmd is the main console command */ @@ -15523,91 +15542,6 @@ namespace io { } } -/** - * Package bytes implements functions for the manipulation of byte slices. - * It is analogous to the facilities of the [strings] package. - */ -namespace bytes { - /** - * A Reader implements the [io.Reader], [io.ReaderAt], [io.WriterTo], [io.Seeker], - * [io.ByteScanner], and [io.RuneScanner] interfaces by reading from - * a byte slice. - * Unlike a [Buffer], a Reader is read-only and supports seeking. - * The zero value for Reader operates like a Reader of an empty slice. - */ - interface Reader { - } - interface Reader { - /** - * Len returns the number of bytes of the unread portion of the - * slice. - */ - len(): number - } - interface Reader { - /** - * Size returns the original length of the underlying byte slice. - * Size is the number of bytes available for reading via [Reader.ReadAt]. - * The result is unaffected by any method calls except [Reader.Reset]. - */ - size(): number - } - interface Reader { - /** - * Read implements the [io.Reader] interface. - */ - read(b: string|Array): number - } - interface Reader { - /** - * ReadAt implements the [io.ReaderAt] interface. - */ - readAt(b: string|Array, off: number): number - } - interface Reader { - /** - * ReadByte implements the [io.ByteReader] interface. - */ - readByte(): number - } - interface Reader { - /** - * UnreadByte complements [Reader.ReadByte] in implementing the [io.ByteScanner] interface. - */ - unreadByte(): void - } - interface Reader { - /** - * ReadRune implements the [io.RuneReader] interface. - */ - readRune(): [number, number] - } - interface Reader { - /** - * UnreadRune complements [Reader.ReadRune] in implementing the [io.RuneScanner] interface. - */ - unreadRune(): void - } - interface Reader { - /** - * Seek implements the [io.Seeker] interface. - */ - seek(offset: number, whence: number): number - } - interface Reader { - /** - * WriteTo implements the [io.WriterTo] interface. - */ - writeTo(w: io.Writer): number - } - interface Reader { - /** - * Reset resets the [Reader] to be reading from b. - */ - reset(b: string|Array): void - } -} - /** * Package syscall contains an interface to the low-level operating system * primitives. The details vary depending on the underlying system, and @@ -16572,178 +16506,297 @@ namespace fs { } /** - * Package cron implements a crontab-like service to execute and schedule - * repeative tasks/jobs. - * - * Example: - * - * ``` - * c := cron.New() - * c.MustAdd("dailyReport", "0 0 * * *", func() { ... }) - * c.Start() - * ``` + * Package bytes implements functions for the manipulation of byte slices. + * It is analogous to the facilities of the [strings] package. */ -namespace cron { +namespace bytes { /** - * Cron is a crontab-like struct for tasks/jobs scheduling. + * A Reader implements the [io.Reader], [io.ReaderAt], [io.WriterTo], [io.Seeker], + * [io.ByteScanner], and [io.RuneScanner] interfaces by reading from + * a byte slice. + * Unlike a [Buffer], a Reader is read-only and supports seeking. + * The zero value for Reader operates like a Reader of an empty slice. */ - interface Cron { + interface Reader { } - interface Cron { + interface Reader { /** - * SetInterval changes the current cron tick interval - * (it usually should be >= 1 minute). + * Len returns the number of bytes of the unread portion of the + * slice. */ - setInterval(d: time.Duration): void + len(): number } - interface Cron { + interface Reader { /** - * SetTimezone changes the current cron tick timezone. + * Size returns the original length of the underlying byte slice. + * Size is the number of bytes available for reading via [Reader.ReadAt]. + * The result is unaffected by any method calls except [Reader.Reset]. */ - setTimezone(l: time.Location): void + size(): number } - interface Cron { + interface Reader { /** - * MustAdd is similar to Add() but panic on failure. + * Read implements the [io.Reader] interface. */ - mustAdd(jobId: string, cronExpr: string, run: () => void): void + read(b: string|Array): number } - interface Cron { + interface Reader { /** - * Add registers a single cron job. - * - * If there is already a job with the provided id, then the old job - * will be replaced with the new one. - * - * cronExpr is a regular cron expression, eg. "0 *\/3 * * *" (aka. at minute 0 past every 3rd hour). - * Check cron.NewSchedule() for the supported tokens. + * ReadAt implements the [io.ReaderAt] interface. */ - add(jobId: string, cronExpr: string, fn: () => void): void + readAt(b: string|Array, off: number): number } - interface Cron { + interface Reader { /** - * Remove removes a single cron job by its id. + * ReadByte implements the [io.ByteReader] interface. */ - remove(jobId: string): void + readByte(): number } - interface Cron { + interface Reader { /** - * RemoveAll removes all registered cron jobs. + * UnreadByte complements [Reader.ReadByte] in implementing the [io.ByteScanner] interface. */ - removeAll(): void + unreadByte(): void } - interface Cron { + interface Reader { /** - * Total returns the current total number of registered cron jobs. + * ReadRune implements the [io.RuneReader] interface. */ - total(): number + readRune(): [number, number] } - interface Cron { + interface Reader { /** - * Jobs returns a shallow copy of the currently registered cron jobs. + * UnreadRune complements [Reader.ReadRune] in implementing the [io.RuneScanner] interface. */ - jobs(): Array<(Job | undefined)> + unreadRune(): void } - interface Cron { + interface Reader { /** - * Stop stops the current cron ticker (if not already). - * - * You can resume the ticker by calling Start(). + * Seek implements the [io.Seeker] interface. */ - stop(): void + seek(offset: number, whence: number): number } - interface Cron { + interface Reader { /** - * Start starts the cron ticker. - * - * Calling Start() on already started cron will restart the ticker. + * WriteTo implements the [io.WriterTo] interface. */ - start(): void + writeTo(w: io.Writer): number } - interface Cron { + interface Reader { /** - * HasStarted checks whether the current Cron ticker has been started. + * Reset resets the [Reader] to be reading from b. */ - hasStarted(): boolean + reset(b: string|Array): void } } -/** - * Package syntax parses regular expressions into parse trees and compiles - * parse trees into programs. Most clients of regular expressions will use the - * facilities of package [regexp] (such as [regexp.Compile] and [regexp.Match]) instead of this package. - * - * # Syntax - * - * The regular expression syntax understood by this package when parsing with the [Perl] flag is as follows. - * Parts of the syntax can be disabled by passing alternate flags to [Parse]. - * - * Single characters: - * - * ``` - * . any character, possibly including newline (flag s=true) - * [xyz] character class - * [^xyz] negated character class - * \d Perl character class - * \D negated Perl character class - * [[:alpha:]] ASCII character class - * [[:^alpha:]] negated ASCII character class - * \pN Unicode character class (one-letter name) - * \p{Greek} Unicode character class - * \PN negated Unicode character class (one-letter name) - * \P{Greek} negated Unicode character class - * ``` - * - * Composites: - * - * ``` - * xy x followed by y - * x|y x or y (prefer x) - * ``` - * - * Repetitions: - * - * ``` - * x* zero or more x, prefer more - * x+ one or more x, prefer more - * x? zero or one x, prefer one - * x{n,m} n or n+1 or ... or m x, prefer more - * x{n,} n or more x, prefer more - * x{n} exactly n x - * x*? zero or more x, prefer fewer - * x+? one or more x, prefer fewer - * x?? zero or one x, prefer zero - * x{n,m}? n or n+1 or ... or m x, prefer fewer - * x{n,}? n or more x, prefer fewer - * x{n}? exactly n x - * ``` - * - * Implementation restriction: The counting forms x{n,m}, x{n,}, and x{n} - * reject forms that create a minimum or maximum repetition count above 1000. - * Unlimited repetitions are not subject to this restriction. - * - * Grouping: - * - * ``` - * (re) numbered capturing group (submatch) - * (?Pre) named & numbered capturing group (submatch) - * (?re) named & numbered capturing group (submatch) - * (?:re) non-capturing group - * (?flags) set flags within current group; non-capturing - * (?flags:re) set flags during re; non-capturing - * - * Flag syntax is xyz (set) or -xyz (clear) or xy-z (set xy, clear z). The flags are: - * - * i case-insensitive (default false) - * m multi-line mode: ^ and $ match begin/end line in addition to begin/end text (default false) - * s let . match \n (default false) - * U ungreedy: swap meaning of x* and x*?, x+ and x+?, etc (default false) - * ``` - * - * Empty strings: - * - * ``` - * ^ at beginning of text or line (flag m=true) +namespace store { + /** + * Store defines a concurrent safe in memory key-value data store. + */ + interface Store { + } + interface Store { + /** + * Reset clears the store and replaces the store data with a + * shallow copy of the provided newData. + */ + reset(newData: _TygojaDict): void + } + interface Store { + /** + * Length returns the current number of elements in the store. + */ + length(): number + } + interface Store { + /** + * RemoveAll removes all the existing store entries. + */ + removeAll(): void + } + interface Store { + /** + * Remove removes a single entry from the store. + * + * Remove does nothing if key doesn't exist in the store. + */ + remove(key: K): void + } + interface Store { + /** + * Has checks if element with the specified key exist or not. + */ + has(key: K): boolean + } + interface Store { + /** + * Get returns a single element value from the store. + * + * If key is not set, the zero T value is returned. + */ + get(key: K): T + } + interface Store { + /** + * GetOk is similar to Get but returns also a boolean indicating whether the key exists or not. + */ + getOk(key: K): [T, boolean] + } + interface Store { + /** + * GetAll returns a shallow copy of the current store data. + */ + getAll(): _TygojaDict + } + interface Store { + /** + * Keys returns a slice with all of the store keys. + */ + keys(): Array + } + interface Store { + /** + * Values returns a slice with all of the store values. + */ + values(): Array + } + interface Store { + /** + * Set sets (or overwrite if already exists) a new value for key. + */ + set(key: K, value: T): void + } + interface Store { + /** + * SetFunc sets (or overwrite if already exists) a new value resolved + * from the function callback for the provided key. + * + * The function callback receives as argument the old store element value (if exists). + * If there is no old store element, the argument will be the T zero value. + * + * Example: + * + * ``` + * s := store.New[string, int](nil) + * s.SetFunc("count", func(old int) int { + * return old + 1 + * }) + * ``` + */ + setFunc(key: K, fn: (old: T) => T): void + } + interface Store { + /** + * GetOrSet retrieves a single existing value for the provided key + * or stores a new one if it doesn't exist. + */ + getOrSet(key: K, setFunc: () => T): T + } + interface Store { + /** + * SetIfLessThanLimit sets (or overwrite if already exist) a new value for key. + * + * This method is similar to Set() but **it will skip adding new elements** + * to the store if the store length has reached the specified limit. + * false is returned if maxAllowedElements limit is reached. + */ + setIfLessThanLimit(key: K, value: T, maxAllowedElements: number): boolean + } + interface Store { + /** + * UnmarshalJSON implements [json.Unmarshaler] and imports the + * provided JSON data into the store. + * + * The store entries that match with the ones from the data will be overwritten with the new value. + */ + unmarshalJSON(data: string|Array): void + } + interface Store { + /** + * MarshalJSON implements [json.Marshaler] and export the current + * store data into valid JSON. + */ + marshalJSON(): string|Array + } +} + +/** + * Package syntax parses regular expressions into parse trees and compiles + * parse trees into programs. Most clients of regular expressions will use the + * facilities of package [regexp] (such as [regexp.Compile] and [regexp.Match]) instead of this package. + * + * # Syntax + * + * The regular expression syntax understood by this package when parsing with the [Perl] flag is as follows. + * Parts of the syntax can be disabled by passing alternate flags to [Parse]. + * + * Single characters: + * + * ``` + * . any character, possibly including newline (flag s=true) + * [xyz] character class + * [^xyz] negated character class + * \d Perl character class + * \D negated Perl character class + * [[:alpha:]] ASCII character class + * [[:^alpha:]] negated ASCII character class + * \pN Unicode character class (one-letter name) + * \p{Greek} Unicode character class + * \PN negated Unicode character class (one-letter name) + * \P{Greek} negated Unicode character class + * ``` + * + * Composites: + * + * ``` + * xy x followed by y + * x|y x or y (prefer x) + * ``` + * + * Repetitions: + * + * ``` + * x* zero or more x, prefer more + * x+ one or more x, prefer more + * x? zero or one x, prefer one + * x{n,m} n or n+1 or ... or m x, prefer more + * x{n,} n or more x, prefer more + * x{n} exactly n x + * x*? zero or more x, prefer fewer + * x+? one or more x, prefer fewer + * x?? zero or one x, prefer zero + * x{n,m}? n or n+1 or ... or m x, prefer fewer + * x{n,}? n or more x, prefer fewer + * x{n}? exactly n x + * ``` + * + * Implementation restriction: The counting forms x{n,m}, x{n,}, and x{n} + * reject forms that create a minimum or maximum repetition count above 1000. + * Unlimited repetitions are not subject to this restriction. + * + * Grouping: + * + * ``` + * (re) numbered capturing group (submatch) + * (?Pre) named & numbered capturing group (submatch) + * (?re) named & numbered capturing group (submatch) + * (?:re) non-capturing group + * (?flags) set flags within current group; non-capturing + * (?flags:re) set flags during re; non-capturing + * + * Flag syntax is xyz (set) or -xyz (clear) or xy-z (set xy, clear z). The flags are: + * + * i case-insensitive (default false) + * m multi-line mode: ^ and $ match begin/end line in addition to begin/end text (default false) + * s let . match \n (default false) + * U ungreedy: swap meaning of x* and x*?, x+ and x+?, etc (default false) + * ``` + * + * Empty strings: + * + * ``` + * ^ at beginning of text or line (flag m=true) * $ at end of text (like \z not \Z) or line (flag m=true) * \A at beginning of text * \b at ASCII word boundary (\w on one side and \W, \A, or \z on the other) @@ -16998,21 +17051,6 @@ namespace context { } } -/** - * Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer - * object, creating another object (Reader or Writer) that also implements - * the interface but provides buffering and some help for textual I/O. - */ -namespace bufio { - /** - * ReadWriter stores pointers to a [Reader] and a [Writer]. - * It implements [io.ReadWriter]. - */ - type _skWqRsr = Reader&Writer - interface ReadWriter extends _skWqRsr { - } -} - /** * Package net provides a portable interface for network I/O, including * TCP/IP, UDP, domain name resolution, and Unix domain sockets. @@ -17211,3100 +17249,3001 @@ namespace net { } /** - * Package multipart implements MIME multipart parsing, as defined in RFC - * 2046. - * - * The implementation is sufficient for HTTP (RFC 2388) and the multipart - * bodies generated by popular browsers. - * - * # Limits - * - * To protect against malicious inputs, this package sets limits on the size - * of the MIME data it processes. - * - * [Reader.NextPart] and [Reader.NextRawPart] limit the number of headers in a - * part to 10000 and [Reader.ReadForm] limits the total number of headers in all - * FileHeaders to 10000. - * These limits may be adjusted with the GODEBUG=multipartmaxheaders= - * setting. + * Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html * - * Reader.ReadForm further limits the number of parts in a form to 1000. - * This limit may be adjusted with the GODEBUG=multipartmaxparts= - * setting. + * See README.md for more info. */ -namespace multipart { +namespace jwt { /** - * A FileHeader describes a file part of a multipart request. + * MapClaims is a claims type that uses the map[string]any for JSON + * decoding. This is the default claims type if you don't supply one */ - interface FileHeader { - filename: string - header: textproto.MIMEHeader - size: number - } - interface FileHeader { + interface MapClaims extends _TygojaDict{} + interface MapClaims { /** - * Open opens and returns the [FileHeader]'s associated File. + * GetExpirationTime implements the Claims interface. */ - open(): File + getExpirationTime(): (NumericDate) + } + interface MapClaims { + /** + * GetNotBefore implements the Claims interface. + */ + getNotBefore(): (NumericDate) + } + interface MapClaims { + /** + * GetIssuedAt implements the Claims interface. + */ + getIssuedAt(): (NumericDate) + } + interface MapClaims { + /** + * GetAudience implements the Claims interface. + */ + getAudience(): ClaimStrings + } + interface MapClaims { + /** + * GetIssuer implements the Claims interface. + */ + getIssuer(): string + } + interface MapClaims { + /** + * GetSubject implements the Claims interface. + */ + getSubject(): string } } -/** - * Package http provides HTTP client and server implementations. - * - * [Get], [Head], [Post], and [PostForm] make HTTP (or HTTPS) requests: - * - * ``` - * resp, err := http.Get("http://example.com/") - * ... - * resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf) - * ... - * resp, err := http.PostForm("http://example.com/form", - * url.Values{"key": {"Value"}, "id": {"123"}}) - * ``` - * - * The caller must close the response body when finished with it: - * - * ``` - * resp, err := http.Get("http://example.com/") - * if err != nil { - * // handle error - * } - * defer resp.Body.Close() - * body, err := io.ReadAll(resp.Body) - * // ... - * ``` - * - * # Clients and Transports - * - * For control over HTTP client headers, redirect policy, and other - * settings, create a [Client]: - * - * ``` - * client := &http.Client{ - * CheckRedirect: redirectPolicyFunc, - * } - * - * resp, err := client.Get("http://example.com") - * // ... - * - * req, err := http.NewRequest("GET", "http://example.com", nil) - * // ... - * req.Header.Add("If-None-Match", `W/"wyzzy"`) - * resp, err := client.Do(req) - * // ... - * ``` - * - * For control over proxies, TLS configuration, keep-alives, - * compression, and other settings, create a [Transport]: - * - * ``` - * tr := &http.Transport{ - * MaxIdleConns: 10, - * IdleConnTimeout: 30 * time.Second, - * DisableCompression: true, - * } - * client := &http.Client{Transport: tr} - * resp, err := client.Get("https://example.com") - * ``` - * - * Clients and Transports are safe for concurrent use by multiple - * goroutines and for efficiency should only be created once and re-used. - * - * # Servers - * - * ListenAndServe starts an HTTP server with a given address and handler. - * The handler is usually nil, which means to use [DefaultServeMux]. - * [Handle] and [HandleFunc] add handlers to [DefaultServeMux]: - * - * ``` - * http.Handle("/foo", fooHandler) - * - * http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) { - * fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) - * }) - * - * log.Fatal(http.ListenAndServe(":8080", nil)) - * ``` - * - * More control over the server's behavior is available by creating a - * custom Server: - * - * ``` - * s := &http.Server{ - * Addr: ":8080", - * Handler: myHandler, - * ReadTimeout: 10 * time.Second, - * WriteTimeout: 10 * time.Second, - * MaxHeaderBytes: 1 << 20, - * } - * log.Fatal(s.ListenAndServe()) - * ``` - * - * # HTTP/2 - * - * The http package has transparent support for the HTTP/2 protocol. - * - * [Server] and [DefaultTransport] automatically enable HTTP/2 support - * when using HTTPS. [Transport] does not enable HTTP/2 by default. - * - * To enable or disable support for HTTP/1, HTTP/2, and/or unencrypted HTTP/2, - * see the [Server.Protocols] and [Transport.Protocols] configuration fields. - * - * To configure advanced HTTP/2 features, see the [Server.HTTP2] and - * [Transport.HTTP2] configuration fields. - * - * Alternatively, the following GODEBUG settings are currently supported: - * - * ``` - * GODEBUG=http2client=0 # disable HTTP/2 client support - * GODEBUG=http2server=0 # disable HTTP/2 server support - * GODEBUG=http2debug=1 # enable verbose HTTP/2 debug logs - * GODEBUG=http2debug=2 # ... even more verbose, with frame dumps - * ``` - * - * The "omithttp2" build tag may be used to disable the HTTP/2 implementation - * contained in the http package. - */ -namespace http { +namespace hook { /** - * PushOptions describes options for [Pusher.Push]. + * Event implements [Resolver] and it is intended to be used as a base + * Hook event that you can embed in your custom typed event structs. + * + * Example: + * + * ``` + * type CustomEvent struct { + * hook.Event + * + * SomeField int + * } + * ``` */ - interface PushOptions { - /** - * Method specifies the HTTP method for the promised request. - * If set, it must be "GET" or "HEAD". Empty means "GET". - */ - method: string + interface Event { + } + interface Event { /** - * Header specifies additional promised request headers. This cannot - * include HTTP/2 pseudo header fields like ":path" and ":scheme", - * which will be added automatically. + * Next calls the next hook handler. */ - header: Header + next(): void } - // @ts-ignore - import urlpkg = url /** - * A Request represents an HTTP request received by a server - * or to be sent by a client. - * - * The field semantics differ slightly between client and server - * usage. In addition to the notes on the fields below, see the - * documentation for [Request.Write] and [RoundTripper]. + * Handler defines a single Hook handler. + * Multiple handlers can share the same id. + * If Id is not explicitly set it will be autogenerated by Hook.Add and Hook.AddHandler. */ - interface Request { + interface Handler { /** - * Method specifies the HTTP method (GET, POST, PUT, etc.). - * For client requests, an empty string means GET. + * Func defines the handler function to execute. + * + * Note that users need to call e.Next() in order to proceed with + * the execution of the hook chain. */ - method: string + func: (_arg0: T) => void /** - * URL specifies either the URI being requested (for server - * requests) or the URL to access (for client requests). + * Id is the unique identifier of the handler. * - * For server requests, the URL is parsed from the URI - * supplied on the Request-Line as stored in RequestURI. For - * most requests, fields other than Path and RawQuery will be - * empty. (See RFC 7230, Section 5.3) + * It could be used later to remove the handler from a hook via [Hook.Remove]. * - * For client requests, the URL's Host specifies the server to - * connect to, while the Request's Host field optionally - * specifies the Host header value to send in the HTTP - * request. + * If missing, an autogenerated value will be assigned when adding + * the handler to a hook. */ - url?: url.URL + id: string /** - * The protocol version for incoming server requests. + * Priority allows changing the default exec priority of the handler within a hook. * - * For client requests, these fields are ignored. The HTTP - * client code always uses either HTTP/1.1 or HTTP/2. - * See the docs on Transport for details. + * If 0, the handler will be executed in the same order it was registered. */ - proto: string // "HTTP/1.0" - protoMajor: number // 1 - protoMinor: number // 0 + priority: number + } + /** + * Hook defines a generic concurrent safe structure for managing event hooks. + * + * When using custom event it must embed the base [hook.Event]. + * + * Example: + * + * ``` + * type CustomEvent struct { + * hook.Event + * SomeField int + * } + * + * h := Hook[*CustomEvent]{} + * + * h.BindFunc(func(e *CustomEvent) error { + * println(e.SomeField) + * + * return e.Next() + * }) + * + * h.Trigger(&CustomEvent{ SomeField: 123 }) + * ``` + */ + interface Hook { + } + interface Hook { /** - * Header contains the request header fields either received - * by the server or to be sent by the client. - * - * If a server received a request with header lines, - * - * ``` - * Host: example.com - * accept-encoding: gzip, deflate - * Accept-Language: en-us - * fOO: Bar - * foo: two - * ``` - * - * then - * - * ``` - * Header = map[string][]string{ - * "Accept-Encoding": {"gzip, deflate"}, - * "Accept-Language": {"en-us"}, - * "Foo": {"Bar", "two"}, - * } - * ``` - * - * For incoming requests, the Host header is promoted to the - * Request.Host field and removed from the Header map. + * Bind registers the provided handler to the current hooks queue. * - * HTTP defines that header names are case-insensitive. The - * request parser implements this by using CanonicalHeaderKey, - * making the first character and any characters following a - * hyphen uppercase and the rest lowercase. + * If handler.Id is empty it is updated with autogenerated value. * - * For client requests, certain headers such as Content-Length - * and Connection are automatically written when needed and - * values in Header may be ignored. See the documentation - * for the Request.Write method. + * If a handler from the current hook list has Id matching handler.Id + * then the old handler is replaced with the new one. */ - header: Header + bind(handler: Handler): string + } + interface Hook { /** - * Body is the request's body. - * - * For client requests, a nil body means the request has no - * body, such as a GET request. The HTTP Client's Transport - * is responsible for calling the Close method. + * BindFunc is similar to Bind but registers a new handler from just the provided function. * - * For server requests, the Request Body is always non-nil - * but will return EOF immediately when no body is present. - * The Server will close the request body. The ServeHTTP - * Handler does not need to. + * The registered handler is added with a default 0 priority and the id will be autogenerated. * - * Body must allow Read to be called concurrently with Close. - * In particular, calling Close should unblock a Read waiting - * for input. + * If you want to register a handler with custom priority or id use the [Hook.Bind] method. */ - body: io.ReadCloser + bindFunc(fn: (e: T) => void): string + } + interface Hook { /** - * GetBody defines an optional func to return a new copy of - * Body. It is used for client requests when a redirect requires - * reading the body more than once. Use of GetBody still - * requires setting Body. - * - * For server requests, it is unused. + * Unbind removes one or many hook handler by their id. */ - getBody: () => io.ReadCloser + unbind(...idsToRemove: string[]): void + } + interface Hook { /** - * ContentLength records the length of the associated content. - * The value -1 indicates that the length is unknown. - * Values >= 0 indicate that the given number of bytes may - * be read from Body. - * - * For client requests, a value of 0 with a non-nil Body is - * also treated as unknown. + * UnbindAll removes all registered handlers. */ - contentLength: number + unbindAll(): void + } + interface Hook { /** - * TransferEncoding lists the transfer encodings from outermost to - * innermost. An empty list denotes the "identity" encoding. - * TransferEncoding can usually be ignored; chunked encoding is - * automatically added and removed as necessary when sending and - * receiving requests. + * Length returns to total number of registered hook handlers. */ - transferEncoding: Array + length(): number + } + interface Hook { /** - * Close indicates whether to close the connection after - * replying to this request (for servers) or after sending this - * request and reading its response (for clients). + * Trigger executes all registered hook handlers one by one + * with the specified event as an argument. * - * For server requests, the HTTP server handles this automatically - * and this field is not needed by Handlers. + * Optionally, this method allows also to register additional one off + * handler funcs that will be temporary appended to the handlers queue. * - * For client requests, setting this field prevents re-use of - * TCP connections between requests to the same hosts, as if - * Transport.DisableKeepAlives were set. + * NB! Each hook handler must call event.Next() in order the hook chain to proceed. */ - close: boolean + trigger(event: T, ...oneOffHandlerFuncs: ((_arg0: T) => void)[]): void + } + /** + * TaggedHook defines a proxy hook which register handlers that are triggered only + * if the TaggedHook.tags are empty or includes at least one of the event data tag(s). + */ + type _soDsJcD = mainHook + interface TaggedHook extends _soDsJcD { + } + interface TaggedHook { /** - * For server requests, Host specifies the host on which the - * URL is sought. For HTTP/1 (per RFC 7230, section 5.4), this - * is either the value of the "Host" header or the host name - * given in the URL itself. For HTTP/2, it is the value of the - * ":authority" pseudo-header field. - * It may be of the form "host:port". For international domain - * names, Host may be in Punycode or Unicode form. Use - * golang.org/x/net/idna to convert it to either format if - * needed. - * To prevent DNS rebinding attacks, server Handlers should - * validate that the Host header has a value for which the - * Handler considers itself authoritative. The included - * ServeMux supports patterns registered to particular host - * names and thus protects its registered Handlers. + * CanTriggerOn checks if the current TaggedHook can be triggered with + * the provided event data tags. * - * For client requests, Host optionally overrides the Host - * header to send. If empty, the Request.Write method uses - * the value of URL.Host. Host may contain an international - * domain name. + * It returns always true if the hook doesn't have any tags. */ - host: string + canTriggerOn(tagsToCheck: Array): boolean + } + interface TaggedHook { /** - * Form contains the parsed form data, including both the URL - * field's query parameters and the PATCH, POST, or PUT form data. - * This field is only available after ParseForm is called. - * The HTTP client ignores Form and uses Body instead. + * Bind registers the provided handler to the current hooks queue. + * + * It is similar to [Hook.Bind] with the difference that the handler + * function is invoked only if the event data tags satisfy h.CanTriggerOn. */ - form: url.Values + bind(handler: Handler): string + } + interface TaggedHook { /** - * PostForm contains the parsed form data from PATCH, POST - * or PUT body parameters. + * BindFunc registers a new handler with the specified function. * - * This field is only available after ParseForm is called. - * The HTTP client ignores PostForm and uses Body instead. + * It is similar to [Hook.Bind] with the difference that the handler + * function is invoked only if the event data tags satisfy h.CanTriggerOn. */ - postForm: url.Values + bindFunc(fn: (e: T) => void): string + } +} + +/** + * Package types implements some commonly used db serializable types + * like datetime, json, etc. + */ +namespace types { + /** + * DateTime represents a [time.Time] instance in UTC that is wrapped + * and serialized using the app default date layout. + */ + interface DateTime { + } + interface DateTime { /** - * MultipartForm is the parsed multipart form, including file uploads. - * This field is only available after ParseMultipartForm is called. - * The HTTP client ignores MultipartForm and uses Body instead. + * Time returns the internal [time.Time] instance. */ - multipartForm?: multipart.Form + time(): time.Time + } + interface DateTime { /** - * Trailer specifies additional headers that are sent after the request - * body. - * - * For server requests, the Trailer map initially contains only the - * trailer keys, with nil values. (The client declares which trailers it - * will later send.) While the handler is reading from Body, it must - * not reference Trailer. After reading from Body returns EOF, Trailer - * can be read again and will contain non-nil values, if they were sent - * by the client. - * - * For client requests, Trailer must be initialized to a map containing - * the trailer keys to later send. The values may be nil or their final - * values. The ContentLength must be 0 or -1, to send a chunked request. - * After the HTTP request is sent the map values can be updated while - * the request body is read. Once the body returns EOF, the caller must - * not mutate Trailer. - * - * Writing a request whose Trailer contains a key with invalid bytes - * (such as CR or LF), or such a value present when Write begins, - * returns an error. + * Add returns a new DateTime based on the current DateTime + the specified duration. + */ + add(duration: time.Duration): DateTime + } + interface DateTime { + /** + * Sub returns a [time.Duration] by subtracting the specified DateTime from the current one. * - * Few HTTP clients, servers, or proxies support HTTP trailers. + * If the result exceeds the maximum (or minimum) value that can be stored in a [time.Duration], + * the maximum (or minimum) duration will be returned. */ - trailer: Header + sub(u: DateTime): time.Duration + } + interface DateTime { /** - * RemoteAddr allows HTTP servers and other software to record - * the network address that sent the request, usually for - * logging. This field is not filled in by ReadRequest and - * has no defined format. The HTTP server in this package - * sets RemoteAddr to an "IP:port" address before invoking a - * handler. - * This field is ignored by the HTTP client. + * AddDate returns a new DateTime based on the current one + duration. + * + * It follows the same rules as [time.AddDate]. */ - remoteAddr: string + addDate(years: number, months: number, days: number): DateTime + } + interface DateTime { /** - * RequestURI is the unmodified request-target of the - * Request-Line (RFC 7230, Section 3.1.1) as sent by the client - * to a server. Usually the URL field should be used instead. - * It is an error to set this field in an HTTP client request. + * After reports whether the current DateTime instance is after u. */ - requestURI: string + after(u: DateTime): boolean + } + interface DateTime { /** - * TLS allows HTTP servers and other software to record - * information about the TLS connection on which the request - * was received. This field is not filled in by ReadRequest. - * The HTTP server in this package sets the field for - * TLS-enabled connections before invoking a handler; - * otherwise it leaves the field nil. - * This field is ignored by the HTTP client. + * Before reports whether the current DateTime instance is before u. */ - tls?: any + before(u: DateTime): boolean + } + interface DateTime { /** - * Cancel is an optional channel whose closure indicates that the client - * request should be regarded as canceled. Not all implementations of - * RoundTripper may support Cancel. - * - * For server requests, this field is not applicable. - * - * Deprecated: Set the Request's context with NewRequestWithContext - * instead. If a Request's Cancel field and context are both - * set, it is undefined whether Cancel is respected. + * Compare compares the current DateTime instance with u. + * If the current instance is before u, it returns -1. + * If the current instance is after u, it returns +1. + * If they're the same, it returns 0. */ - cancel: undefined + compare(u: DateTime): number + } + interface DateTime { /** - * Response is the redirect response which caused this request - * to be created. This field is only populated during client - * redirects. + * Equal reports whether the current DateTime and u represent the same time instant. + * Two DateTime can be equal even if they are in different locations. + * For example, 6:00 +0200 and 4:00 UTC are Equal. */ - response?: Response + equal(u: DateTime): boolean + } + interface DateTime { /** - * Pattern is the [ServeMux] pattern that matched the request. - * It is empty if the request was not matched against a pattern. + * Unix returns the current DateTime as a Unix time, aka. + * the number of seconds elapsed since January 1, 1970 UTC. */ - pattern: string + unix(): number } - interface Request { + interface DateTime { /** - * Context returns the request's context. To change the context, use - * [Request.Clone] or [Request.WithContext]. - * - * The returned context is always non-nil; it defaults to the - * background context. - * - * For outgoing client requests, the context controls cancellation. - * - * For incoming server requests, the context is canceled when the - * client's connection closes, the request is canceled (with HTTP/2), - * or when the ServeHTTP method returns. + * IsZero checks whether the current DateTime instance has zero time value. */ - context(): context.Context + isZero(): boolean } - interface Request { + interface DateTime { /** - * WithContext returns a shallow copy of r with its context changed - * to ctx. The provided ctx must be non-nil. - * - * For outgoing client request, the context controls the entire - * lifetime of a request and its response: obtaining a connection, - * sending the request, and reading the response headers and body. + * String serializes the current DateTime instance into a formatted + * UTC date string. * - * To create a new request with a context, use [NewRequestWithContext]. - * To make a deep copy of a request with a new context, use [Request.Clone]. + * The zero value is serialized to an empty string. */ - withContext(ctx: context.Context): (Request) + string(): string } - interface Request { + interface DateTime { /** - * Clone returns a deep copy of r with its context changed to ctx. - * The provided ctx must be non-nil. - * - * Clone only makes a shallow copy of the Body field. - * - * For an outgoing client request, the context controls the entire - * lifetime of a request and its response: obtaining a connection, - * sending the request, and reading the response headers and body. + * MarshalJSON implements the [json.Marshaler] interface. */ - clone(ctx: context.Context): (Request) + marshalJSON(): string|Array } - interface Request { + interface DateTime { /** - * ProtoAtLeast reports whether the HTTP protocol used - * in the request is at least major.minor. + * UnmarshalJSON implements the [json.Unmarshaler] interface. */ - protoAtLeast(major: number, minor: number): boolean + unmarshalJSON(b: string|Array): void } - interface Request { + interface DateTime { /** - * UserAgent returns the client's User-Agent, if sent in the request. + * Value implements the [driver.Valuer] interface. */ - userAgent(): string + value(): any } - interface Request { + interface DateTime { /** - * Cookies parses and returns the HTTP cookies sent with the request. + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current DateTime instance. */ - cookies(): Array<(Cookie | undefined)> + scan(value: any): void } - interface Request { + /** + * GeoPoint defines a struct for storing geo coordinates as serialized json object + * (e.g. {lon:0,lat:0}). + * + * Note: using object notation and not a plain array to avoid the confusion + * as there doesn't seem to be a fixed standard for the coordinates order. + */ + interface GeoPoint { + lon: number + lat: number + } + interface GeoPoint { /** - * CookiesNamed parses and returns the named HTTP cookies sent with the request - * or an empty slice if none matched. + * String returns the string representation of the current GeoPoint instance. */ - cookiesNamed(name: string): Array<(Cookie | undefined)> + string(): string } - interface Request { + interface GeoPoint { /** - * Cookie returns the named cookie provided in the request or - * [ErrNoCookie] if not found. - * If multiple cookies match the given name, only one cookie will - * be returned. + * AsMap implements [core.mapExtractor] and returns a value suitable + * to be used in an API rule expression. */ - cookie(name: string): (Cookie) + asMap(): _TygojaDict } - interface Request { + interface GeoPoint { /** - * AddCookie adds a cookie to the request. Per RFC 6265 section 5.4, - * AddCookie does not attach more than one [Cookie] header field. That - * means all cookies, if any, are written into the same line, - * separated by semicolon. - * AddCookie only sanitizes c's name and value, and does not sanitize - * a Cookie header already present in the request. + * Value implements the [driver.Valuer] interface. */ - addCookie(c: Cookie): void + value(): any } - interface Request { + interface GeoPoint { /** - * Referer returns the referring URL, if sent in the request. + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current GeoPoint instance. * - * Referer is misspelled as in the request itself, a mistake from the - * earliest days of HTTP. This value can also be fetched from the - * [Header] map as Header["Referer"]; the benefit of making it available - * as a method is that the compiler can diagnose programs that use the - * alternate (correct English) spelling req.Referrer() but cannot - * diagnose programs that use Header["Referrer"]. + * The value argument could be nil (no-op), another GeoPoint instance, + * map or serialized json object with lat-lon props. */ - referer(): string + scan(value: any): void } - interface Request { + /** + * JSONArray defines a slice that is safe for json and db read/write. + */ + interface JSONArray extends Array{} + interface JSONArray { /** - * MultipartReader returns a MIME multipart reader if this is a - * multipart/form-data or a multipart/mixed POST request, else returns nil and an error. - * Use this function instead of [Request.ParseMultipartForm] to - * process the request body as a stream. + * MarshalJSON implements the [json.Marshaler] interface. */ - multipartReader(): (multipart.Reader) + marshalJSON(): string|Array } - interface Request { + interface JSONArray { /** - * Write writes an HTTP/1.1 request, which is the header and body, in wire format. - * This method consults the following fields of the request: - * - * ``` - * Host - * URL - * Method (defaults to "GET") - * Header - * ContentLength - * TransferEncoding - * Body - * ``` - * - * If Body is present, Content-Length is <= 0 and [Request.TransferEncoding] - * hasn't been set to "identity", Write adds "Transfer-Encoding: - * chunked" to the header. Body is closed after it is sent. - * - * Header values for Host, Content-Length, Transfer-Encoding, - * and Trailer are not used; these are derived from other Request fields. - * If the Header does not contain a User-Agent value, Write uses - * "Go-http-client/1.1". + * String returns the string representation of the current json array. */ - write(w: io.Writer): void + string(): string } - interface Request { + interface JSONArray { /** - * WriteProxy is like [Request.Write] but writes the request in the form - * expected by an HTTP proxy. In particular, [Request.WriteProxy] writes the - * initial Request-URI line of the request with an absolute URI, per - * section 5.3 of RFC 7230, including the scheme and host. - * In either case, WriteProxy also writes a Host header, using - * either r.Host or r.URL.Host. + * Value implements the [driver.Valuer] interface. */ - writeProxy(w: io.Writer): void + value(): any } - interface Request { + interface JSONArray { /** - * BasicAuth returns the username and password provided in the request's - * Authorization header, if the request uses HTTP Basic Authentication. - * See RFC 2617, Section 2. + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current JSONArray[T] instance. */ - basicAuth(): [string, string, boolean] + scan(value: any): void } - interface Request { + /** + * JSONMap defines a map that is safe for json and db read/write. + */ + interface JSONMap extends _TygojaDict{} + interface JSONMap { /** - * SetBasicAuth sets the request's Authorization header to use HTTP - * Basic Authentication with the provided username and password. - * - * With HTTP Basic Authentication the provided username and password - * are not encrypted. It should generally only be used in an HTTPS - * request. + * Get retrieves a single value from the current JSONMap[T]. * - * The username may not contain a colon. Some protocols may impose - * additional requirements on pre-escaping the username and - * password. For instance, when used with OAuth2, both arguments must - * be URL encoded first with [url.QueryEscape]. + * This helper was added primarily to assist the goja integration since custom map types + * don't have direct access to the map keys (https://pkg.go.dev/github.com/dop251/goja#hdr-Maps_with_methods). */ - setBasicAuth(username: string, password: string): void + get(key: string): T } - interface Request { + interface JSONMap { /** - * ParseForm populates r.Form and r.PostForm. - * - * For all requests, ParseForm parses the raw query from the URL and updates - * r.Form. - * - * For POST, PUT, and PATCH requests, it also reads the request body, parses it - * as a form and puts the results into both r.PostForm and r.Form. Request body - * parameters take precedence over URL query string values in r.Form. - * - * If the request Body's size has not already been limited by [MaxBytesReader], - * the size is capped at 10MB. - * - * For other HTTP methods, or when the Content-Type is not - * application/x-www-form-urlencoded, the request Body is not read, and - * r.PostForm is initialized to a non-nil, empty value. + * Set sets a single value in the current JSONMap[T]. * - * [Request.ParseMultipartForm] calls ParseForm automatically. - * ParseForm is idempotent. + * This helper was added primarily to assist the goja integration since custom map types + * don't have direct access to the map keys (https://pkg.go.dev/github.com/dop251/goja#hdr-Maps_with_methods). */ - parseForm(): void + set(key: string, value: T): void } - interface Request { + interface JSONMap { /** - * ParseMultipartForm parses a request body as multipart/form-data. - * The whole request body is parsed and up to a total of maxMemory bytes of - * its file parts are stored in memory, with the remainder stored on - * disk in temporary files. - * ParseMultipartForm calls [Request.ParseForm] if necessary. - * If ParseForm returns an error, ParseMultipartForm returns it but also - * continues parsing the request body. - * After one call to ParseMultipartForm, subsequent calls have no effect. + * MarshalJSON implements the [json.Marshaler] interface. */ - parseMultipartForm(maxMemory: number): void + marshalJSON(): string|Array } - interface Request { + interface JSONMap { /** - * FormValue returns the first value for the named component of the query. - * The precedence order: - * 1. application/x-www-form-urlencoded form body (POST, PUT, PATCH only) - * 2. query parameters (always) - * 3. multipart/form-data form body (always) - * - * FormValue calls [Request.ParseMultipartForm] and [Request.ParseForm] - * if necessary and ignores any errors returned by these functions. - * If key is not present, FormValue returns the empty string. - * To access multiple values of the same key, call ParseForm and - * then inspect [Request.Form] directly. + * String returns the string representation of the current json map. */ - formValue(key: string): string + string(): string } - interface Request { + interface JSONMap { /** - * PostFormValue returns the first value for the named component of the POST, - * PUT, or PATCH request body. URL query parameters are ignored. - * PostFormValue calls [Request.ParseMultipartForm] and [Request.ParseForm] if necessary and ignores - * any errors returned by these functions. - * If key is not present, PostFormValue returns the empty string. + * Value implements the [driver.Valuer] interface. */ - postFormValue(key: string): string + value(): any } - interface Request { + interface JSONMap { /** - * FormFile returns the first file for the provided form key. - * FormFile calls [Request.ParseMultipartForm] and [Request.ParseForm] if necessary. + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current JSONMap[T] instance. */ - formFile(key: string): [multipart.File, (multipart.FileHeader)] + scan(value: any): void } - interface Request { + /** + * JSONRaw defines a json value type that is safe for db read/write. + */ + interface JSONRaw extends Array{} + interface JSONRaw { /** - * PathValue returns the value for the named path wildcard in the [ServeMux] pattern - * that matched the request. - * It returns the empty string if the request was not matched against a pattern - * or there is no such wildcard in the pattern. - * - * The value is unescaped. For example, if the pattern "/b/{bucket}" matches - * the path "/b/a%2fb", PathValue("bucket") returns "a/b". + * String returns the current JSONRaw instance as a json encoded string. */ - pathValue(name: string): string + string(): string } - interface Request { + interface JSONRaw { /** - * SetPathValue sets name to value, so that subsequent calls to r.PathValue(name) - * return value. - * It does not unescape value. + * MarshalJSON implements the [json.Marshaler] interface. */ - setPathValue(name: string, value: string): void - } - /** - * A Handler responds to an HTTP request. - * - * [Handler.ServeHTTP] should write reply headers and data to the [ResponseWriter] - * and then return. Returning signals that the request is finished; it - * is not valid to use the [ResponseWriter] or read from the - * [Request.Body] after or concurrently with the completion of the - * ServeHTTP call. - * - * Depending on the HTTP client software, HTTP protocol version, and - * any intermediaries between the client and the Go server, it may not - * be possible to read from the [Request.Body] after writing to the - * [ResponseWriter]. Cautious handlers should read the [Request.Body] - * first, and then reply. - * - * Except for reading the body, handlers should not modify the - * provided Request. - * - * If ServeHTTP panics, the server (the caller of ServeHTTP) assumes - * that the effect of the panic was isolated to the active request. - * It recovers the panic, logs a stack trace to the server error log, - * and either closes the network connection or sends an HTTP/2 - * RST_STREAM, depending on the HTTP protocol. To abort a handler so - * the client sees an interrupted response but the server doesn't log - * an error, panic with the value [ErrAbortHandler]. - */ - interface Handler { - [key:string]: any; - serveHTTP(_arg0: ResponseWriter, _arg1: Request): void + marshalJSON(): string|Array } - /** - * A ResponseWriter interface is used by an HTTP handler to - * construct an HTTP response. - * - * A ResponseWriter may not be used after [Handler.ServeHTTP] has returned. - */ - interface ResponseWriter { - [key:string]: any; + interface JSONRaw { /** - * Header returns the header map that will be sent by - * [ResponseWriter.WriteHeader]. The [Header] map also is the mechanism with which - * [Handler] implementations can set HTTP trailers. - * - * Changing the header map after a call to [ResponseWriter.WriteHeader] (or - * [ResponseWriter.Write]) has no effect unless the HTTP status code was of the - * 1xx class or the modified headers are trailers. - * - * There are two ways to set Trailers. The preferred way is to - * predeclare in the headers which trailers you will later - * send by setting the "Trailer" header to the names of the - * trailer keys which will come later. In this case, those - * keys of the Header map are treated as if they were - * trailers. See the example. The second way, for trailer - * keys not known to the [Handler] until after the first [ResponseWriter.Write], - * is to prefix the [Header] map keys with the [TrailerPrefix] - * constant value. - * - * To suppress automatic response headers (such as "Date"), set - * their value to nil. + * UnmarshalJSON implements the [json.Unmarshaler] interface. */ - header(): Header + unmarshalJSON(b: string|Array): void + } + interface JSONRaw { /** - * Write writes the data to the connection as part of an HTTP reply. - * - * If [ResponseWriter.WriteHeader] has not yet been called, Write calls - * WriteHeader(http.StatusOK) before writing the data. If the Header - * does not contain a Content-Type line, Write adds a Content-Type set - * to the result of passing the initial 512 bytes of written data to - * [DetectContentType]. Additionally, if the total size of all written - * data is under a few KB and there are no Flush calls, the - * Content-Length header is added automatically. - * - * Depending on the HTTP protocol version and the client, calling - * Write or WriteHeader may prevent future reads on the - * Request.Body. For HTTP/1.x requests, handlers should read any - * needed request body data before writing the response. Once the - * headers have been flushed (due to either an explicit Flusher.Flush - * call or writing enough data to trigger a flush), the request body - * may be unavailable. For HTTP/2 requests, the Go HTTP server permits - * handlers to continue to read the request body while concurrently - * writing the response. However, such behavior may not be supported - * by all HTTP/2 clients. Handlers should read before writing if - * possible to maximize compatibility. + * Value implements the [driver.Valuer] interface. */ - write(_arg0: string|Array): number + value(): any + } + interface JSONRaw { /** - * WriteHeader sends an HTTP response header with the provided - * status code. - * - * If WriteHeader is not called explicitly, the first call to Write - * will trigger an implicit WriteHeader(http.StatusOK). - * Thus explicit calls to WriteHeader are mainly used to - * send error codes or 1xx informational responses. - * - * The provided code must be a valid HTTP 1xx-5xx status code. - * Any number of 1xx headers may be written, followed by at most - * one 2xx-5xx header. 1xx headers are sent immediately, but 2xx-5xx - * headers may be buffered. Use the Flusher interface to send - * buffered data. The header map is cleared when 2xx-5xx headers are - * sent, but not with 1xx headers. - * - * The server will automatically send a 100 (Continue) header - * on the first read from the request body if the request has - * an "Expect: 100-continue" header. + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current JSONRaw instance. */ - writeHeader(statusCode: number): void + scan(value: any): void } +} + +/** + * Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer + * object, creating another object (Reader or Writer) that also implements + * the interface but provides buffering and some help for textual I/O. + */ +namespace bufio { /** - * A Server defines parameters for running an HTTP server. - * The zero value for Server is a valid configuration. + * ReadWriter stores pointers to a [Reader] and a [Writer]. + * It implements [io.ReadWriter]. */ - interface Server { - /** - * Addr optionally specifies the TCP address for the server to listen on, - * in the form "host:port". If empty, ":http" (port 80) is used. - * The service names are defined in RFC 6335 and assigned by IANA. - * See net.Dial for details of the address format. - */ - addr: string - handler: Handler // handler to invoke, http.DefaultServeMux if nil - /** - * DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler, - * otherwise responds with 200 OK and Content-Length: 0. - */ - disableGeneralOptionsHandler: boolean + type _sKQEoxm = Reader&Writer + interface ReadWriter extends _sKQEoxm { + } +} + +/** + * Package multipart implements MIME multipart parsing, as defined in RFC + * 2046. + * + * The implementation is sufficient for HTTP (RFC 2388) and the multipart + * bodies generated by popular browsers. + * + * # Limits + * + * To protect against malicious inputs, this package sets limits on the size + * of the MIME data it processes. + * + * [Reader.NextPart] and [Reader.NextRawPart] limit the number of headers in a + * part to 10000 and [Reader.ReadForm] limits the total number of headers in all + * FileHeaders to 10000. + * These limits may be adjusted with the GODEBUG=multipartmaxheaders= + * setting. + * + * Reader.ReadForm further limits the number of parts in a form to 1000. + * This limit may be adjusted with the GODEBUG=multipartmaxparts= + * setting. + */ +namespace multipart { + /** + * A FileHeader describes a file part of a multipart request. + */ + interface FileHeader { + filename: string + header: textproto.MIMEHeader + size: number + } + interface FileHeader { /** - * TLSConfig optionally provides a TLS configuration for use - * by ServeTLS and ListenAndServeTLS. Note that this value is - * cloned by ServeTLS and ListenAndServeTLS, so it's not - * possible to modify the configuration with methods like - * tls.Config.SetSessionTicketKeys. To use - * SetSessionTicketKeys, use Server.Serve with a TLS Listener - * instead. + * Open opens and returns the [FileHeader]'s associated File. */ - tlsConfig?: any - /** - * ReadTimeout is the maximum duration for reading the entire - * request, including the body. A zero or negative value means - * there will be no timeout. - * - * Because ReadTimeout does not let Handlers make per-request - * decisions on each request body's acceptable deadline or - * upload rate, most users will prefer to use - * ReadHeaderTimeout. It is valid to use them both. - */ - readTimeout: time.Duration - /** - * ReadHeaderTimeout is the amount of time allowed to read - * request headers. The connection's read deadline is reset - * after reading the headers and the Handler can decide what - * is considered too slow for the body. If zero, the value of - * ReadTimeout is used. If negative, or if zero and ReadTimeout - * is zero or negative, there is no timeout. - */ - readHeaderTimeout: time.Duration - /** - * WriteTimeout is the maximum duration before timing out - * writes of the response. It is reset whenever a new - * request's header is read. Like ReadTimeout, it does not - * let Handlers make decisions on a per-request basis. - * A zero or negative value means there will be no timeout. - */ - writeTimeout: time.Duration + open(): File + } +} + +/** + * Package http provides HTTP client and server implementations. + * + * [Get], [Head], [Post], and [PostForm] make HTTP (or HTTPS) requests: + * + * ``` + * resp, err := http.Get("http://example.com/") + * ... + * resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf) + * ... + * resp, err := http.PostForm("http://example.com/form", + * url.Values{"key": {"Value"}, "id": {"123"}}) + * ``` + * + * The caller must close the response body when finished with it: + * + * ``` + * resp, err := http.Get("http://example.com/") + * if err != nil { + * // handle error + * } + * defer resp.Body.Close() + * body, err := io.ReadAll(resp.Body) + * // ... + * ``` + * + * # Clients and Transports + * + * For control over HTTP client headers, redirect policy, and other + * settings, create a [Client]: + * + * ``` + * client := &http.Client{ + * CheckRedirect: redirectPolicyFunc, + * } + * + * resp, err := client.Get("http://example.com") + * // ... + * + * req, err := http.NewRequest("GET", "http://example.com", nil) + * // ... + * req.Header.Add("If-None-Match", `W/"wyzzy"`) + * resp, err := client.Do(req) + * // ... + * ``` + * + * For control over proxies, TLS configuration, keep-alives, + * compression, and other settings, create a [Transport]: + * + * ``` + * tr := &http.Transport{ + * MaxIdleConns: 10, + * IdleConnTimeout: 30 * time.Second, + * DisableCompression: true, + * } + * client := &http.Client{Transport: tr} + * resp, err := client.Get("https://example.com") + * ``` + * + * Clients and Transports are safe for concurrent use by multiple + * goroutines and for efficiency should only be created once and re-used. + * + * # Servers + * + * ListenAndServe starts an HTTP server with a given address and handler. + * The handler is usually nil, which means to use [DefaultServeMux]. + * [Handle] and [HandleFunc] add handlers to [DefaultServeMux]: + * + * ``` + * http.Handle("/foo", fooHandler) + * + * http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) { + * fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) + * }) + * + * log.Fatal(http.ListenAndServe(":8080", nil)) + * ``` + * + * More control over the server's behavior is available by creating a + * custom Server: + * + * ``` + * s := &http.Server{ + * Addr: ":8080", + * Handler: myHandler, + * ReadTimeout: 10 * time.Second, + * WriteTimeout: 10 * time.Second, + * MaxHeaderBytes: 1 << 20, + * } + * log.Fatal(s.ListenAndServe()) + * ``` + * + * # HTTP/2 + * + * The http package has transparent support for the HTTP/2 protocol. + * + * [Server] and [DefaultTransport] automatically enable HTTP/2 support + * when using HTTPS. [Transport] does not enable HTTP/2 by default. + * + * To enable or disable support for HTTP/1, HTTP/2, and/or unencrypted HTTP/2, + * see the [Server.Protocols] and [Transport.Protocols] configuration fields. + * + * To configure advanced HTTP/2 features, see the [Server.HTTP2] and + * [Transport.HTTP2] configuration fields. + * + * Alternatively, the following GODEBUG settings are currently supported: + * + * ``` + * GODEBUG=http2client=0 # disable HTTP/2 client support + * GODEBUG=http2server=0 # disable HTTP/2 server support + * GODEBUG=http2debug=1 # enable verbose HTTP/2 debug logs + * GODEBUG=http2debug=2 # ... even more verbose, with frame dumps + * ``` + * + * The "omithttp2" build tag may be used to disable the HTTP/2 implementation + * contained in the http package. + */ +namespace http { + /** + * PushOptions describes options for [Pusher.Push]. + */ + interface PushOptions { /** - * IdleTimeout is the maximum amount of time to wait for the - * next request when keep-alives are enabled. If zero, the value - * of ReadTimeout is used. If negative, or if zero and ReadTimeout - * is zero or negative, there is no timeout. + * Method specifies the HTTP method for the promised request. + * If set, it must be "GET" or "HEAD". Empty means "GET". */ - idleTimeout: time.Duration + method: string /** - * MaxHeaderBytes controls the maximum number of bytes the - * server will read parsing the request header's keys and - * values, including the request line. It does not limit the - * size of the request body. - * If zero, DefaultMaxHeaderBytes is used. + * Header specifies additional promised request headers. This cannot + * include HTTP/2 pseudo header fields like ":path" and ":scheme", + * which will be added automatically. */ - maxHeaderBytes: number + header: Header + } + // @ts-ignore + import urlpkg = url + /** + * A Request represents an HTTP request received by a server + * or to be sent by a client. + * + * The field semantics differ slightly between client and server + * usage. In addition to the notes on the fields below, see the + * documentation for [Request.Write] and [RoundTripper]. + */ + interface Request { /** - * MaxHeaderValueCount controls the maximum number of header - * values that the server is willing to parse from a request. - * If zero, DefaultMaxHeaderValueCount is used. - * Note that comma-separated values in a single header line are - * counted once, while values sent as multiple header lines are - * counted multiple times. + * Method specifies the HTTP method (GET, POST, PUT, etc.). + * For client requests, an empty string means GET. */ - maxHeaderValueCount: number + method: string /** - * TLSNextProto optionally specifies a function to take over - * ownership of the provided TLS connection when an ALPN - * protocol upgrade has occurred. The map key is the protocol - * name negotiated. The Handler argument should be used to - * handle HTTP requests and will initialize the Request's TLS - * and RemoteAddr if not already set. The connection is - * automatically closed when the function returns. - * If TLSNextProto is not nil, HTTP/2 support is not enabled - * automatically. + * URL specifies either the URI being requested (for server + * requests) or the URL to access (for client requests). * - * Historically, TLSNextProto was used to disable HTTP/2 support. - * The Server.Protocols field now provides a simpler way to do this. - */ - tlsNextProto: _TygojaDict - /** - * ConnState specifies an optional callback function that is - * called when a client connection changes state. See the - * ConnState type and associated constants for details. - */ - connState: (_arg0: net.Conn, _arg1: ConnState) => void - /** - * ErrorLog specifies an optional logger for errors accepting - * connections, unexpected behavior from handlers, and - * underlying FileSystem errors. - * If nil, logging is done via the log package's standard logger. - */ - errorLog?: any - /** - * BaseContext optionally specifies a function that returns - * the base context for incoming requests on this server. - * The provided Listener is the specific Listener that's - * about to start accepting requests. - * If BaseContext is nil, the default is context.Background(). - * If non-nil, it must return a non-nil context. - */ - baseContext: (_arg0: net.Listener) => context.Context - /** - * ConnContext optionally specifies a function that modifies - * the context used for a new connection c. The provided ctx - * is derived from the base context and has a ServerContextKey - * value. + * For server requests, the URL is parsed from the URI + * supplied on the Request-Line as stored in RequestURI. For + * most requests, fields other than Path and RawQuery will be + * empty. (See RFC 7230, Section 5.3) + * + * For client requests, the URL's Host specifies the server to + * connect to, while the Request's Host field optionally + * specifies the Host header value to send in the HTTP + * request. */ - connContext: (ctx: context.Context, c: net.Conn) => context.Context + url?: url.URL /** - * HTTP2 configures HTTP/2 connections. + * The protocol version for incoming server requests. + * + * For client requests, these fields are ignored. The HTTP + * client code always uses either HTTP/1.1 or HTTP/2. + * See the docs on Transport for details. */ - http2?: HTTP2Config + proto: string // "HTTP/1.0" + protoMajor: number // 1 + protoMinor: number // 0 /** - * Protocols is the set of protocols accepted by the server. + * Header contains the request header fields either received + * by the server or to be sent by the client. * - * If Protocols includes UnencryptedHTTP2, the server will accept - * unencrypted HTTP/2 connections. The server can serve both - * HTTP/1 and unencrypted HTTP/2 on the same address and port. + * If a server received a request with header lines, * - * If Protocols is nil, the default is usually HTTP/1 and HTTP/2. - * If TLSNextProto is non-nil and does not contain an "h2" entry, - * the default is HTTP/1 only. - */ - protocols?: Protocols - /** - * DisableClientPriority specifies whether client-specified priority, as - * specified in RFC 9218, should be respected or not. - * - * This field only takes effect if using HTTP/2, and if no custom write - * scheduler is defined for the HTTP/2 server. Otherwise, this field is a - * no-op. - * - * If set to true, requests will be served in a round-robin manner, without - * prioritization. - */ - disableClientPriority: boolean - } - interface Server { - /** - * Close immediately closes all active net.Listeners and any - * connections in state [StateNew], [StateActive], or [StateIdle]. For a - * graceful shutdown, use [Server.Shutdown]. + * ``` + * Host: example.com + * accept-encoding: gzip, deflate + * Accept-Language: en-us + * fOO: Bar + * foo: two + * ``` * - * Close does not attempt to close (and does not even know about) - * any hijacked connections, such as WebSockets. + * then * - * Close returns any error returned from closing the [Server]'s - * underlying Listener(s). - */ - close(): void - } - interface Server { - /** - * Shutdown gracefully shuts down the server without interrupting any - * active connections. Shutdown works by first closing all open - * listeners, then closing all idle connections, and then waiting - * indefinitely for connections to return to idle and then shut down. - * If the provided context expires before the shutdown is complete, - * Shutdown returns the context's error, otherwise it returns any - * error returned from closing the [Server]'s underlying Listener(s). + * ``` + * Header = map[string][]string{ + * "Accept-Encoding": {"gzip, deflate"}, + * "Accept-Language": {"en-us"}, + * "Foo": {"Bar", "two"}, + * } + * ``` * - * When Shutdown is called, [Serve], [ServeTLS], [ListenAndServe], and - * [ListenAndServeTLS] immediately return [ErrServerClosed]. Make sure the - * program doesn't exit and waits instead for Shutdown to return. + * For incoming requests, the Host header is promoted to the + * Request.Host field and removed from the Header map. * - * Shutdown does not attempt to close nor wait for hijacked - * connections such as WebSockets. The caller of Shutdown should - * separately notify such long-lived connections of shutdown and wait - * for them to close, if desired. See [Server.RegisterOnShutdown] for a way to - * register shutdown notification functions. + * HTTP defines that header names are case-insensitive. The + * request parser implements this by using CanonicalHeaderKey, + * making the first character and any characters following a + * hyphen uppercase and the rest lowercase. * - * Once Shutdown has been called on a server, it may not be reused; - * future calls to methods such as Serve will return ErrServerClosed. - */ - shutdown(ctx: context.Context): void - } - interface Server { - /** - * RegisterOnShutdown registers a function to call on [Server.Shutdown]. - * This can be used to gracefully shutdown connections that have - * undergone ALPN protocol upgrade or that have been hijacked. - * This function should start protocol-specific graceful shutdown, - * but should not wait for shutdown to complete. + * For client requests, certain headers such as Content-Length + * and Connection are automatically written when needed and + * values in Header may be ignored. See the documentation + * for the Request.Write method. */ - registerOnShutdown(f: () => void): void - } - interface Server { + header: Header /** - * ListenAndServe listens on the TCP network address s.Addr and then - * calls [Serve] to handle requests on incoming connections. - * Accepted connections are configured to enable TCP keep-alives. + * Body is the request's body. * - * If s.Addr is blank, ":http" is used. + * For client requests, a nil body means the request has no + * body, such as a GET request. The HTTP Client's Transport + * is responsible for calling the Close method. * - * ListenAndServe always returns a non-nil error. After [Server.Shutdown] or [Server.Close], - * the returned error is [ErrServerClosed]. + * For server requests, the Request Body is always non-nil + * but will return EOF immediately when no body is present. + * The Server will close the request body. The ServeHTTP + * Handler does not need to. + * + * Body must allow Read to be called concurrently with Close. + * In particular, calling Close should unblock a Read waiting + * for input. */ - listenAndServe(): void - } - interface Server { + body: io.ReadCloser /** - * Serve accepts incoming connections on the Listener l, creating a - * new service goroutine for each. The service goroutines read requests and - * then call s.Handler to reply to them. - * - * HTTP/2 support is only enabled if the Listener returns [*tls.Conn] - * connections and they were configured with "h2" in the TLS - * Config.NextProtos. + * GetBody defines an optional func to return a new copy of + * Body. It is used for client requests when a redirect requires + * reading the body more than once. Use of GetBody still + * requires setting Body. * - * Serve always returns a non-nil error and closes l. - * After [Server.Shutdown] or [Server.Close], the returned error is [ErrServerClosed]. + * For server requests, it is unused. */ - serve(l: net.Listener): void - } - interface Server { + getBody: () => io.ReadCloser /** - * ServeTLS accepts incoming connections on the Listener l, creating a - * new service goroutine for each. The service goroutines perform TLS - * setup and then read requests, calling s.Handler to reply to them. - * - * Files containing a certificate and matching private key for the - * server must be provided if neither the [Server]'s - * TLSConfig.Certificates, TLSConfig.GetCertificate nor - * config.GetConfigForClient are populated. - * If the certificate is signed by a certificate authority, the - * certFile should be the concatenation of the server's certificate, - * any intermediates, and the CA's certificate. + * ContentLength records the length of the associated content. + * The value -1 indicates that the length is unknown. + * Values >= 0 indicate that the given number of bytes may + * be read from Body. * - * ServeTLS always returns a non-nil error. After [Server.Shutdown] or [Server.Close], the - * returned error is [ErrServerClosed]. + * For client requests, a value of 0 with a non-nil Body is + * also treated as unknown. */ - serveTLS(l: net.Listener, certFile: string, keyFile: string): void - } - interface Server { + contentLength: number /** - * SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled. - * By default, keep-alives are always enabled. Only very - * resource-constrained environments or servers in the process of - * shutting down should disable them. + * TransferEncoding lists the transfer encodings from outermost to + * innermost. An empty list denotes the "identity" encoding. + * TransferEncoding can usually be ignored; chunked encoding is + * automatically added and removed as necessary when sending and + * receiving requests. */ - setKeepAlivesEnabled(v: boolean): void - } - interface Server { + transferEncoding: Array /** - * ListenAndServeTLS listens on the TCP network address s.Addr and - * then calls [ServeTLS] to handle requests on incoming TLS connections. - * Accepted connections are configured to enable TCP keep-alives. - * - * Filenames containing a certificate and matching private key for the - * server must be provided if neither the [Server]'s TLSConfig.Certificates - * nor TLSConfig.GetCertificate are populated. If the certificate is - * signed by a certificate authority, the certFile should be the - * concatenation of the server's certificate, any intermediates, and - * the CA's certificate. + * Close indicates whether to close the connection after + * replying to this request (for servers) or after sending this + * request and reading its response (for clients). * - * If s.Addr is blank, ":https" is used. + * For server requests, the HTTP server handles this automatically + * and this field is not needed by Handlers. * - * ListenAndServeTLS always returns a non-nil error. After [Server.Shutdown] or - * [Server.Close], the returned error is [ErrServerClosed]. + * For client requests, setting this field prevents re-use of + * TCP connections between requests to the same hosts, as if + * Transport.DisableKeepAlives were set. */ - listenAndServeTLS(certFile: string, keyFile: string): void - } -} - -/** - * Package blob defines a lightweight abstration for interacting with - * various storage services (local filesystem, S3, etc.). - * - * NB! - * For compatibility with earlier PocketBase versions and to prevent - * unnecessary breaking changes, this package is based and implemented - * as a minimal, stripped down version of the previously used gocloud.dev/blob. - * While there is no promise that it won't diverge in the future to accommodate - * better some PocketBase specific use cases, currently it copies and - * tries to follow as close as possible the same implementations, - * conventions and rules for the key escaping/unescaping, blob read/write - * interfaces and struct options as gocloud.dev/blob, therefore the - * credits goes to the original Go Cloud Development Kit Authors. - */ -namespace blob { - /** - * ListObject represents a single blob returned from List. - */ - interface ListObject { + close: boolean /** - * Key is the key for this blob. + * For server requests, Host specifies the host on which the + * URL is sought. For HTTP/1 (per RFC 7230, section 5.4), this + * is either the value of the "Host" header or the host name + * given in the URL itself. For HTTP/2, it is the value of the + * ":authority" pseudo-header field. + * It may be of the form "host:port". For international domain + * names, Host may be in Punycode or Unicode form. Use + * golang.org/x/net/idna to convert it to either format if + * needed. + * To prevent DNS rebinding attacks, server Handlers should + * validate that the Host header has a value for which the + * Handler considers itself authoritative. The included + * ServeMux supports patterns registered to particular host + * names and thus protects its registered Handlers. + * + * For client requests, Host optionally overrides the Host + * header to send. If empty, the Request.Write method uses + * the value of URL.Host. Host may contain an international + * domain name. */ - key: string + host: string /** - * ModTime is the time the blob was last modified. + * Form contains the parsed form data, including both the URL + * field's query parameters and the PATCH, POST, or PUT form data. + * This field is only available after ParseForm is called. + * The HTTP client ignores Form and uses Body instead. */ - modTime: time.Time + form: url.Values /** - * Size is the size of the blob's content in bytes. + * PostForm contains the parsed form data from PATCH, POST + * or PUT body parameters. + * + * This field is only available after ParseForm is called. + * The HTTP client ignores PostForm and uses Body instead. */ - size: number + postForm: url.Values /** - * MD5 is an MD5 hash of the blob contents or nil if not available. + * MultipartForm is the parsed multipart form, including file uploads. + * This field is only available after ParseMultipartForm is called. + * The HTTP client ignores MultipartForm and uses Body instead. */ - md5: string|Array + multipartForm?: multipart.Form /** - * IsDir indicates that this result represents a "directory" in the - * hierarchical namespace, ending in ListOptions.Delimiter. Key can be - * passed as ListOptions.Prefix to list items in the "directory". - * Fields other than Key and IsDir will not be set if IsDir is true. - */ - isDir: boolean - } - /** - * Attributes contains attributes about a blob. - */ - interface Attributes { - /** - * CacheControl specifies caching attributes that services may use - * when serving the blob. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control - */ - cacheControl: string - /** - * ContentDisposition specifies whether the blob content is expected to be - * displayed inline or as an attachment. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition - */ - contentDisposition: string - /** - * ContentEncoding specifies the encoding used for the blob's content, if any. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding - */ - contentEncoding: string - /** - * ContentLanguage specifies the language used in the blob's content, if any. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language - */ - contentLanguage: string - /** - * ContentType is the MIME type of the blob. It will not be empty. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type + * Trailer specifies additional headers that are sent after the request + * body. + * + * For server requests, the Trailer map initially contains only the + * trailer keys, with nil values. (The client declares which trailers it + * will later send.) While the handler is reading from Body, it must + * not reference Trailer. After reading from Body returns EOF, Trailer + * can be read again and will contain non-nil values, if they were sent + * by the client. + * + * For client requests, Trailer must be initialized to a map containing + * the trailer keys to later send. The values may be nil or their final + * values. The ContentLength must be 0 or -1, to send a chunked request. + * After the HTTP request is sent the map values can be updated while + * the request body is read. Once the body returns EOF, the caller must + * not mutate Trailer. + * + * Writing a request whose Trailer contains a key with invalid bytes + * (such as CR or LF), or such a value present when Write begins, + * returns an error. + * + * Few HTTP clients, servers, or proxies support HTTP trailers. */ - contentType: string + trailer: Header /** - * Metadata holds key/value pairs associated with the blob. - * Keys are guaranteed to be in lowercase, even if the backend service - * has case-sensitive keys (although note that Metadata written via - * this package will always be lowercased). If there are duplicate - * case-insensitive keys (e.g., "foo" and "FOO"), only one value - * will be kept, and it is undefined which one. + * RemoteAddr allows HTTP servers and other software to record + * the network address that sent the request, usually for + * logging. This field is not filled in by ReadRequest and + * has no defined format. The HTTP server in this package + * sets RemoteAddr to an "IP:port" address before invoking a + * handler. + * This field is ignored by the HTTP client. */ - metadata: _TygojaDict + remoteAddr: string /** - * CreateTime is the time the blob was created, if available. If not available, - * CreateTime will be the zero time. + * RequestURI is the unmodified request-target of the + * Request-Line (RFC 7230, Section 3.1.1) as sent by the client + * to a server. Usually the URL field should be used instead. + * It is an error to set this field in an HTTP client request. */ - createTime: time.Time + requestURI: string /** - * ModTime is the time the blob was last modified. + * TLS allows HTTP servers and other software to record + * information about the TLS connection on which the request + * was received. This field is not filled in by ReadRequest. + * The HTTP server in this package sets the field for + * TLS-enabled connections before invoking a handler; + * otherwise it leaves the field nil. + * This field is ignored by the HTTP client. */ - modTime: time.Time + tls?: any /** - * Size is the size of the blob's content in bytes. + * Cancel is an optional channel whose closure indicates that the client + * request should be regarded as canceled. Not all implementations of + * RoundTripper may support Cancel. + * + * For server requests, this field is not applicable. + * + * Deprecated: Set the Request's context with NewRequestWithContext + * instead. If a Request's Cancel field and context are both + * set, it is undefined whether Cancel is respected. */ - size: number + cancel: undefined /** - * MD5 is an MD5 hash of the blob contents or nil if not available. + * Response is the redirect response which caused this request + * to be created. This field is only populated during client + * redirects. */ - md5: string|Array + response?: Response /** - * ETag for the blob; see https://en.wikipedia.org/wiki/HTTP_ETag. + * Pattern is the [ServeMux] pattern that matched the request. + * It is empty if the request was not matched against a pattern. */ - eTag: string + pattern: string } - /** - * WriterOptions sets options for NewWriter. - */ - interface WriterOptions { + interface Request { /** - * BufferSize changes the default size in bytes of the chunks that - * Writer will upload in a single request; larger blobs will be split into - * multiple requests. + * Context returns the request's context. To change the context, use + * [Request.Clone] or [Request.WithContext]. * - * This option may be ignored by some drivers. + * The returned context is always non-nil; it defaults to the + * background context. * - * If 0, the driver will choose a reasonable default. + * For outgoing client requests, the context controls cancellation. * - * If the Writer is used to do many small writes concurrently, using a - * smaller BufferSize may reduce memory usage. + * For incoming server requests, the context is canceled when the + * client's connection closes, the request is canceled (with HTTP/2), + * or when the ServeHTTP method returns. */ - bufferSize: number + context(): context.Context + } + interface Request { /** - * MaxConcurrency changes the default concurrency for parts of an upload. + * WithContext returns a shallow copy of r with its context changed + * to ctx. The provided ctx must be non-nil. * - * This option may be ignored by some drivers. + * For outgoing client request, the context controls the entire + * lifetime of a request and its response: obtaining a connection, + * sending the request, and reading the response headers and body. * - * If 0, the driver will choose a reasonable default. - */ - maxConcurrency: number - /** - * CacheControl specifies caching attributes that services may use - * when serving the blob. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control - */ - cacheControl: string - /** - * ContentDisposition specifies whether the blob content is expected to be - * displayed inline or as an attachment. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition - */ - contentDisposition: string - /** - * ContentEncoding specifies the encoding used for the blob's content, if any. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding - */ - contentEncoding: string - /** - * ContentLanguage specifies the language used in the blob's content, if any. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language - */ - contentLanguage: string - /** - * ContentType specifies the MIME type of the blob being written. If not set, - * it will be inferred from the content using the algorithm described at - * http://mimesniff.spec.whatwg.org/. - * Set DisableContentTypeDetection to true to disable the above and force - * the ContentType to stay empty. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type + * To create a new request with a context, use [NewRequestWithContext]. + * To make a deep copy of a request with a new context, use [Request.Clone]. */ - contentType: string + withContext(ctx: context.Context): (Request) + } + interface Request { /** - * When true, if ContentType is the empty string, it will stay the empty - * string rather than being inferred from the content. - * Note that while the blob will be written with an empty string ContentType, - * most providers will fill one in during reads, so don't expect an empty - * ContentType if you read the blob back. + * Clone returns a deep copy of r with its context changed to ctx. + * The provided ctx must be non-nil. + * + * Clone only makes a shallow copy of the Body field. + * + * For an outgoing client request, the context controls the entire + * lifetime of a request and its response: obtaining a connection, + * sending the request, and reading the response headers and body. */ - disableContentTypeDetection: boolean + clone(ctx: context.Context): (Request) + } + interface Request { /** - * ContentMD5 is used as a message integrity check. - * If len(ContentMD5) > 0, the MD5 hash of the bytes written must match - * ContentMD5, or Close will return an error without completing the write. - * https://tools.ietf.org/html/rfc1864 + * ProtoAtLeast reports whether the HTTP protocol used + * in the request is at least major.minor. */ - contentMD5: string|Array + protoAtLeast(major: number, minor: number): boolean + } + interface Request { /** - * Metadata holds key/value strings to be associated with the blob, or nil. - * Keys may not be empty, and are lowercased before being written. - * Duplicate case-insensitive keys (e.g., "foo" and "FOO") will result in - * an error. + * UserAgent returns the client's User-Agent, if sent in the request. */ - metadata: _TygojaDict - } - /** - * Reader reads bytes from a blob. - * It implements io.ReadSeekCloser, and must be closed after reads are finished. - */ - interface Reader { + userAgent(): string } - interface Reader { + interface Request { /** - * Read implements io.Reader (https://golang.org/pkg/io/#Reader). + * Cookies parses and returns the HTTP cookies sent with the request. */ - read(p: string|Array): number + cookies(): Array<(Cookie | undefined)> } - interface Reader { + interface Request { /** - * Seek implements io.Seeker (https://golang.org/pkg/io/#Seeker). + * CookiesNamed parses and returns the named HTTP cookies sent with the request + * or an empty slice if none matched. */ - seek(offset: number, whence: number): number + cookiesNamed(name: string): Array<(Cookie | undefined)> } - interface Reader { + interface Request { /** - * Close implements io.Closer (https://golang.org/pkg/io/#Closer). + * Cookie returns the named cookie provided in the request or + * [ErrNoCookie] if not found. + * If multiple cookies match the given name, only one cookie will + * be returned. */ - close(): void + cookie(name: string): (Cookie) } - interface Reader { + interface Request { /** - * ContentType returns the MIME type of the blob. + * AddCookie adds a cookie to the request. Per RFC 6265 section 5.4, + * AddCookie does not attach more than one [Cookie] header field. That + * means all cookies, if any, are written into the same line, + * separated by semicolon. + * AddCookie only sanitizes c's name and value, and does not sanitize + * a Cookie header already present in the request. */ - contentType(): string + addCookie(c: Cookie): void } - interface Reader { + interface Request { /** - * ModTime returns the time the blob was last modified. + * Referer returns the referring URL, if sent in the request. + * + * Referer is misspelled as in the request itself, a mistake from the + * earliest days of HTTP. This value can also be fetched from the + * [Header] map as Header["Referer"]; the benefit of making it available + * as a method is that the compiler can diagnose programs that use the + * alternate (correct English) spelling req.Referrer() but cannot + * diagnose programs that use Header["Referrer"]. */ - modTime(): time.Time + referer(): string } - interface Reader { + interface Request { /** - * Size returns the size of the blob content in bytes. + * MultipartReader returns a MIME multipart reader if this is a + * multipart/form-data or a multipart/mixed POST request, else returns nil and an error. + * Use this function instead of [Request.ParseMultipartForm] to + * process the request body as a stream. */ - size(): number + multipartReader(): (multipart.Reader) } - interface Reader { + interface Request { /** - * WriteTo reads from r and writes to w until there's no more data or - * an error occurs. - * The return value is the number of bytes written to w. + * Write writes an HTTP/1.1 request, which is the header and body, in wire format. + * This method consults the following fields of the request: * - * It implements the io.WriterTo interface. + * ``` + * Host + * URL + * Method (defaults to "GET") + * Header + * ContentLength + * TransferEncoding + * Body + * ``` + * + * If Body is present, Content-Length is <= 0 and [Request.TransferEncoding] + * hasn't been set to "identity", Write adds "Transfer-Encoding: + * chunked" to the header. Body is closed after it is sent. + * + * Header values for Host, Content-Length, Transfer-Encoding, + * and Trailer are not used; these are derived from other Request fields. + * If the Header does not contain a User-Agent value, Write uses + * "Go-http-client/1.1". */ - writeTo(w: io.Writer): number + write(w: io.Writer): void } - /** - * Writer writes bytes to a blob. - * - * It implements io.WriteCloser (https://golang.org/pkg/io/#Closer), and must be - * closed after all writes are done. - */ - interface Writer { + interface Request { + /** + * WriteProxy is like [Request.Write] but writes the request in the form + * expected by an HTTP proxy. In particular, [Request.WriteProxy] writes the + * initial Request-URI line of the request with an absolute URI, per + * section 5.3 of RFC 7230, including the scheme and host. + * In either case, WriteProxy also writes a Host header, using + * either r.Host or r.URL.Host. + */ + writeProxy(w: io.Writer): void } - interface Writer { + interface Request { /** - * Write implements the io.Writer interface (https://golang.org/pkg/io/#Writer). - * - * Writes may happen asynchronously, so the returned error can be nil - * even if the actual write eventually fails. The write is only guaranteed to - * have succeeded if Close returns no error. + * BasicAuth returns the username and password provided in the request's + * Authorization header, if the request uses HTTP Basic Authentication. + * See RFC 2617, Section 2. */ - write(p: string|Array): number + basicAuth(): [string, string, boolean] } - interface Writer { + interface Request { /** - * Close closes the blob writer. The write operation is not guaranteed - * to have succeeded until Close returns with no error. + * SetBasicAuth sets the request's Authorization header to use HTTP + * Basic Authentication with the provided username and password. * - * Close may return an error if the context provided to create the - * Writer is canceled or reaches its deadline. + * With HTTP Basic Authentication the provided username and password + * are not encrypted. It should generally only be used in an HTTPS + * request. + * + * The username may not contain a colon. Some protocols may impose + * additional requirements on pre-escaping the username and + * password. For instance, when used with OAuth2, both arguments must + * be URL encoded first with [url.QueryEscape]. */ - close(): void + setBasicAuth(username: string, password: string): void } - interface Writer { + interface Request { /** - * ReadFrom reads from r and writes to w until EOF or error. - * The return value is the number of bytes read from r. + * ParseForm populates r.Form and r.PostForm. * - * It implements the io.ReaderFrom interface. + * For all requests, ParseForm parses the raw query from the URL and updates + * r.Form. + * + * For POST, PUT, and PATCH requests, it also reads the request body, parses it + * as a form and puts the results into both r.PostForm and r.Form. Request body + * parameters take precedence over URL query string values in r.Form. + * + * If the request Body's size has not already been limited by [MaxBytesReader], + * the size is capped at 10MB. + * + * For other HTTP methods, or when the Content-Type is not + * application/x-www-form-urlencoded, the request Body is not read, and + * r.PostForm is initialized to a non-nil, empty value. + * + * [Request.ParseMultipartForm] calls ParseForm automatically. + * ParseForm is idempotent. */ - readFrom(r: io.Reader): number + parseForm(): void } -} - -/** - * Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html - * - * See README.md for more info. - */ -namespace jwt { - /** - * MapClaims is a claims type that uses the map[string]any for JSON - * decoding. This is the default claims type if you don't supply one - */ - interface MapClaims extends _TygojaDict{} - interface MapClaims { + interface Request { /** - * GetExpirationTime implements the Claims interface. + * ParseMultipartForm parses a request body as multipart/form-data. + * The whole request body is parsed and up to a total of maxMemory bytes of + * its file parts are stored in memory, with the remainder stored on + * disk in temporary files. + * ParseMultipartForm calls [Request.ParseForm] if necessary. + * If ParseForm returns an error, ParseMultipartForm returns it but also + * continues parsing the request body. + * After one call to ParseMultipartForm, subsequent calls have no effect. */ - getExpirationTime(): (NumericDate) + parseMultipartForm(maxMemory: number): void } - interface MapClaims { + interface Request { /** - * GetNotBefore implements the Claims interface. + * FormValue returns the first value for the named component of the query. + * The precedence order: + * 1. application/x-www-form-urlencoded form body (POST, PUT, PATCH only) + * 2. query parameters (always) + * 3. multipart/form-data form body (always) + * + * FormValue calls [Request.ParseMultipartForm] and [Request.ParseForm] + * if necessary and ignores any errors returned by these functions. + * If key is not present, FormValue returns the empty string. + * To access multiple values of the same key, call ParseForm and + * then inspect [Request.Form] directly. */ - getNotBefore(): (NumericDate) + formValue(key: string): string } - interface MapClaims { + interface Request { /** - * GetIssuedAt implements the Claims interface. + * PostFormValue returns the first value for the named component of the POST, + * PUT, or PATCH request body. URL query parameters are ignored. + * PostFormValue calls [Request.ParseMultipartForm] and [Request.ParseForm] if necessary and ignores + * any errors returned by these functions. + * If key is not present, PostFormValue returns the empty string. */ - getIssuedAt(): (NumericDate) + postFormValue(key: string): string } - interface MapClaims { + interface Request { /** - * GetAudience implements the Claims interface. + * FormFile returns the first file for the provided form key. + * FormFile calls [Request.ParseMultipartForm] and [Request.ParseForm] if necessary. */ - getAudience(): ClaimStrings + formFile(key: string): [multipart.File, (multipart.FileHeader)] } - interface MapClaims { + interface Request { /** - * GetIssuer implements the Claims interface. + * PathValue returns the value for the named path wildcard in the [ServeMux] pattern + * that matched the request. + * It returns the empty string if the request was not matched against a pattern + * or there is no such wildcard in the pattern. + * + * The value is unescaped. For example, if the pattern "/b/{bucket}" matches + * the path "/b/a%2fb", PathValue("bucket") returns "a/b". */ - getIssuer(): string + pathValue(name: string): string } - interface MapClaims { + interface Request { /** - * GetSubject implements the Claims interface. + * SetPathValue sets name to value, so that subsequent calls to r.PathValue(name) + * return value. + * It does not unescape value. */ - getSubject(): string + setPathValue(name: string, value: string): void } -} - -/** - * Package types implements some commonly used db serializable types - * like datetime, json, etc. - */ -namespace types { /** - * DateTime represents a [time.Time] instance in UTC that is wrapped - * and serialized using the app default date layout. + * A Handler responds to an HTTP request. + * + * [Handler.ServeHTTP] should write reply headers and data to the [ResponseWriter] + * and then return. Returning signals that the request is finished; it + * is not valid to use the [ResponseWriter] or read from the + * [Request.Body] after or concurrently with the completion of the + * ServeHTTP call. + * + * Depending on the HTTP client software, HTTP protocol version, and + * any intermediaries between the client and the Go server, it may not + * be possible to read from the [Request.Body] after writing to the + * [ResponseWriter]. Cautious handlers should read the [Request.Body] + * first, and then reply. + * + * Except for reading the body, handlers should not modify the + * provided Request. + * + * If ServeHTTP panics, the server (the caller of ServeHTTP) assumes + * that the effect of the panic was isolated to the active request. + * It recovers the panic, logs a stack trace to the server error log, + * and either closes the network connection or sends an HTTP/2 + * RST_STREAM, depending on the HTTP protocol. To abort a handler so + * the client sees an interrupted response but the server doesn't log + * an error, panic with the value [ErrAbortHandler]. */ - interface DateTime { - } - interface DateTime { - /** - * Time returns the internal [time.Time] instance. - */ - time(): time.Time - } - interface DateTime { - /** - * Add returns a new DateTime based on the current DateTime + the specified duration. - */ - add(duration: time.Duration): DateTime + interface Handler { + [key:string]: any; + serveHTTP(_arg0: ResponseWriter, _arg1: Request): void } - interface DateTime { + /** + * A ResponseWriter interface is used by an HTTP handler to + * construct an HTTP response. + * + * A ResponseWriter may not be used after [Handler.ServeHTTP] has returned. + */ + interface ResponseWriter { + [key:string]: any; /** - * Sub returns a [time.Duration] by subtracting the specified DateTime from the current one. + * Header returns the header map that will be sent by + * [ResponseWriter.WriteHeader]. The [Header] map also is the mechanism with which + * [Handler] implementations can set HTTP trailers. * - * If the result exceeds the maximum (or minimum) value that can be stored in a [time.Duration], - * the maximum (or minimum) duration will be returned. + * Changing the header map after a call to [ResponseWriter.WriteHeader] (or + * [ResponseWriter.Write]) has no effect unless the HTTP status code was of the + * 1xx class or the modified headers are trailers. + * + * There are two ways to set Trailers. The preferred way is to + * predeclare in the headers which trailers you will later + * send by setting the "Trailer" header to the names of the + * trailer keys which will come later. In this case, those + * keys of the Header map are treated as if they were + * trailers. See the example. The second way, for trailer + * keys not known to the [Handler] until after the first [ResponseWriter.Write], + * is to prefix the [Header] map keys with the [TrailerPrefix] + * constant value. + * + * To suppress automatic response headers (such as "Date"), set + * their value to nil. */ - sub(u: DateTime): time.Duration - } - interface DateTime { + header(): Header /** - * AddDate returns a new DateTime based on the current one + duration. + * Write writes the data to the connection as part of an HTTP reply. * - * It follows the same rules as [time.AddDate]. + * If [ResponseWriter.WriteHeader] has not yet been called, Write calls + * WriteHeader(http.StatusOK) before writing the data. If the Header + * does not contain a Content-Type line, Write adds a Content-Type set + * to the result of passing the initial 512 bytes of written data to + * [DetectContentType]. Additionally, if the total size of all written + * data is under a few KB and there are no Flush calls, the + * Content-Length header is added automatically. + * + * Depending on the HTTP protocol version and the client, calling + * Write or WriteHeader may prevent future reads on the + * Request.Body. For HTTP/1.x requests, handlers should read any + * needed request body data before writing the response. Once the + * headers have been flushed (due to either an explicit Flusher.Flush + * call or writing enough data to trigger a flush), the request body + * may be unavailable. For HTTP/2 requests, the Go HTTP server permits + * handlers to continue to read the request body while concurrently + * writing the response. However, such behavior may not be supported + * by all HTTP/2 clients. Handlers should read before writing if + * possible to maximize compatibility. */ - addDate(years: number, months: number, days: number): DateTime - } - interface DateTime { + write(_arg0: string|Array): number /** - * After reports whether the current DateTime instance is after u. + * WriteHeader sends an HTTP response header with the provided + * status code. + * + * If WriteHeader is not called explicitly, the first call to Write + * will trigger an implicit WriteHeader(http.StatusOK). + * Thus explicit calls to WriteHeader are mainly used to + * send error codes or 1xx informational responses. + * + * The provided code must be a valid HTTP 1xx-5xx status code. + * Any number of 1xx headers may be written, followed by at most + * one 2xx-5xx header. 1xx headers are sent immediately, but 2xx-5xx + * headers may be buffered. Use the Flusher interface to send + * buffered data. The header map is cleared when 2xx-5xx headers are + * sent, but not with 1xx headers. + * + * The server will automatically send a 100 (Continue) header + * on the first read from the request body if the request has + * an "Expect: 100-continue" header. */ - after(u: DateTime): boolean + writeHeader(statusCode: number): void } - interface DateTime { + /** + * A Server defines parameters for running an HTTP server. + * The zero value for Server is a valid configuration. + */ + interface Server { /** - * Before reports whether the current DateTime instance is before u. + * Addr optionally specifies the TCP address for the server to listen on, + * in the form "host:port". If empty, ":http" (port 80) is used. + * The service names are defined in RFC 6335 and assigned by IANA. + * See net.Dial for details of the address format. */ - before(u: DateTime): boolean - } - interface DateTime { + addr: string + handler: Handler // handler to invoke, http.DefaultServeMux if nil /** - * Compare compares the current DateTime instance with u. - * If the current instance is before u, it returns -1. - * If the current instance is after u, it returns +1. - * If they're the same, it returns 0. + * DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler, + * otherwise responds with 200 OK and Content-Length: 0. */ - compare(u: DateTime): number - } - interface DateTime { + disableGeneralOptionsHandler: boolean /** - * Equal reports whether the current DateTime and u represent the same time instant. - * Two DateTime can be equal even if they are in different locations. - * For example, 6:00 +0200 and 4:00 UTC are Equal. + * TLSConfig optionally provides a TLS configuration for use + * by ServeTLS and ListenAndServeTLS. Note that this value is + * cloned by ServeTLS and ListenAndServeTLS, so it's not + * possible to modify the configuration with methods like + * tls.Config.SetSessionTicketKeys. To use + * SetSessionTicketKeys, use Server.Serve with a TLS Listener + * instead. */ - equal(u: DateTime): boolean - } - interface DateTime { + tlsConfig?: any /** - * Unix returns the current DateTime as a Unix time, aka. - * the number of seconds elapsed since January 1, 1970 UTC. + * ReadTimeout is the maximum duration for reading the entire + * request, including the body. A zero or negative value means + * there will be no timeout. + * + * Because ReadTimeout does not let Handlers make per-request + * decisions on each request body's acceptable deadline or + * upload rate, most users will prefer to use + * ReadHeaderTimeout. It is valid to use them both. */ - unix(): number - } - interface DateTime { + readTimeout: time.Duration /** - * IsZero checks whether the current DateTime instance has zero time value. + * ReadHeaderTimeout is the amount of time allowed to read + * request headers. The connection's read deadline is reset + * after reading the headers and the Handler can decide what + * is considered too slow for the body. If zero, the value of + * ReadTimeout is used. If negative, or if zero and ReadTimeout + * is zero or negative, there is no timeout. */ - isZero(): boolean - } - interface DateTime { + readHeaderTimeout: time.Duration /** - * String serializes the current DateTime instance into a formatted - * UTC date string. - * - * The zero value is serialized to an empty string. + * WriteTimeout is the maximum duration before timing out + * writes of the response. It is reset whenever a new + * request's header is read. Like ReadTimeout, it does not + * let Handlers make decisions on a per-request basis. + * A zero or negative value means there will be no timeout. */ - string(): string - } - interface DateTime { + writeTimeout: time.Duration /** - * MarshalJSON implements the [json.Marshaler] interface. + * IdleTimeout is the maximum amount of time to wait for the + * next request when keep-alives are enabled. If zero, the value + * of ReadTimeout is used. If negative, or if zero and ReadTimeout + * is zero or negative, there is no timeout. */ - marshalJSON(): string|Array - } - interface DateTime { + idleTimeout: time.Duration /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. + * MaxHeaderBytes controls the maximum number of bytes the + * server will read parsing the request header's keys and + * values, including the request line. It does not limit the + * size of the request body. + * If zero, DefaultMaxHeaderBytes is used. */ - unmarshalJSON(b: string|Array): void - } - interface DateTime { + maxHeaderBytes: number /** - * Value implements the [driver.Valuer] interface. + * MaxHeaderValueCount controls the maximum number of header + * values that the server is willing to parse from a request. + * If zero, DefaultMaxHeaderValueCount is used. + * Note that comma-separated values in a single header line are + * counted once, while values sent as multiple header lines are + * counted multiple times. */ - value(): any - } - interface DateTime { + maxHeaderValueCount: number /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current DateTime instance. + * TLSNextProto optionally specifies a function to take over + * ownership of the provided TLS connection when an ALPN + * protocol upgrade has occurred. The map key is the protocol + * name negotiated. The Handler argument should be used to + * handle HTTP requests and will initialize the Request's TLS + * and RemoteAddr if not already set. The connection is + * automatically closed when the function returns. + * If TLSNextProto is not nil, HTTP/2 support is not enabled + * automatically. + * + * Historically, TLSNextProto was used to disable HTTP/2 support. + * The Server.Protocols field now provides a simpler way to do this. */ - scan(value: any): void - } - /** - * GeoPoint defines a struct for storing geo coordinates as serialized json object - * (e.g. {lon:0,lat:0}). - * - * Note: using object notation and not a plain array to avoid the confusion - * as there doesn't seem to be a fixed standard for the coordinates order. - */ - interface GeoPoint { - lon: number - lat: number - } - interface GeoPoint { + tlsNextProto: _TygojaDict /** - * String returns the string representation of the current GeoPoint instance. + * ConnState specifies an optional callback function that is + * called when a client connection changes state. See the + * ConnState type and associated constants for details. */ - string(): string - } - interface GeoPoint { + connState: (_arg0: net.Conn, _arg1: ConnState) => void /** - * AsMap implements [core.mapExtractor] and returns a value suitable - * to be used in an API rule expression. + * ErrorLog specifies an optional logger for errors accepting + * connections, unexpected behavior from handlers, and + * underlying FileSystem errors. + * If nil, logging is done via the log package's standard logger. */ - asMap(): _TygojaDict - } - interface GeoPoint { + errorLog?: any /** - * Value implements the [driver.Valuer] interface. + * BaseContext optionally specifies a function that returns + * the base context for incoming requests on this server. + * The provided Listener is the specific Listener that's + * about to start accepting requests. + * If BaseContext is nil, the default is context.Background(). + * If non-nil, it must return a non-nil context. */ - value(): any - } - interface GeoPoint { + baseContext: (_arg0: net.Listener) => context.Context /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current GeoPoint instance. - * - * The value argument could be nil (no-op), another GeoPoint instance, - * map or serialized json object with lat-lon props. + * ConnContext optionally specifies a function that modifies + * the context used for a new connection c. The provided ctx + * is derived from the base context and has a ServerContextKey + * value. */ - scan(value: any): void - } - /** - * JSONArray defines a slice that is safe for json and db read/write. - */ - interface JSONArray extends Array{} - interface JSONArray { + connContext: (ctx: context.Context, c: net.Conn) => context.Context /** - * MarshalJSON implements the [json.Marshaler] interface. + * HTTP2 configures HTTP/2 connections. */ - marshalJSON(): string|Array - } - interface JSONArray { + http2?: HTTP2Config /** - * String returns the string representation of the current json array. + * Protocols is the set of protocols accepted by the server. + * + * If Protocols includes UnencryptedHTTP2, the server will accept + * unencrypted HTTP/2 connections. The server can serve both + * HTTP/1 and unencrypted HTTP/2 on the same address and port. + * + * If Protocols is nil, the default is usually HTTP/1 and HTTP/2. + * If TLSNextProto is non-nil and does not contain an "h2" entry, + * the default is HTTP/1 only. */ - string(): string - } - interface JSONArray { + protocols?: Protocols /** - * Value implements the [driver.Valuer] interface. + * DisableClientPriority specifies whether client-specified priority, as + * specified in RFC 9218, should be respected or not. + * + * This field only takes effect if using HTTP/2, and if no custom write + * scheduler is defined for the HTTP/2 server. Otherwise, this field is a + * no-op. + * + * If set to true, requests will be served in a round-robin manner, without + * prioritization. */ - value(): any + disableClientPriority: boolean } - interface JSONArray { + interface Server { /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current JSONArray[T] instance. + * Close immediately closes all active net.Listeners and any + * connections in state [StateNew], [StateActive], or [StateIdle]. For a + * graceful shutdown, use [Server.Shutdown]. + * + * Close does not attempt to close (and does not even know about) + * any hijacked connections, such as WebSockets. + * + * Close returns any error returned from closing the [Server]'s + * underlying Listener(s). */ - scan(value: any): void + close(): void } - /** - * JSONMap defines a map that is safe for json and db read/write. - */ - interface JSONMap extends _TygojaDict{} - interface JSONMap { + interface Server { /** - * Get retrieves a single value from the current JSONMap[T]. + * Shutdown gracefully shuts down the server without interrupting any + * active connections. Shutdown works by first closing all open + * listeners, then closing all idle connections, and then waiting + * indefinitely for connections to return to idle and then shut down. + * If the provided context expires before the shutdown is complete, + * Shutdown returns the context's error, otherwise it returns any + * error returned from closing the [Server]'s underlying Listener(s). * - * This helper was added primarily to assist the goja integration since custom map types - * don't have direct access to the map keys (https://pkg.go.dev/github.com/dop251/goja#hdr-Maps_with_methods). + * When Shutdown is called, [Serve], [ServeTLS], [ListenAndServe], and + * [ListenAndServeTLS] immediately return [ErrServerClosed]. Make sure the + * program doesn't exit and waits instead for Shutdown to return. + * + * Shutdown does not attempt to close nor wait for hijacked + * connections such as WebSockets. The caller of Shutdown should + * separately notify such long-lived connections of shutdown and wait + * for them to close, if desired. See [Server.RegisterOnShutdown] for a way to + * register shutdown notification functions. + * + * Once Shutdown has been called on a server, it may not be reused; + * future calls to methods such as Serve will return ErrServerClosed. */ - get(key: string): T + shutdown(ctx: context.Context): void } - interface JSONMap { + interface Server { /** - * Set sets a single value in the current JSONMap[T]. + * RegisterOnShutdown registers a function to call on [Server.Shutdown]. + * This can be used to gracefully shutdown connections that have + * undergone ALPN protocol upgrade or that have been hijacked. + * This function should start protocol-specific graceful shutdown, + * but should not wait for shutdown to complete. + */ + registerOnShutdown(f: () => void): void + } + interface Server { + /** + * ListenAndServe listens on the TCP network address s.Addr and then + * calls [Serve] to handle requests on incoming connections. + * Accepted connections are configured to enable TCP keep-alives. * - * This helper was added primarily to assist the goja integration since custom map types - * don't have direct access to the map keys (https://pkg.go.dev/github.com/dop251/goja#hdr-Maps_with_methods). + * If s.Addr is blank, ":http" is used. + * + * ListenAndServe always returns a non-nil error. After [Server.Shutdown] or [Server.Close], + * the returned error is [ErrServerClosed]. */ - set(key: string, value: T): void + listenAndServe(): void } - interface JSONMap { + interface Server { /** - * MarshalJSON implements the [json.Marshaler] interface. + * Serve accepts incoming connections on the Listener l, creating a + * new service goroutine for each. The service goroutines read requests and + * then call s.Handler to reply to them. + * + * HTTP/2 support is only enabled if the Listener returns [*tls.Conn] + * connections and they were configured with "h2" in the TLS + * Config.NextProtos. + * + * Serve always returns a non-nil error and closes l. + * After [Server.Shutdown] or [Server.Close], the returned error is [ErrServerClosed]. */ - marshalJSON(): string|Array + serve(l: net.Listener): void } - interface JSONMap { + interface Server { /** - * String returns the string representation of the current json map. + * ServeTLS accepts incoming connections on the Listener l, creating a + * new service goroutine for each. The service goroutines perform TLS + * setup and then read requests, calling s.Handler to reply to them. + * + * Files containing a certificate and matching private key for the + * server must be provided if neither the [Server]'s + * TLSConfig.Certificates, TLSConfig.GetCertificate nor + * config.GetConfigForClient are populated. + * If the certificate is signed by a certificate authority, the + * certFile should be the concatenation of the server's certificate, + * any intermediates, and the CA's certificate. + * + * ServeTLS always returns a non-nil error. After [Server.Shutdown] or [Server.Close], the + * returned error is [ErrServerClosed]. */ - string(): string + serveTLS(l: net.Listener, certFile: string, keyFile: string): void } - interface JSONMap { + interface Server { /** - * Value implements the [driver.Valuer] interface. + * SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled. + * By default, keep-alives are always enabled. Only very + * resource-constrained environments or servers in the process of + * shutting down should disable them. */ - value(): any + setKeepAlivesEnabled(v: boolean): void } - interface JSONMap { + interface Server { /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current JSONMap[T] instance. + * ListenAndServeTLS listens on the TCP network address s.Addr and + * then calls [ServeTLS] to handle requests on incoming TLS connections. + * Accepted connections are configured to enable TCP keep-alives. + * + * Filenames containing a certificate and matching private key for the + * server must be provided if neither the [Server]'s TLSConfig.Certificates + * nor TLSConfig.GetCertificate are populated. If the certificate is + * signed by a certificate authority, the certFile should be the + * concatenation of the server's certificate, any intermediates, and + * the CA's certificate. + * + * If s.Addr is blank, ":https" is used. + * + * ListenAndServeTLS always returns a non-nil error. After [Server.Shutdown] or + * [Server.Close], the returned error is [ErrServerClosed]. */ - scan(value: any): void + listenAndServeTLS(certFile: string, keyFile: string): void } +} + +/** + * Package blob defines a lightweight abstration for interacting with + * various storage services (local filesystem, S3, etc.). + * + * NB! + * For compatibility with earlier PocketBase versions and to prevent + * unnecessary breaking changes, this package is based and implemented + * as a minimal, stripped down version of the previously used gocloud.dev/blob. + * While there is no promise that it won't diverge in the future to accommodate + * better some PocketBase specific use cases, currently it copies and + * tries to follow as close as possible the same implementations, + * conventions and rules for the key escaping/unescaping, blob read/write + * interfaces and struct options as gocloud.dev/blob, therefore the + * credits goes to the original Go Cloud Development Kit Authors. + */ +namespace blob { /** - * JSONRaw defines a json value type that is safe for db read/write. + * ListObject represents a single blob returned from List. */ - interface JSONRaw extends Array{} - interface JSONRaw { + interface ListObject { /** - * String returns the current JSONRaw instance as a json encoded string. + * Key is the key for this blob. */ - string(): string - } - interface JSONRaw { + key: string /** - * MarshalJSON implements the [json.Marshaler] interface. + * ModTime is the time the blob was last modified. */ - marshalJSON(): string|Array - } - interface JSONRaw { + modTime: time.Time /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. + * Size is the size of the blob's content in bytes. */ - unmarshalJSON(b: string|Array): void - } - interface JSONRaw { + size: number /** - * Value implements the [driver.Valuer] interface. + * MD5 is an MD5 hash of the blob contents or nil if not available. */ - value(): any - } - interface JSONRaw { + md5: string|Array /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current JSONRaw instance. + * IsDir indicates that this result represents a "directory" in the + * hierarchical namespace, ending in ListOptions.Delimiter. Key can be + * passed as ListOptions.Prefix to list items in the "directory". + * Fields other than Key and IsDir will not be set if IsDir is true. */ - scan(value: any): void + isDir: boolean } -} - -/** - * Package sql provides a generic interface around SQL (or SQL-like) - * databases. - * - * The sql package must be used in conjunction with a database driver. - * See https://golang.org/s/sqldrivers for a list of drivers. - * - * Drivers that do not support context cancellation will not return until - * after the query is completed. - * - * For usage examples, see the wiki page at - * https://golang.org/s/sqlwiki. - */ -namespace sql { /** - * TxOptions holds the transaction options to be used in [DB.BeginTx]. + * Attributes contains attributes about a blob. */ - interface TxOptions { + interface Attributes { /** - * Isolation is the transaction isolation level. - * If zero, the driver or database's default level is used. + * CacheControl specifies caching attributes that services may use + * when serving the blob. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control */ - isolation: IsolationLevel - readOnly: boolean - } - /** - * NullString represents a string that may be null. - * NullString implements the [Scanner] interface so - * it can be used as a scan destination: - * - * ``` - * var s NullString - * err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s) - * ... - * if s.Valid { - * // use s.String - * } else { - * // NULL value - * } - * ``` - */ - interface NullString { - string: string - valid: boolean // Valid is true if String is not NULL - } - interface NullString { + cacheControl: string /** - * Scan implements the [Scanner] interface. + * ContentDisposition specifies whether the blob content is expected to be + * displayed inline or as an attachment. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition */ - scan(value: any): void - } - interface NullString { + contentDisposition: string /** - * Value implements the [driver.Valuer] interface. + * ContentEncoding specifies the encoding used for the blob's content, if any. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding */ - value(): any - } - /** - * DB is a database handle representing a pool of zero or more - * underlying connections. It's safe for concurrent use by multiple - * goroutines. - * - * The sql package creates and frees connections automatically; it - * also maintains a free pool of idle connections. If the database has - * a concept of per-connection state, such state can be reliably observed - * within a transaction ([Tx]) or connection ([Conn]). Once [DB.Begin] is called, the - * returned [Tx] is bound to a single connection. Once [Tx.Commit] or - * [Tx.Rollback] is called on the transaction, that transaction's - * connection is returned to [DB]'s idle connection pool. The pool size - * can be controlled with [DB.SetMaxIdleConns]. - */ - interface DB { - } - interface DB { + contentEncoding: string /** - * PingContext verifies a connection to the database is still alive, - * establishing a connection if necessary. + * ContentLanguage specifies the language used in the blob's content, if any. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language */ - pingContext(ctx: context.Context): void - } - interface DB { + contentLanguage: string /** - * Ping verifies a connection to the database is still alive, - * establishing a connection if necessary. - * - * Ping uses [context.Background] internally; to specify the context, use - * [DB.PingContext]. + * ContentType is the MIME type of the blob. It will not be empty. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type */ - ping(): void - } - interface DB { + contentType: string /** - * Close closes the database and prevents new queries from starting. - * Close then waits for all queries that have started processing on the server - * to finish. - * - * It is rare to Close a [DB], as the [DB] handle is meant to be - * long-lived and shared between many goroutines. + * Metadata holds key/value pairs associated with the blob. + * Keys are guaranteed to be in lowercase, even if the backend service + * has case-sensitive keys (although note that Metadata written via + * this package will always be lowercased). If there are duplicate + * case-insensitive keys (e.g., "foo" and "FOO"), only one value + * will be kept, and it is undefined which one. */ - close(): void + metadata: _TygojaDict + /** + * CreateTime is the time the blob was created, if available. If not available, + * CreateTime will be the zero time. + */ + createTime: time.Time + /** + * ModTime is the time the blob was last modified. + */ + modTime: time.Time + /** + * Size is the size of the blob's content in bytes. + */ + size: number + /** + * MD5 is an MD5 hash of the blob contents or nil if not available. + */ + md5: string|Array + /** + * ETag for the blob; see https://en.wikipedia.org/wiki/HTTP_ETag. + */ + eTag: string } - interface DB { + /** + * WriterOptions sets options for NewWriter. + */ + interface WriterOptions { /** - * SetMaxIdleConns sets the maximum number of connections in the idle - * connection pool. + * BufferSize changes the default size in bytes of the chunks that + * Writer will upload in a single request; larger blobs will be split into + * multiple requests. * - * If MaxOpenConns is greater than 0 but less than the new MaxIdleConns, - * then the new MaxIdleConns will be reduced to match the MaxOpenConns limit. + * This option may be ignored by some drivers. * - * If n <= 0, no idle connections are retained. + * If 0, the driver will choose a reasonable default. * - * The default max idle connections is currently 2. This may change in - * a future release. + * If the Writer is used to do many small writes concurrently, using a + * smaller BufferSize may reduce memory usage. */ - setMaxIdleConns(n: number): void - } - interface DB { + bufferSize: number /** - * SetMaxOpenConns sets the maximum number of open connections to the database. + * MaxConcurrency changes the default concurrency for parts of an upload. * - * If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than - * MaxIdleConns, then MaxIdleConns will be reduced to match the new - * MaxOpenConns limit. + * This option may be ignored by some drivers. * - * If n <= 0, then there is no limit on the number of open connections. - * The default is 0 (unlimited). + * If 0, the driver will choose a reasonable default. */ - setMaxOpenConns(n: number): void - } - interface DB { + maxConcurrency: number /** - * SetConnMaxLifetime sets the maximum amount of time a connection may be reused. - * - * Expired connections may be closed lazily before reuse. - * - * If d <= 0, connections are not closed due to a connection's age. + * CacheControl specifies caching attributes that services may use + * when serving the blob. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control */ - setConnMaxLifetime(d: time.Duration): void - } - interface DB { + cacheControl: string /** - * SetConnMaxIdleTime sets the maximum amount of time a connection may be idle. - * - * Expired connections may be closed lazily before reuse. - * - * If d <= 0, connections are not closed due to a connection's idle time. + * ContentDisposition specifies whether the blob content is expected to be + * displayed inline or as an attachment. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition */ - setConnMaxIdleTime(d: time.Duration): void - } - interface DB { + contentDisposition: string /** - * Stats returns database statistics. + * ContentEncoding specifies the encoding used for the blob's content, if any. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding */ - stats(): DBStats - } - interface DB { + contentEncoding: string /** - * PrepareContext creates a prepared statement for later queries or executions. - * Multiple queries or executions may be run concurrently from the - * returned statement. - * The caller must call the statement's [*Stmt.Close] method - * when the statement is no longer needed. - * - * The provided context is used for the preparation of the statement, not for the - * execution of the statement. + * ContentLanguage specifies the language used in the blob's content, if any. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language */ - prepareContext(ctx: context.Context, query: string): (Stmt) - } - interface DB { + contentLanguage: string /** - * Prepare creates a prepared statement for later queries or executions. - * Multiple queries or executions may be run concurrently from the - * returned statement. - * The caller must call the statement's [*Stmt.Close] method - * when the statement is no longer needed. - * - * Prepare uses [context.Background] internally; to specify the context, use - * [DB.PrepareContext]. + * ContentType specifies the MIME type of the blob being written. If not set, + * it will be inferred from the content using the algorithm described at + * http://mimesniff.spec.whatwg.org/. + * Set DisableContentTypeDetection to true to disable the above and force + * the ContentType to stay empty. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type */ - prepare(query: string): (Stmt) - } - interface DB { + contentType: string /** - * ExecContext executes a query without returning any rows. - * The args are for any placeholder parameters in the query. + * When true, if ContentType is the empty string, it will stay the empty + * string rather than being inferred from the content. + * Note that while the blob will be written with an empty string ContentType, + * most providers will fill one in during reads, so don't expect an empty + * ContentType if you read the blob back. */ - execContext(ctx: context.Context, query: string, ...args: any[]): Result + disableContentTypeDetection: boolean + /** + * ContentMD5 is used as a message integrity check. + * If len(ContentMD5) > 0, the MD5 hash of the bytes written must match + * ContentMD5, or Close will return an error without completing the write. + * https://tools.ietf.org/html/rfc1864 + */ + contentMD5: string|Array + /** + * Metadata holds key/value strings to be associated with the blob, or nil. + * Keys may not be empty, and are lowercased before being written. + * Duplicate case-insensitive keys (e.g., "foo" and "FOO") will result in + * an error. + */ + metadata: _TygojaDict } - interface DB { + /** + * Reader reads bytes from a blob. + * It implements io.ReadSeekCloser, and must be closed after reads are finished. + */ + interface Reader { + } + interface Reader { /** - * Exec executes a query without returning any rows. - * The args are for any placeholder parameters in the query. - * - * Exec uses [context.Background] internally; to specify the context, use - * [DB.ExecContext]. + * Read implements io.Reader (https://golang.org/pkg/io/#Reader). */ - exec(query: string, ...args: any[]): Result + read(p: string|Array): number } - interface DB { + interface Reader { /** - * QueryContext executes a query that returns rows, typically a SELECT. - * The args are for any placeholder parameters in the query. + * Seek implements io.Seeker (https://golang.org/pkg/io/#Seeker). */ - queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows) + seek(offset: number, whence: number): number } - interface DB { + interface Reader { /** - * Query executes a query that returns rows, typically a SELECT. - * The args are for any placeholder parameters in the query. - * - * Query uses [context.Background] internally; to specify the context, use - * [DB.QueryContext]. + * Close implements io.Closer (https://golang.org/pkg/io/#Closer). */ - query(query: string, ...args: any[]): (Rows) + close(): void } - interface DB { + interface Reader { /** - * QueryRowContext executes a query that is expected to return at most one row. - * QueryRowContext always returns a non-nil value. Errors are deferred until - * [Row]'s Scan method is called. - * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. - * Otherwise, [*Row.Scan] scans the first selected row and discards - * the rest. + * ContentType returns the MIME type of the blob. */ - queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row) + contentType(): string } - interface DB { + interface Reader { /** - * QueryRow executes a query that is expected to return at most one row. - * QueryRow always returns a non-nil value. Errors are deferred until - * [Row]'s Scan method is called. - * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. - * Otherwise, [*Row.Scan] scans the first selected row and discards - * the rest. - * - * QueryRow uses [context.Background] internally; to specify the context, use - * [DB.QueryRowContext]. + * ModTime returns the time the blob was last modified. */ - queryRow(query: string, ...args: any[]): (Row) + modTime(): time.Time } - interface DB { + interface Reader { /** - * BeginTx starts a transaction. - * - * The provided context is used until the transaction is committed or rolled back. - * If the context is canceled, the sql package will roll back - * the transaction. [Tx.Commit] will return an error if the context provided to - * BeginTx is canceled. + * Size returns the size of the blob content in bytes. + */ + size(): number + } + interface Reader { + /** + * WriteTo reads from r and writes to w until there's no more data or + * an error occurs. + * The return value is the number of bytes written to w. * - * The provided [TxOptions] is optional and may be nil if defaults should be used. - * If a non-default isolation level is used that the driver doesn't support, - * an error will be returned. + * It implements the io.WriterTo interface. */ - beginTx(ctx: context.Context, opts: TxOptions): (Tx) + writeTo(w: io.Writer): number } - interface DB { + /** + * Writer writes bytes to a blob. + * + * It implements io.WriteCloser (https://golang.org/pkg/io/#Closer), and must be + * closed after all writes are done. + */ + interface Writer { + } + interface Writer { /** - * Begin starts a transaction. The default isolation level is dependent on - * the driver. + * Write implements the io.Writer interface (https://golang.org/pkg/io/#Writer). * - * Begin uses [context.Background] internally; to specify the context, use - * [DB.BeginTx]. + * Writes may happen asynchronously, so the returned error can be nil + * even if the actual write eventually fails. The write is only guaranteed to + * have succeeded if Close returns no error. */ - begin(): (Tx) + write(p: string|Array): number } - interface DB { + interface Writer { /** - * Driver returns the database's underlying driver. + * Close closes the blob writer. The write operation is not guaranteed + * to have succeeded until Close returns with no error. + * + * Close may return an error if the context provided to create the + * Writer is canceled or reaches its deadline. */ - driver(): any + close(): void } - interface DB { + interface Writer { /** - * Conn returns a single connection by either opening a new connection - * or returning an existing connection from the connection pool. Conn will - * block until either a connection is returned or ctx is canceled. - * Queries run on the same Conn will be run in the same database session. + * ReadFrom reads from r and writes to w until EOF or error. + * The return value is the number of bytes read from r. * - * Every Conn must be returned to the database pool after use by - * calling [Conn.Close]. + * It implements the io.ReaderFrom interface. */ - conn(ctx: context.Context): (Conn) + readFrom(r: io.Reader): number } +} + +namespace subscriptions { /** - * Tx is an in-progress database transaction. - * - * A transaction must end with a call to [Tx.Commit] or [Tx.Rollback]. - * - * After a call to [Tx.Commit] or [Tx.Rollback], all operations on the - * transaction fail with [ErrTxDone]. - * - * The statements prepared for a transaction by calling - * the transaction's [Tx.Prepare] or [Tx.Stmt] methods are closed - * by the call to [Tx.Commit] or [Tx.Rollback]. + * Broker defines a struct for managing subscriptions clients. */ - interface Tx { + interface Broker { } - interface Tx { + interface Broker { /** - * Commit commits the transaction. + * Clients returns a shallow copy of all registered clients indexed + * with their connection id. */ - commit(): void + clients(): _TygojaDict } - interface Tx { + interface Broker { /** - * Rollback aborts the transaction. + * ChunkedClients splits the current clients into a chunked slice. */ - rollback(): void + chunkedClients(chunkSize: number): Array> } - interface Tx { + interface Broker { /** - * PrepareContext creates a prepared statement for use within a transaction. - * - * The returned statement operates within the transaction and will be closed - * when the transaction has been committed or rolled back. - * - * To use an existing prepared statement on this transaction, see [Tx.Stmt]. - * - * The provided context will be used for the preparation of the context, not - * for the execution of the returned statement. The returned statement - * will run in the transaction context. + * TotalClients returns the total number of registered clients. */ - prepareContext(ctx: context.Context, query: string): (Stmt) + totalClients(): number } - interface Tx { + interface Broker { /** - * Prepare creates a prepared statement for use within a transaction. - * - * The returned statement operates within the transaction and will be closed - * when the transaction has been committed or rolled back. - * - * To use an existing prepared statement on this transaction, see [Tx.Stmt]. + * ClientById finds a registered client by its id. * - * Prepare uses [context.Background] internally; to specify the context, use - * [Tx.PrepareContext]. + * Returns non-nil error when client with clientId is not registered. */ - prepare(query: string): (Stmt) + clientById(clientId: string): Client } - interface Tx { + interface Broker { /** - * StmtContext returns a transaction-specific prepared statement from - * an existing statement. - * - * Example: - * - * ``` - * updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") - * ... - * tx, err := db.Begin() - * ... - * res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203) - * ``` - * - * The provided context is used for the preparation of the statement, not for the - * execution of the statement. - * - * The returned statement operates within the transaction and will be closed - * when the transaction has been committed or rolled back. + * Register adds a new client to the broker instance. */ - stmtContext(ctx: context.Context, stmt: Stmt): (Stmt) + register(client: Client): void } - interface Tx { + interface Broker { /** - * Stmt returns a transaction-specific prepared statement from - * an existing statement. - * - * Example: - * - * ``` - * updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") - * ... - * tx, err := db.Begin() - * ... - * res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203) - * ``` - * - * The returned statement operates within the transaction and will be closed - * when the transaction has been committed or rolled back. + * Unregister removes a single client by its id and marks it as discarded. * - * Stmt uses [context.Background] internally; to specify the context, use - * [Tx.StmtContext]. + * If client with clientId doesn't exist, this method does nothing. */ - stmt(stmt: Stmt): (Stmt) + unregister(clientId: string): void } - interface Tx { + /** + * Client is an interface for a generic subscription client. + */ + interface Client { + [key:string]: any; /** - * ExecContext executes a query that doesn't return rows. - * For example: an INSERT and UPDATE. + * Id Returns the unique id of the client. */ - execContext(ctx: context.Context, query: string, ...args: any[]): Result - } - interface Tx { + id(): string /** - * Exec executes a query that doesn't return rows. - * For example: an INSERT and UPDATE. + * Channel returns the client's communication channel. * - * Exec uses [context.Background] internally; to specify the context, use - * [Tx.ExecContext]. + * NB! The channel shouldn't be used after calling Discard(). */ - exec(query: string, ...args: any[]): Result - } - interface Tx { + channel(): undefined /** - * QueryContext executes a query that returns rows, typically a SELECT. + * Subscriptions returns a shallow copy of the client subscriptions matching the prefixes. + * If no prefix is specified, returns all subscriptions. */ - queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows) - } - interface Tx { + subscriptions(...prefixes: string[]): _TygojaDict /** - * Query executes a query that returns rows, typically a SELECT. + * Subscribe subscribes the client to the provided subscriptions list. * - * Query uses [context.Background] internally; to specify the context, use - * [Tx.QueryContext]. + * Each subscription can also have "options" (json serialized SubscriptionOptions) as query parameter. + * + * Example: + * + * ``` + * Subscribe( + * "subscriptionA", + * `subscriptionB?options={"query":{"a":1},"headers":{"x_token":"abc"}}`, + * ) + * ``` */ - query(query: string, ...args: any[]): (Rows) - } - interface Tx { + subscribe(...subs: string[]): void /** - * QueryRowContext executes a query that is expected to return at most one row. - * QueryRowContext always returns a non-nil value. Errors are deferred until - * [Row]'s Scan method is called. - * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. - * Otherwise, the [*Row.Scan] scans the first selected row and discards - * the rest. + * Unsubscribe unsubscribes the client from the provided subscriptions list. */ - queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row) - } - interface Tx { + unsubscribe(...subs: string[]): void /** - * QueryRow executes a query that is expected to return at most one row. - * QueryRow always returns a non-nil value. Errors are deferred until - * [Row]'s Scan method is called. - * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. - * Otherwise, the [*Row.Scan] scans the first selected row and discards - * the rest. - * - * QueryRow uses [context.Background] internally; to specify the context, use - * [Tx.QueryRowContext]. + * HasSubscription checks if the client is subscribed to `sub`. */ - queryRow(query: string, ...args: any[]): (Row) - } - /** - * Stmt is a prepared statement. - * A Stmt is safe for concurrent use by multiple goroutines. - * - * If a Stmt is prepared on a [Tx] or [Conn], it will be bound to a single - * underlying connection forever. If the [Tx] or [Conn] closes, the Stmt will - * become unusable and all operations will return an error. - * If a Stmt is prepared on a [DB], it will remain usable for the lifetime of the - * [DB]. When the Stmt needs to execute on a new underlying connection, it will - * prepare itself on the new connection automatically. - */ - interface Stmt { - } - interface Stmt { + hasSubscription(sub: string): boolean /** - * ExecContext executes a prepared statement with the given arguments and - * returns a [Result] summarizing the effect of the statement. + * Set stores any value to the client's context. */ - execContext(ctx: context.Context, ...args: any[]): Result - } - interface Stmt { + set(key: string, value: any): void /** - * Exec executes a prepared statement with the given arguments and - * returns a [Result] summarizing the effect of the statement. - * - * Exec uses [context.Background] internally; to specify the context, use - * [Stmt.ExecContext]. + * Unset removes a single value from the client's context. */ - exec(...args: any[]): Result - } - interface Stmt { + unset(key: string): void /** - * QueryContext executes a prepared query statement with the given arguments - * and returns the query results as a [*Rows]. + * Get retrieves the key value from the client's context. */ - queryContext(ctx: context.Context, ...args: any[]): (Rows) - } - interface Stmt { + get(key: string): any /** - * Query executes a prepared query statement with the given arguments - * and returns the query results as a *Rows. + * Discard marks the client as "discarded" (and closes its channel), + * meaning that it shouldn't be used anymore for sending new messages. * - * Query uses [context.Background] internally; to specify the context, use - * [Stmt.QueryContext]. + * It is safe to call Discard() multiple times. */ - query(...args: any[]): (Rows) - } - interface Stmt { + discard(): void /** - * QueryRowContext executes a prepared query statement with the given arguments. - * If an error occurs during the execution of the statement, that error will - * be returned by a call to Scan on the returned [*Row], which is always non-nil. - * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. - * Otherwise, the [*Row.Scan] scans the first selected row and discards - * the rest. + * IsDiscarded indicates whether the client has been "discarded" + * and should no longer be used. */ - queryRowContext(ctx: context.Context, ...args: any[]): (Row) + isDiscarded(): boolean + /** + * Send sends the specified message to the client's channel (if not discarded). + */ + send(m: Message): void } - interface Stmt { + /** + * Message defines a client's channel data. + */ + interface Message { + name: string + data: string|Array + } + interface Message { /** - * QueryRow executes a prepared query statement with the given arguments. - * If an error occurs during the execution of the statement, that error will - * be returned by a call to Scan on the returned [*Row], which is always non-nil. - * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. - * Otherwise, the [*Row.Scan] scans the first selected row and discards - * the rest. + * WriteSSE writes the current message in a SSE format into the provided writer. * - * Example usage: + * For example, writing to a router.Event: * * ``` - * var name string - * err := nameByUseridStmt.QueryRow(id).Scan(&name) + * m := Message{Name: "users/create", Data: []byte{...}} + * m.WriteSSE(e.Response, "yourEventId") + * e.Flush() * ``` - * - * QueryRow uses [context.Background] internally; to specify the context, use - * [Stmt.QueryRowContext]. */ - queryRow(...args: any[]): (Row) + writeSSE(w: io.Writer, eventId: string): void } - interface Stmt { +} + +/** + * Package sql provides a generic interface around SQL (or SQL-like) + * databases. + * + * The sql package must be used in conjunction with a database driver. + * See https://golang.org/s/sqldrivers for a list of drivers. + * + * Drivers that do not support context cancellation will not return until + * after the query is completed. + * + * For usage examples, see the wiki page at + * https://golang.org/s/sqlwiki. + */ +namespace sql { + /** + * TxOptions holds the transaction options to be used in [DB.BeginTx]. + */ + interface TxOptions { /** - * Close closes the statement. + * Isolation is the transaction isolation level. + * If zero, the driver or database's default level is used. */ - close(): void + isolation: IsolationLevel + readOnly: boolean } /** - * Rows is the result of a query. Its cursor starts before the first row - * of the result set. Use [Rows.Next] to advance from row to row. + * NullString represents a string that may be null. + * NullString implements the [Scanner] interface so + * it can be used as a scan destination: + * + * ``` + * var s NullString + * err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s) + * ... + * if s.Valid { + * // use s.String + * } else { + * // NULL value + * } + * ``` */ - interface Rows { + interface NullString { + string: string + valid: boolean // Valid is true if String is not NULL } - interface Rows { + interface NullString { /** - * Next prepares the next result row for reading with the [Rows.Scan] method. It - * returns true on success, or false if there is no next result row or an error - * happened while preparing it. [Rows.Err] should be consulted to distinguish between - * the two cases. - * - * Every call to [Rows.Scan], even the first one, must be preceded by a call to [Rows.Next]. + * Scan implements the [Scanner] interface. */ - next(): boolean + scan(value: any): void } - interface Rows { + interface NullString { /** - * NextResultSet prepares the next result set for reading. It reports whether - * there is further result sets, or false if there is no further result set - * or if there is an error advancing to it. The [Rows.Err] method should be consulted - * to distinguish between the two cases. - * - * After calling NextResultSet, the [Rows.Next] method should always be called before - * scanning. If there are further result sets they may not have rows in the result - * set. + * Value implements the [driver.Valuer] interface. */ - nextResultSet(): boolean + value(): any } - interface Rows { + /** + * DB is a database handle representing a pool of zero or more + * underlying connections. It's safe for concurrent use by multiple + * goroutines. + * + * The sql package creates and frees connections automatically; it + * also maintains a free pool of idle connections. If the database has + * a concept of per-connection state, such state can be reliably observed + * within a transaction ([Tx]) or connection ([Conn]). Once [DB.Begin] is called, the + * returned [Tx] is bound to a single connection. Once [Tx.Commit] or + * [Tx.Rollback] is called on the transaction, that transaction's + * connection is returned to [DB]'s idle connection pool. The pool size + * can be controlled with [DB.SetMaxIdleConns]. + */ + interface DB { + } + interface DB { /** - * Err returns the error, if any, that was encountered during iteration. - * Err may be called after an explicit or implicit [Rows.Close]. + * PingContext verifies a connection to the database is still alive, + * establishing a connection if necessary. */ - err(): void + pingContext(ctx: context.Context): void } - interface Rows { + interface DB { /** - * Columns returns the column names. - * Columns returns an error if the rows are closed. + * Ping verifies a connection to the database is still alive, + * establishing a connection if necessary. + * + * Ping uses [context.Background] internally; to specify the context, use + * [DB.PingContext]. */ - columns(): Array + ping(): void } - interface Rows { + interface DB { /** - * ColumnTypes returns column information such as column type, length, - * and nullable. Some information may not be available from some drivers. + * Close closes the database and prevents new queries from starting. + * Close then waits for all queries that have started processing on the server + * to finish. + * + * It is rare to Close a [DB], as the [DB] handle is meant to be + * long-lived and shared between many goroutines. */ - columnTypes(): Array<(ColumnType | undefined)> + close(): void } - interface Rows { + interface DB { /** - * Scan copies the columns in the current row into the values pointed - * at by dest. The number of values in dest must be the same as the - * number of columns in [Rows]. + * SetMaxIdleConns sets the maximum number of connections in the idle + * connection pool. * - * Scan converts columns read from the database into the following - * common Go types and special types provided by the sql package: + * If MaxOpenConns is greater than 0 but less than the new MaxIdleConns, + * then the new MaxIdleConns will be reduced to match the MaxOpenConns limit. * - * ``` - * *string - * *[]byte - * *int, *int8, *int16, *int32, *int64 - * *uint, *uint8, *uint16, *uint32, *uint64 - * *bool - * *float32, *float64 - * *interface{} - * *RawBytes - * *Rows (cursor value) - * any type implementing Scanner (see Scanner docs) - * ``` + * If n <= 0, no idle connections are retained. * - * In the most simple case, if the type of the value from the source - * column is an integer, bool or string type T and dest is of type *T, - * Scan simply assigns the value through the pointer. + * The default max idle connections is currently 2. This may change in + * a future release. + */ + setMaxIdleConns(n: number): void + } + interface DB { + /** + * SetMaxOpenConns sets the maximum number of open connections to the database. * - * Scan also converts between string and numeric types, as long as no - * information would be lost. While Scan stringifies all numbers - * scanned from numeric database columns into *string, scans into - * numeric types are checked for overflow. For example, a float64 with - * value 300 or a string with value "300" can scan into a uint16, but - * not into a uint8, though float64(255) or "255" can scan into a - * uint8. One exception is that scans of some float64 numbers to - * strings may lose information when stringifying. In general, scan - * floating point columns into *float64. - * - * If a dest argument has type *[]byte, Scan saves in that argument a - * copy of the corresponding data. The copy is owned by the caller and - * can be modified and held indefinitely. The copy can be avoided by - * using an argument of type [*RawBytes] instead; see the documentation - * for [RawBytes] for restrictions on its use. - * - * If an argument has type *interface{}, Scan copies the value - * provided by the underlying driver without conversion. When scanning - * from a source value of type []byte to *interface{}, a copy of the - * slice is made and the caller owns the result. + * If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than + * MaxIdleConns, then MaxIdleConns will be reduced to match the new + * MaxOpenConns limit. * - * Source values of type [time.Time] may be scanned into values of type - * *time.Time, *interface{}, *string, or *[]byte. When converting to - * the latter two, [time.RFC3339Nano] is used. + * If n <= 0, then there is no limit on the number of open connections. + * The default is 0 (unlimited). + */ + setMaxOpenConns(n: number): void + } + interface DB { + /** + * SetConnMaxLifetime sets the maximum amount of time a connection may be reused. * - * Source values of type bool may be scanned into types *bool, - * *interface{}, *string, *[]byte, or [*RawBytes]. + * Expired connections may be closed lazily before reuse. * - * For scanning into *bool, the source may be true, false, 1, 0, or - * string inputs parseable by [strconv.ParseBool]. + * If d <= 0, connections are not closed due to a connection's age. + */ + setConnMaxLifetime(d: time.Duration): void + } + interface DB { + /** + * SetConnMaxIdleTime sets the maximum amount of time a connection may be idle. * - * Scan can also convert a cursor returned from a query, such as - * "select cursor(select * from my_table) from dual", into a - * [*Rows] value that can itself be scanned from. The parent - * select query will close any cursor [*Rows] if the parent [*Rows] is closed. + * Expired connections may be closed lazily before reuse. * - * If any of the first arguments implementing [Scanner] returns an error, - * that error will be wrapped in the returned error. + * If d <= 0, connections are not closed due to a connection's idle time. */ - scan(...dest: any[]): void + setConnMaxIdleTime(d: time.Duration): void } - interface Rows { + interface DB { /** - * Close closes the [Rows], preventing further enumeration. If [Rows.Next] is called - * and returns false and there are no further result sets, - * the [Rows] are closed automatically and it will suffice to check the - * result of [Rows.Err]. Close is idempotent and does not affect the result of [Rows.Err]. + * Stats returns database statistics. */ - close(): void + stats(): DBStats } - /** - * A Result summarizes an executed SQL command. - */ - interface Result { - [key:string]: any; + interface DB { /** - * LastInsertId returns the integer generated by the database - * in response to a command. Typically this will be from an - * "auto increment" column when inserting a new row. Not all - * databases support this feature, and the syntax of such - * statements varies. + * PrepareContext creates a prepared statement for later queries or executions. + * Multiple queries or executions may be run concurrently from the + * returned statement. + * The caller must call the statement's [*Stmt.Close] method + * when the statement is no longer needed. + * + * The provided context is used for the preparation of the statement, not for the + * execution of the statement. */ - lastInsertId(): number + prepareContext(ctx: context.Context, query: string): (Stmt) + } + interface DB { /** - * RowsAffected returns the number of rows affected by an - * update, insert, or delete. Not every database or database - * driver may support this. + * Prepare creates a prepared statement for later queries or executions. + * Multiple queries or executions may be run concurrently from the + * returned statement. + * The caller must call the statement's [*Stmt.Close] method + * when the statement is no longer needed. + * + * Prepare uses [context.Background] internally; to specify the context, use + * [DB.PrepareContext]. */ - rowsAffected(): number + prepare(query: string): (Stmt) } -} - -namespace exec { - /** - * Cmd represents an external command being prepared or run. - * - * A Cmd cannot be reused after calling its [Cmd.Start], [Cmd.Run], - * [Cmd.Output], or [Cmd.CombinedOutput] methods. - */ - interface Cmd { + interface DB { /** - * Path is the path of the command to run. - * - * This is the only field that must be set to a non-zero - * value. If Path is relative, it is evaluated relative - * to Dir. + * ExecContext executes a query without returning any rows. + * The args are for any placeholder parameters in the query. */ - path: string + execContext(ctx: context.Context, query: string, ...args: any[]): Result + } + interface DB { /** - * Args holds command line arguments, including the command as Args[0]. - * If the Args field is empty or nil, Run uses {Path}. + * Exec executes a query without returning any rows. + * The args are for any placeholder parameters in the query. * - * In typical use, both Path and Args are set by calling Command. + * Exec uses [context.Background] internally; to specify the context, use + * [DB.ExecContext]. */ - args: Array + exec(query: string, ...args: any[]): Result + } + interface DB { /** - * Env specifies the environment of the process. - * Each entry is of the form "key=value". - * If Env is nil, the new process uses the current process's - * environment. - * If Env contains duplicate environment keys, only the last - * value in the slice for each duplicate key is used. - * As a special case on Windows, SYSTEMROOT is always added if - * missing and not explicitly set to the empty string. - * - * See also the Dir field, which may set PWD in the environment. + * QueryContext executes a query that returns rows, typically a SELECT. + * The args are for any placeholder parameters in the query. */ - env: Array + queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows) + } + interface DB { /** - * Dir specifies the working directory of the command. - * If Dir is the empty string, Run runs the command in the - * calling process's current directory. + * Query executes a query that returns rows, typically a SELECT. + * The args are for any placeholder parameters in the query. * - * On Unix systems, the value of Dir also determines the - * child process's PWD environment variable if not otherwise - * specified. A Unix process represents its working directory - * not by name but as an implicit reference to a node in the - * file tree. So, if the child process obtains its working - * directory by calling a function such as C's getcwd, which - * computes the canonical name by walking up the file tree, it - * will not recover the original value of Dir if that value - * was an alias involving symbolic links. However, if the - * child process calls Go's [os.Getwd] or GNU C's - * get_current_dir_name, and the value of PWD is an alias for - * the current directory, those functions will return the - * value of PWD, which matches the value of Dir. + * Query uses [context.Background] internally; to specify the context, use + * [DB.QueryContext]. */ - dir: string + query(query: string, ...args: any[]): (Rows) + } + interface DB { /** - * Stdin specifies the process's standard input. - * - * If Stdin is nil, the process reads from the null device (os.DevNull). - * - * If Stdin is an *os.File, the process's standard input is connected - * directly to that file. - * - * Otherwise, during the execution of the command a separate - * goroutine reads from Stdin and delivers that data to the command - * over a pipe. In this case, Wait does not complete until the goroutine - * stops copying, either because it has reached the end of Stdin - * (EOF or a read error), or because writing to the pipe returned an error, - * or because a nonzero WaitDelay was set and expired. - * - * Regardless of WaitDelay, Wait can block until a Read from - * Stdin completes. If you need to use a blocking io.Reader, - * use the StdinPipe method to get a pipe, copy from the Reader - * to the pipe, and arrange to close the Reader after Wait returns. + * QueryRowContext executes a query that is expected to return at most one row. + * QueryRowContext always returns a non-nil value. Errors are deferred until + * [Row]'s Scan method is called. + * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. + * Otherwise, [*Row.Scan] scans the first selected row and discards + * the rest. */ - stdin: io.Reader + queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row) + } + interface DB { /** - * Stdout and Stderr specify the process's standard output and error. - * - * If either is nil, Run connects the corresponding file descriptor - * to the null device (os.DevNull). - * - * If either is an *os.File, the corresponding output from the process - * is connected directly to that file. + * QueryRow executes a query that is expected to return at most one row. + * QueryRow always returns a non-nil value. Errors are deferred until + * [Row]'s Scan method is called. + * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. + * Otherwise, [*Row.Scan] scans the first selected row and discards + * the rest. * - * Otherwise, during the execution of the command a separate goroutine - * reads from the process over a pipe and delivers that data to the - * corresponding Writer. In this case, Wait does not complete until the - * goroutine reaches EOF or encounters an error or a nonzero WaitDelay - * expires. + * QueryRow uses [context.Background] internally; to specify the context, use + * [DB.QueryRowContext]. + */ + queryRow(query: string, ...args: any[]): (Row) + } + interface DB { + /** + * BeginTx starts a transaction. * - * Regardless of WaitDelay, Wait can block until a Write to - * Stdout or Stderr completes. If you need to use a blocking io.Writer, - * use the StdoutPipe or StderrPipe method to get a pipe, - * copy from the pipe to the Writer, and arrange to close the - * Writer after Wait returns. + * The provided context is used until the transaction is committed or rolled back. + * If the context is canceled, the sql package will roll back + * the transaction. [Tx.Commit] will return an error if the context provided to + * BeginTx is canceled. * - * If Stdout and Stderr are the same writer, and have a type that can - * be compared with ==, at most one goroutine at a time will call Write. + * The provided [TxOptions] is optional and may be nil if defaults should be used. + * If a non-default isolation level is used that the driver doesn't support, + * an error will be returned. */ - stdout: io.Writer - stderr: io.Writer + beginTx(ctx: context.Context, opts: TxOptions): (Tx) + } + interface DB { /** - * ExtraFiles specifies additional open files to be inherited by the - * new process. It does not include standard input, standard output, or - * standard error. If non-nil, entry i becomes file descriptor 3+i. + * Begin starts a transaction. The default isolation level is dependent on + * the driver. * - * ExtraFiles is not supported on Windows. + * Begin uses [context.Background] internally; to specify the context, use + * [DB.BeginTx]. */ - extraFiles: Array<(os.File | undefined)> + begin(): (Tx) + } + interface DB { /** - * SysProcAttr holds optional, operating system-specific attributes. - * Run passes it to os.StartProcess as the os.ProcAttr's Sys field. + * Driver returns the database's underlying driver. */ - sysProcAttr?: syscall.SysProcAttr + driver(): any + } + interface DB { /** - * Process is the underlying process, once started. + * Conn returns a single connection by either opening a new connection + * or returning an existing connection from the connection pool. Conn will + * block until either a connection is returned or ctx is canceled. + * Queries run on the same Conn will be run in the same database session. + * + * Every Conn must be returned to the database pool after use by + * calling [Conn.Close]. */ - process?: os.Process + conn(ctx: context.Context): (Conn) + } + /** + * Tx is an in-progress database transaction. + * + * A transaction must end with a call to [Tx.Commit] or [Tx.Rollback]. + * + * After a call to [Tx.Commit] or [Tx.Rollback], all operations on the + * transaction fail with [ErrTxDone]. + * + * The statements prepared for a transaction by calling + * the transaction's [Tx.Prepare] or [Tx.Stmt] methods are closed + * by the call to [Tx.Commit] or [Tx.Rollback]. + */ + interface Tx { + } + interface Tx { /** - * ProcessState contains information about an exited process. - * If the process was started successfully, Wait or Run will - * populate its ProcessState when the command completes. + * Commit commits the transaction. */ - processState?: os.ProcessState - err: Error // LookPath error, if any. + commit(): void + } + interface Tx { /** - * If Cancel is non-nil, the command must have been created with - * CommandContext and Cancel will be called when the command's - * Context is done. By default, CommandContext sets Cancel to - * call the Kill method on the command's Process. - * - * Typically a custom Cancel will send a signal to the command's - * Process, but it may instead take other actions to initiate cancellation, - * such as closing a stdin or stdout pipe or sending a shutdown request on a - * network socket. - * - * If the command exits with a success status after Cancel is - * called, and Cancel does not return an error equivalent to - * os.ErrProcessDone, then Wait and similar methods will return a non-nil - * error: either an error wrapping the one returned by Cancel, - * or the error from the Context. - * (If the command exits with a non-success status, or Cancel - * returns an error that wraps os.ErrProcessDone, Wait and similar methods - * continue to return the command's usual exit status.) - * - * If Cancel is set to nil, nothing will happen immediately when the command's - * Context is done, but a nonzero WaitDelay will still take effect. That may - * be useful, for example, to work around deadlocks in commands that do not - * support shutdown signals but are expected to always finish quickly. - * - * Cancel will not be called if Start returns a non-nil error. + * Rollback aborts the transaction. */ - cancel: () => void + rollback(): void + } + interface Tx { /** - * If WaitDelay is non-zero, it bounds the time spent waiting on two sources - * of unexpected delay in Wait: a child process that fails to exit after the - * associated Context is canceled, and a child process that exits but leaves - * its I/O pipes unclosed. - * - * The WaitDelay timer starts when either the associated Context is done or a - * call to Wait observes that the child process has exited, whichever occurs - * first. When the delay has elapsed, the command shuts down the child process - * and/or its I/O pipes. - * - * If the child process has failed to exit — perhaps because it ignored or - * failed to receive a shutdown signal from a Cancel function, or because no - * Cancel function was set — then it will be terminated using os.Process.Kill. + * PrepareContext creates a prepared statement for use within a transaction. * - * Then, if the I/O pipes communicating with the child process are still open, - * those pipes are closed in order to unblock any goroutines currently blocked - * on Read or Write calls. + * The returned statement operates within the transaction and will be closed + * when the transaction has been committed or rolled back. * - * If pipes are closed due to WaitDelay, no Cancel call has occurred, - * and the command has otherwise exited with a successful status, Wait and - * similar methods will return ErrWaitDelay instead of nil. + * To use an existing prepared statement on this transaction, see [Tx.Stmt]. * - * If WaitDelay is zero (the default), I/O pipes will be read until EOF, - * which might not occur until orphaned subprocesses of the command have - * also closed their descriptors for the pipes. - */ - waitDelay: time.Duration - } - interface Cmd { - /** - * String returns a human-readable description of c. - * It is intended only for debugging. - * In particular, it is not suitable for use as input to a shell. - * The output of String may vary across Go releases. + * The provided context will be used for the preparation of the context, not + * for the execution of the returned statement. The returned statement + * will run in the transaction context. */ - string(): string + prepareContext(ctx: context.Context, query: string): (Stmt) } - interface Cmd { + interface Tx { /** - * Run starts the specified command and waits for it to complete. + * Prepare creates a prepared statement for use within a transaction. * - * The returned error is nil if the command runs, has no problems - * copying stdin, stdout, and stderr, and exits with a zero exit - * status. + * The returned statement operates within the transaction and will be closed + * when the transaction has been committed or rolled back. * - * If the command starts but does not complete successfully, the error is of - * type [*ExitError]. Other error types may be returned for other situations. + * To use an existing prepared statement on this transaction, see [Tx.Stmt]. * - * If the calling goroutine has locked the operating system thread - * with [runtime.LockOSThread] and modified any inheritable OS-level - * thread state (for example, Linux or Plan 9 name spaces), the new - * process will inherit the caller's thread state. + * Prepare uses [context.Background] internally; to specify the context, use + * [Tx.PrepareContext]. */ - run(): void + prepare(query: string): (Stmt) } - interface Cmd { + interface Tx { /** - * Start starts the specified command but does not wait for it to complete. + * StmtContext returns a transaction-specific prepared statement from + * an existing statement. * - * If Start returns successfully, the c.Process field will be set. + * Example: * - * After a successful call to Start the [Cmd.Wait] method must be called in - * order to release associated system resources. + * ``` + * updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") + * ... + * tx, err := db.Begin() + * ... + * res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203) + * ``` + * + * The provided context is used for the preparation of the statement, not for the + * execution of the statement. + * + * The returned statement operates within the transaction and will be closed + * when the transaction has been committed or rolled back. */ - start(): void + stmtContext(ctx: context.Context, stmt: Stmt): (Stmt) } - interface Cmd { + interface Tx { /** - * Wait waits for the command to exit and waits for any copying to - * stdin or copying from stdout or stderr to complete. - * - * The command must have been started by [Cmd.Start]. - * - * The returned error is nil if the command runs, has no problems - * copying stdin, stdout, and stderr, and exits with a zero exit - * status. + * Stmt returns a transaction-specific prepared statement from + * an existing statement. * - * If the command fails to run or doesn't complete successfully, the - * error is of type [*ExitError]. Other error types may be - * returned for I/O problems. + * Example: * - * If any of c.Stdin, c.Stdout or c.Stderr are not an [*os.File], Wait also waits - * for the respective I/O loop copying to or from the process to complete. + * ``` + * updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") + * ... + * tx, err := db.Begin() + * ... + * res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203) + * ``` * - * Wait must not be called concurrently from multiple goroutines. - * A custom Cmd.Cancel function should not call Wait. + * The returned statement operates within the transaction and will be closed + * when the transaction has been committed or rolled back. * - * Wait releases any resources associated with the [Cmd]. + * Stmt uses [context.Background] internally; to specify the context, use + * [Tx.StmtContext]. */ - wait(): void + stmt(stmt: Stmt): (Stmt) } - interface Cmd { + interface Tx { /** - * Output runs the command and returns its standard output. - * Any returned error will usually be of type [*ExitError]. - * If c.Stderr was nil and the returned error is of type - * [*ExitError], Output populates the Stderr field of the - * returned error. + * ExecContext executes a query that doesn't return rows. + * For example: an INSERT and UPDATE. */ - output(): string|Array + execContext(ctx: context.Context, query: string, ...args: any[]): Result } - interface Cmd { + interface Tx { /** - * CombinedOutput runs the command and returns its combined standard - * output and standard error. + * Exec executes a query that doesn't return rows. + * For example: an INSERT and UPDATE. + * + * Exec uses [context.Background] internally; to specify the context, use + * [Tx.ExecContext]. */ - combinedOutput(): string|Array + exec(query: string, ...args: any[]): Result } - interface Cmd { + interface Tx { /** - * StdinPipe returns a pipe that will be connected to the command's - * standard input when the command starts. - * The pipe will be closed automatically after [Cmd.Wait] sees the command exit. - * A caller need only call Close to force the pipe to close sooner. - * For example, if the command being run will not exit until standard input - * is closed, the caller must close the pipe. + * QueryContext executes a query that returns rows, typically a SELECT. */ - stdinPipe(): io.WriteCloser + queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows) } - interface Cmd { + interface Tx { /** - * StdoutPipe returns a pipe that will be connected to the command's - * standard output when the command starts. + * Query executes a query that returns rows, typically a SELECT. * - * [Cmd.Wait] will close the pipe after seeing the command exit, so most callers - * need not close the pipe themselves. It is thus incorrect to call Wait - * before all reads from the pipe have completed. - * For the same reason, it is incorrect to call [Cmd.Run] when using StdoutPipe. - * See the example for idiomatic usage. + * Query uses [context.Background] internally; to specify the context, use + * [Tx.QueryContext]. */ - stdoutPipe(): io.ReadCloser + query(query: string, ...args: any[]): (Rows) } - interface Cmd { + interface Tx { /** - * StderrPipe returns a pipe that will be connected to the command's - * standard error when the command starts. - * - * [Cmd.Wait] will close the pipe after seeing the command exit, so most callers - * need not close the pipe themselves. It is thus incorrect to call Wait - * before all reads from the pipe have completed. - * For the same reason, it is incorrect to use [Cmd.Run] when using StderrPipe. - * See the StdoutPipe example for idiomatic usage. + * QueryRowContext executes a query that is expected to return at most one row. + * QueryRowContext always returns a non-nil value. Errors are deferred until + * [Row]'s Scan method is called. + * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. + * Otherwise, the [*Row.Scan] scans the first selected row and discards + * the rest. */ - stderrPipe(): io.ReadCloser + queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row) } - interface Cmd { + interface Tx { /** - * Environ returns a copy of the environment in which the command would be run - * as it is currently configured. + * QueryRow executes a query that is expected to return at most one row. + * QueryRow always returns a non-nil value. Errors are deferred until + * [Row]'s Scan method is called. + * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. + * Otherwise, the [*Row.Scan] scans the first selected row and discards + * the rest. + * + * QueryRow uses [context.Background] internally; to specify the context, use + * [Tx.QueryRowContext]. */ - environ(): Array + queryRow(query: string, ...args: any[]): (Row) } -} - -namespace store { /** - * Store defines a concurrent safe in memory key-value data store. + * Stmt is a prepared statement. + * A Stmt is safe for concurrent use by multiple goroutines. + * + * If a Stmt is prepared on a [Tx] or [Conn], it will be bound to a single + * underlying connection forever. If the [Tx] or [Conn] closes, the Stmt will + * become unusable and all operations will return an error. + * If a Stmt is prepared on a [DB], it will remain usable for the lifetime of the + * [DB]. When the Stmt needs to execute on a new underlying connection, it will + * prepare itself on the new connection automatically. */ - interface Store { - } - interface Store { - /** - * Reset clears the store and replaces the store data with a - * shallow copy of the provided newData. - */ - reset(newData: _TygojaDict): void - } - interface Store { - /** - * Length returns the current number of elements in the store. - */ - length(): number + interface Stmt { } - interface Store { + interface Stmt { /** - * RemoveAll removes all the existing store entries. + * ExecContext executes a prepared statement with the given arguments and + * returns a [Result] summarizing the effect of the statement. */ - removeAll(): void + execContext(ctx: context.Context, ...args: any[]): Result } - interface Store { + interface Stmt { /** - * Remove removes a single entry from the store. + * Exec executes a prepared statement with the given arguments and + * returns a [Result] summarizing the effect of the statement. * - * Remove does nothing if key doesn't exist in the store. + * Exec uses [context.Background] internally; to specify the context, use + * [Stmt.ExecContext]. */ - remove(key: K): void + exec(...args: any[]): Result } - interface Store { + interface Stmt { /** - * Has checks if element with the specified key exist or not. + * QueryContext executes a prepared query statement with the given arguments + * and returns the query results as a [*Rows]. */ - has(key: K): boolean + queryContext(ctx: context.Context, ...args: any[]): (Rows) } - interface Store { + interface Stmt { /** - * Get returns a single element value from the store. + * Query executes a prepared query statement with the given arguments + * and returns the query results as a *Rows. * - * If key is not set, the zero T value is returned. - */ - get(key: K): T - } - interface Store { - /** - * GetOk is similar to Get but returns also a boolean indicating whether the key exists or not. - */ - getOk(key: K): [T, boolean] - } - interface Store { - /** - * GetAll returns a shallow copy of the current store data. - */ - getAll(): _TygojaDict - } - interface Store { - /** - * Keys returns a slice with all of the store keys. - */ - keys(): Array - } - interface Store { - /** - * Values returns a slice with all of the store values. + * Query uses [context.Background] internally; to specify the context, use + * [Stmt.QueryContext]. */ - values(): Array + query(...args: any[]): (Rows) } - interface Store { + interface Stmt { /** - * Set sets (or overwrite if already exists) a new value for key. + * QueryRowContext executes a prepared query statement with the given arguments. + * If an error occurs during the execution of the statement, that error will + * be returned by a call to Scan on the returned [*Row], which is always non-nil. + * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. + * Otherwise, the [*Row.Scan] scans the first selected row and discards + * the rest. */ - set(key: K, value: T): void + queryRowContext(ctx: context.Context, ...args: any[]): (Row) } - interface Store { + interface Stmt { /** - * SetFunc sets (or overwrite if already exists) a new value resolved - * from the function callback for the provided key. - * - * The function callback receives as argument the old store element value (if exists). - * If there is no old store element, the argument will be the T zero value. + * QueryRow executes a prepared query statement with the given arguments. + * If an error occurs during the execution of the statement, that error will + * be returned by a call to Scan on the returned [*Row], which is always non-nil. + * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. + * Otherwise, the [*Row.Scan] scans the first selected row and discards + * the rest. * - * Example: + * Example usage: * * ``` - * s := store.New[string, int](nil) - * s.SetFunc("count", func(old int) int { - * return old + 1 - * }) + * var name string + * err := nameByUseridStmt.QueryRow(id).Scan(&name) * ``` - */ - setFunc(key: K, fn: (old: T) => T): void - } - interface Store { - /** - * GetOrSet retrieves a single existing value for the provided key - * or stores a new one if it doesn't exist. - */ - getOrSet(key: K, setFunc: () => T): T - } - interface Store { - /** - * SetIfLessThanLimit sets (or overwrite if already exist) a new value for key. - * - * This method is similar to Set() but **it will skip adding new elements** - * to the store if the store length has reached the specified limit. - * false is returned if maxAllowedElements limit is reached. - */ - setIfLessThanLimit(key: K, value: T, maxAllowedElements: number): boolean - } - interface Store { - /** - * UnmarshalJSON implements [json.Unmarshaler] and imports the - * provided JSON data into the store. * - * The store entries that match with the ones from the data will be overwritten with the new value. + * QueryRow uses [context.Background] internally; to specify the context, use + * [Stmt.QueryRowContext]. */ - unmarshalJSON(data: string|Array): void + queryRow(...args: any[]): (Row) } - interface Store { + interface Stmt { /** - * MarshalJSON implements [json.Marshaler] and export the current - * store data into valid JSON. + * Close closes the statement. */ - marshalJSON(): string|Array + close(): void } -} - -namespace subscriptions { /** - * Broker defines a struct for managing subscriptions clients. + * Rows is the result of a query. Its cursor starts before the first row + * of the result set. Use [Rows.Next] to advance from row to row. */ - interface Broker { + interface Rows { } - interface Broker { + interface Rows { /** - * Clients returns a shallow copy of all registered clients indexed - * with their connection id. + * Next prepares the next result row for reading with the [Rows.Scan] method. It + * returns true on success, or false if there is no next result row or an error + * happened while preparing it. [Rows.Err] should be consulted to distinguish between + * the two cases. + * + * Every call to [Rows.Scan], even the first one, must be preceded by a call to [Rows.Next]. */ - clients(): _TygojaDict + next(): boolean } - interface Broker { + interface Rows { /** - * ChunkedClients splits the current clients into a chunked slice. + * NextResultSet prepares the next result set for reading. It reports whether + * there is further result sets, or false if there is no further result set + * or if there is an error advancing to it. The [Rows.Err] method should be consulted + * to distinguish between the two cases. + * + * After calling NextResultSet, the [Rows.Next] method should always be called before + * scanning. If there are further result sets they may not have rows in the result + * set. */ - chunkedClients(chunkSize: number): Array> + nextResultSet(): boolean } - interface Broker { + interface Rows { /** - * TotalClients returns the total number of registered clients. + * Err returns the error, if any, that was encountered during iteration. + * Err may be called after an explicit or implicit [Rows.Close]. */ - totalClients(): number + err(): void } - interface Broker { + interface Rows { /** - * ClientById finds a registered client by its id. - * - * Returns non-nil error when client with clientId is not registered. + * Columns returns the column names. + * Columns returns an error if the rows are closed. */ - clientById(clientId: string): Client + columns(): Array } - interface Broker { + interface Rows { /** - * Register adds a new client to the broker instance. + * ColumnTypes returns column information such as column type, length, + * and nullable. Some information may not be available from some drivers. */ - register(client: Client): void + columnTypes(): Array<(ColumnType | undefined)> } - interface Broker { + interface Rows { /** - * Unregister removes a single client by its id and marks it as discarded. + * Scan copies the columns in the current row into the values pointed + * at by dest. The number of values in dest must be the same as the + * number of columns in [Rows]. * - * If client with clientId doesn't exist, this method does nothing. - */ - unregister(clientId: string): void - } - /** - * Client is an interface for a generic subscription client. - */ - interface Client { - [key:string]: any; - /** - * Id Returns the unique id of the client. - */ - id(): string - /** - * Channel returns the client's communication channel. + * Scan converts columns read from the database into the following + * common Go types and special types provided by the sql package: * - * NB! The channel shouldn't be used after calling Discard(). - */ - channel(): undefined - /** - * Subscriptions returns a shallow copy of the client subscriptions matching the prefixes. - * If no prefix is specified, returns all subscriptions. - */ - subscriptions(...prefixes: string[]): _TygojaDict - /** - * Subscribe subscribes the client to the provided subscriptions list. + * ``` + * *string + * *[]byte + * *int, *int8, *int16, *int32, *int64 + * *uint, *uint8, *uint16, *uint32, *uint64 + * *bool + * *float32, *float64 + * *interface{} + * *RawBytes + * *Rows (cursor value) + * any type implementing Scanner (see Scanner docs) + * ``` * - * Each subscription can also have "options" (json serialized SubscriptionOptions) as query parameter. + * In the most simple case, if the type of the value from the source + * column is an integer, bool or string type T and dest is of type *T, + * Scan simply assigns the value through the pointer. * - * Example: + * Scan also converts between string and numeric types, as long as no + * information would be lost. While Scan stringifies all numbers + * scanned from numeric database columns into *string, scans into + * numeric types are checked for overflow. For example, a float64 with + * value 300 or a string with value "300" can scan into a uint16, but + * not into a uint8, though float64(255) or "255" can scan into a + * uint8. One exception is that scans of some float64 numbers to + * strings may lose information when stringifying. In general, scan + * floating point columns into *float64. * - * ``` - * Subscribe( - * "subscriptionA", - * `subscriptionB?options={"query":{"a":1},"headers":{"x_token":"abc"}}`, - * ) - * ``` + * If a dest argument has type *[]byte, Scan saves in that argument a + * copy of the corresponding data. The copy is owned by the caller and + * can be modified and held indefinitely. The copy can be avoided by + * using an argument of type [*RawBytes] instead; see the documentation + * for [RawBytes] for restrictions on its use. + * + * If an argument has type *interface{}, Scan copies the value + * provided by the underlying driver without conversion. When scanning + * from a source value of type []byte to *interface{}, a copy of the + * slice is made and the caller owns the result. + * + * Source values of type [time.Time] may be scanned into values of type + * *time.Time, *interface{}, *string, or *[]byte. When converting to + * the latter two, [time.RFC3339Nano] is used. + * + * Source values of type bool may be scanned into types *bool, + * *interface{}, *string, *[]byte, or [*RawBytes]. + * + * For scanning into *bool, the source may be true, false, 1, 0, or + * string inputs parseable by [strconv.ParseBool]. + * + * Scan can also convert a cursor returned from a query, such as + * "select cursor(select * from my_table) from dual", into a + * [*Rows] value that can itself be scanned from. The parent + * select query will close any cursor [*Rows] if the parent [*Rows] is closed. + * + * If any of the first arguments implementing [Scanner] returns an error, + * that error will be wrapped in the returned error. */ - subscribe(...subs: string[]): void + scan(...dest: any[]): void + } + interface Rows { /** - * Unsubscribe unsubscribes the client from the provided subscriptions list. + * Close closes the [Rows], preventing further enumeration. If [Rows.Next] is called + * and returns false and there are no further result sets, + * the [Rows] are closed automatically and it will suffice to check the + * result of [Rows.Err]. Close is idempotent and does not affect the result of [Rows.Err]. */ - unsubscribe(...subs: string[]): void + close(): void + } + /** + * A Result summarizes an executed SQL command. + */ + interface Result { + [key:string]: any; /** - * HasSubscription checks if the client is subscribed to `sub`. + * LastInsertId returns the integer generated by the database + * in response to a command. Typically this will be from an + * "auto increment" column when inserting a new row. Not all + * databases support this feature, and the syntax of such + * statements varies. */ - hasSubscription(sub: string): boolean + lastInsertId(): number /** - * Set stores any value to the client's context. + * RowsAffected returns the number of rows affected by an + * update, insert, or delete. Not every database or database + * driver may support this. */ - set(key: string, value: any): void + rowsAffected(): number + } +} + +namespace search { + /** + * Result defines the returned search result structure. + */ + interface Result { + items: any + page: number + perPage: number + totalItems: number + totalPages: number + } + /** + * ResolverResult defines a single FieldResolver.Resolve() successfully parsed result. + */ + interface ResolverResult { /** - * Unset removes a single value from the client's context. + * Identifier is the plain SQL identifier/column that will be used + * in the final db expression as left or right operand. */ - unset(key: string): void + identifier: string /** - * Get retrieves the key value from the client's context. + * NullFallback specify the preference for how NULL or empty values + * should be resolved (default to "auto"). + * + * Set to NullFallbackDisabled to prevent any COALESCE or NULL fallbacks. + * Set to NullFallbackEnforced to prefer COALESCE or NULL fallbacks when needed. */ - get(key: string): any + nullFallback: NullFallbackPreference /** - * Discard marks the client as "discarded" (and closes its channel), - * meaning that it shouldn't be used anymore for sending new messages. - * - * It is safe to call Discard() multiple times. + * Params is a map with db placeholder->value pairs that will be added + * to the query when building both resolved operands/sides in a single expression. */ - discard(): void + params: dbx.Params /** - * IsDiscarded indicates whether the client has been "discarded" - * and should no longer be used. + * MultiMatchSubQuery is an optional sub query expression that will be added + * in addition to the combined ResolverResult expression during build. */ - isDiscarded(): boolean + multiMatchSubQuery?: MultiMatchSubquery /** - * Send sends the specified message to the client's channel (if not discarded). + * AfterBuild is an optional function that will be called after building + * and combining the result of both resolved operands/sides in a single expression. */ - send(m: Message): void + afterBuild: (expr: dbx.Expression) => dbx.Expression } +} + +namespace router { + // @ts-ignore + import validation = ozzo_validation /** - * Message defines a client's channel data. + * ApiError defines the struct for a basic api error response. */ - interface Message { - name: string - data: string|Array + interface ApiError { + data: _TygojaDict + message: string + status: number } - interface Message { + interface ApiError { /** - * WriteSSE writes the current message in a SSE format into the provided writer. - * - * For example, writing to a router.Event: - * - * ``` - * m := Message{Name: "users/create", Data: []byte{...}} - * m.WriteSSE(e.Response, "yourEventId") - * e.Flush() - * ``` + * Error makes it compatible with the `error` interface. */ - writeSSE(w: io.Writer, eventId: string): void + error(): string + } + interface ApiError { + /** + * RawData returns the unformatted error data (could be an internal error, text, etc.) + */ + rawData(): any + } + interface ApiError { + /** + * Is reports whether the current ApiError wraps the target. + */ + is(target: Error): boolean } -} - -namespace auth { /** - * @todo refactor and consider replace with a plain struct + * Event specifies based Route handler event that is usually intended + * to be embedded as part of a custom event struct. * - * Provider defines a common interface for an OAuth2 client. + * NB! It is expected that the Response and Request fields are always set. */ - interface Provider { - [key:string]: any; + type _sSFfqHr = hook.Event + interface Event extends _sSFfqHr { + response: http.ResponseWriter + request?: http.Request + } + interface Event { /** - * @todo temp backport + * Written reports whether the current response has already been written. * - * Order returns the sorting order of the provider usually used in the auth methods list response. + * This method always returns false if e.ResponseWritter doesn't implement the WriteTracker interface + * (all router package handlers receives a ResponseWritter that implements it unless explicitly replaced with a custom one). */ - logo(): string + written(): boolean + } + interface Event { /** - * @todo temp backport + * Status reports the status code of the current response. * - * Order returns the sorting order of the provider usually used in the auth methods list response. + * This method always returns 0 if e.Response doesn't implement the StatusTracker interface + * (all router package handlers receives a ResponseWritter that implements it unless explicitly replaced with a custom one). */ - order(): number + status(): number + } + interface Event { /** - * Context returns the context associated with the provider (if any). + * Flush flushes buffered data to the current response. + * + * Returns [http.ErrNotSupported] if e.Response doesn't implement the [http.Flusher] interface + * (all router package handlers receives a ResponseWritter that implements it unless explicitly replaced with a custom one). */ - context(): context.Context + flush(): void + } + interface Event { /** - * SetContext assigns the specified context to the current provider. + * IsTLS reports whether the connection on which the request was received is TLS. */ - setContext(ctx: context.Context): void + isTLS(): boolean + } + interface Event { /** - * PKCE indicates whether the provider can use the PKCE flow. + * SetCookie is an alias for [http.SetCookie]. + * + * SetCookie adds a Set-Cookie header to the current response's headers. + * The provided cookie must have a valid Name. + * Invalid cookies may be silently dropped. */ - pkce(): boolean + setCookie(cookie: http.Cookie): void + } + interface Event { /** - * SetPKCE toggles the state whether the provider can use the PKCE flow or not. + * RemoteIP returns the IP address of the client that sent the request. + * + * IPv6 addresses are returned expanded. + * For example, "2001:db8::1" becomes "2001:0db8:0000:0000:0000:0000:0000:0001". + * + * Note that if you are behind reverse proxy(ies), this method returns + * the IP of the last connecting proxy. */ - setPKCE(enable: boolean): void + remoteIP(): string + } + interface Event { /** - * DisplayName usually returns provider name as it is officially written - * and it could be used directly in the UI. + * FindUploadedFiles extracts all form files of "key" from a http request + * and returns a slice with filesystem.File instances (if any). */ - displayName(): string - /** - * SetDisplayName sets the provider's display name. - */ - setDisplayName(displayName: string): void - /** - * Scopes returns the provider access permissions that will be requested. - */ - scopes(): Array - /** - * SetScopes sets the provider access permissions that will be requested later. - */ - setScopes(scopes: Array): void - /** - * ClientId returns the provider client's app ID. - */ - clientId(): string - /** - * SetClientId sets the provider client's ID. - */ - setClientId(clientId: string): void - /** - * ClientSecret returns the provider client's app secret. - */ - clientSecret(): string - /** - * SetClientSecret sets the provider client's app secret. - */ - setClientSecret(secret: string): void - /** - * RedirectURL returns the end address to redirect the user - * going through the OAuth flow. - */ - redirectURL(): string + findUploadedFiles(key: string): Array<(filesystem.File | undefined)> + } + interface Event { /** - * SetRedirectURL sets the provider's RedirectURL. + * Get retrieves single value from the current event data store. */ - setRedirectURL(url: string): void + get(key: string): any + } + interface Event { /** - * AuthURL returns the provider's authorization service url. + * GetAll returns a copy of the current event data store. */ - authURL(): string + getAll(): _TygojaDict + } + interface Event { /** - * SetAuthURL sets the provider's AuthURL. + * Set saves single value into the current event data store. */ - setAuthURL(url: string): void + set(key: string, value: any): void + } + interface Event { /** - * TokenURL returns the provider's token exchange service url. + * SetAll saves all items from m into the current event data store. */ - tokenURL(): string + setAll(m: _TygojaDict): void + } + interface Event { /** - * SetTokenURL sets the provider's TokenURL. + * String writes a plain string response. */ - setTokenURL(url: string): void + string(status: number, data: string): void + } + interface Event { /** - * UserInfoURL returns the provider's user info api url. + * HTML writes an HTML response. */ - userInfoURL(): string + html(status: number, data: string): void + } + interface Event { /** - * SetUserInfoURL sets the provider's UserInfoURL. + * JSON writes a JSON response. + * + * It also provides a generic response data fields picker if the "fields" query parameter is set. + * For example, if you are requesting `?fields=a,b` for `e.JSON(200, map[string]int{ "a":1, "b":2, "c":3 })`, + * it should result in a JSON response like: `{"a":1, "b": 2}`. + * + * Note that invalid UTF8 characters are mangled for compatibility + * with earlier versions and to prevent unnecessary causing a response error. */ - setUserInfoURL(url: string): void + json(status: number, data: any): void + } + interface Event { /** - * Extra returns a shallow copy of any custom config data - * that the provider may need. + * XML writes an XML response. + * It automatically prepends the generic [xml.Header] string to the response. */ - extra(): _TygojaDict + xml(status: number, data: any): void + } + interface Event { /** - * SetExtra updates the provider's custom config data. + * Stream streams the specified reader into the response. */ - setExtra(data: _TygojaDict): void + stream(status: number, contentType: string, reader: io.Reader): void + } + interface Event { /** - * Client returns an http client using the provided token. + * Blob writes a blob (bytes slice) response. */ - client(token: oauth2.Token): (any) + blob(status: number, contentType: string, b: string|Array): void + } + interface Event { /** - * BuildAuthURL returns a URL to the provider's consent page - * that asks for permissions for the required scopes explicitly. + * FileFS serves the specified filename from fsys. + * + * It is similar to [echo.FileFS] for consistency with earlier versions. */ - buildAuthURL(state: string, ...opts: oauth2.AuthCodeOption[]): string + fileFS(fsys: fs.FS, filename: string): void + } + interface Event { /** - * FetchToken converts an authorization code to token. + * NoContent writes a response with no body (ex. 204). */ - fetchToken(code: string, ...opts: oauth2.AuthCodeOption[]): (oauth2.Token) + noContent(status: number): void + } + interface Event { /** - * FetchRawUserInfo requests and marshalizes into `result` the - * the OAuth user api response. + * Redirect writes a redirect response to the specified url. + * The status code must be in between 300 – 399 range. */ - fetchRawUserInfo(token: oauth2.Token): string|Array + redirect(status: number, url: string): void + } + interface Event { + error(status: number, message: string, errData: any): (ApiError) + } + interface Event { + badRequestError(message: string, errData: any): (ApiError) + } + interface Event { + notFoundError(message: string, errData: any): (ApiError) + } + interface Event { + forbiddenError(message: string, errData: any): (ApiError) + } + interface Event { + unauthorizedError(message: string, errData: any): (ApiError) + } + interface Event { + tooManyRequestsError(message: string, errData: any): (ApiError) + } + interface Event { + internalServerError(message: string, errData: any): (ApiError) + } + interface Event { /** - * FetchAuthUser is similar to FetchRawUserInfo, but normalizes and - * marshalizes the user api response into a standardized AuthUser struct. + * BindBody unmarshal the request body into the provided dst. + * + * dst must be either a struct pointer or map[string]any. + * + * The rules how the body will be scanned depends on the request Content-Type. + * + * Currently the following Content-Types are supported: + * ``` + * - application/json + * - text/xml, application/xml + * - multipart/form-data, application/x-www-form-urlencoded + * ``` + * + * Respectively the following struct tags are supported (again, which one will be used depends on the Content-Type): + * ``` + * - "json" (json body)- uses the builtin Go json package for unmarshaling. + * - "xml" (xml body) - uses the builtin Go xml package for unmarshaling. + * - "form" (form data) - utilizes the custom [router.UnmarshalRequestData] method. + * ``` + * + * NB! When dst is a struct make sure that it doesn't have public fields + * that shouldn't be bindable and it is advisible such fields to be unexported + * or have a separate struct just for the binding. For example: + * + * ``` + * data := struct{ + * somethingPrivate string + * + * Title string `json:"title" form:"title"` + * Total int `json:"total" form:"total"` + * }{} + * err := e.BindBody(&data) + * ``` */ - fetchAuthUser(token: oauth2.Token): (AuthUser) + bindBody(dst: any): void } /** - * AuthUser defines a standardized OAuth2 user data structure. + * Router defines a thin wrapper around the standard Go [http.ServeMux] by + * adding support for routing sub-groups, middlewares and other common utils. + * + * Example: + * + * ``` + * r := NewRouter[*MyEvent](eventFactory) + * + * // middlewares + * r.BindFunc(m1, m2) + * + * // routes + * r.GET("/test", handler1) + * + * // sub-routers/groups + * api := r.Group("/api") + * api.GET("/admins", handler2) + * + * // generate a http.ServeMux instance based on the router configurations + * mux, _ := r.BuildMux() + * + * http.ListenAndServe("localhost:8090", mux) + * ``` */ - interface AuthUser { - expiry: types.DateTime - rawUser: _TygojaDict - id: string - name: string - username: string - avatarURL: string - accessToken: string - refreshToken: string - /** - * The VERIFIED OAuth2 account email. - * - * It must be empty if the provider is not able to verify the email ownership. - */ - email: string - /** - * @todo - * deprecated: use AvatarURL instead - * AvatarUrl will be removed after dropping v0.22 support - */ - avatarUrl: string + type _scWyLcr = RouterGroup + interface Router extends _scWyLcr { } - interface AuthUser { + interface Router { /** - * MarshalJSON implements the [json.Marshaler] interface. - * - * @todo remove after dropping v0.22 support + * BuildMux constructs a new mux [http.Handler] instance from the current router configurations. */ - marshalJSON(): string|Array + buildMux(): http.Handler } } @@ -20666,640 +20605,143 @@ namespace auth { * Then use a value of that type in log calls: * * ``` - * slog.Debug("frobbing", "value", expensive{arg}) - * ``` - * - * Now computeExpensiveValue will only be called when the line is enabled. - * - * The built-in handlers acquire a lock before calling [io.Writer.Write] - * to ensure that exactly one [Record] is written at a time in its entirety. - * Although each log record has a timestamp, - * the built-in handlers do not use that time to sort the written records. - * User-defined handlers are responsible for their own locking and sorting. - * - * # Writing a handler - * - * For a guide to writing a custom handler, see https://golang.org/s/slog-handler-guide. - */ -namespace slog { - // @ts-ignore - import loginternal = internal - /** - * A Logger records structured information about each call to its - * Log, Debug, Info, Warn, and Error methods. - * For each call, it creates a [Record] and passes it to a [Handler]. - * - * To create a new Logger, call [New] or a Logger method - * that begins "With". - */ - interface Logger { - } - interface Logger { - /** - * Handler returns l's Handler. - */ - handler(): Handler - } - interface Logger { - /** - * With returns a Logger that includes the given attributes - * in each output operation. Arguments are converted to - * attributes as if by [Logger.Log]. - */ - with(...args: any[]): (Logger) - } - interface Logger { - /** - * WithGroup returns a Logger that starts a group, if name is non-empty. - * The keys of all attributes added to the Logger will be qualified by the given - * name. (How that qualification happens depends on the [Handler.WithGroup] - * method of the Logger's Handler.) - * - * If name is empty, WithGroup returns the receiver. - */ - withGroup(name: string): (Logger) - } - interface Logger { - /** - * Enabled reports whether l emits log records at the given context and level. - */ - enabled(ctx: context.Context, level: Level): boolean - } - interface Logger { - /** - * Log emits a log record with the current time and the given level and message. - * The Record's Attrs consist of the Logger's attributes followed by - * the Attrs specified by args. - * - * The attribute arguments are processed as follows: - * ``` - * - If an argument is an Attr, it is used as is. - * - If an argument is a string and this is not the last argument, - * the following argument is treated as the value and the two are combined - * into an Attr. - * - Otherwise, the argument is treated as a value with key "!BADKEY". - * ``` - */ - log(ctx: context.Context, level: Level, msg: string, ...args: any[]): void - } - interface Logger { - /** - * LogAttrs is a more efficient version of [Logger.Log] that accepts only Attrs. - */ - logAttrs(ctx: context.Context, level: Level, msg: string, ...attrs: Attr[]): void - } - interface Logger { - /** - * Debug logs at [LevelDebug]. - * It uses [context.Background] internally; to specify the context, use - * [Logger.DebugContext]. - */ - debug(msg: string, ...args: any[]): void - } - interface Logger { - /** - * DebugContext logs at [LevelDebug] with the given context. - */ - debugContext(ctx: context.Context, msg: string, ...args: any[]): void - } - interface Logger { - /** - * Info logs at [LevelInfo]. - * It uses [context.Background] internally; to specify the context, use - * [Logger.InfoContext]. - */ - info(msg: string, ...args: any[]): void - } - interface Logger { - /** - * InfoContext logs at [LevelInfo] with the given context. - */ - infoContext(ctx: context.Context, msg: string, ...args: any[]): void - } - interface Logger { - /** - * Warn logs at [LevelWarn]. - * It uses [context.Background] internally; to specify the context, use - * [Logger.WarnContext]. - */ - warn(msg: string, ...args: any[]): void - } - interface Logger { - /** - * WarnContext logs at [LevelWarn] with the given context. - */ - warnContext(ctx: context.Context, msg: string, ...args: any[]): void - } - interface Logger { - /** - * Error logs at [LevelError]. - * It uses [context.Background] internally; to specify the context, use - * [Logger.ErrorContext]. - */ - error(msg: string, ...args: any[]): void - } - interface Logger { - /** - * ErrorContext logs at [LevelError] with the given context. - */ - errorContext(ctx: context.Context, msg: string, ...args: any[]): void - } -} - -namespace hook { - /** - * Event implements [Resolver] and it is intended to be used as a base - * Hook event that you can embed in your custom typed event structs. - * - * Example: - * - * ``` - * type CustomEvent struct { - * hook.Event - * - * SomeField int - * } - * ``` - */ - interface Event { - } - interface Event { - /** - * Next calls the next hook handler. - */ - next(): void - } - /** - * Handler defines a single Hook handler. - * Multiple handlers can share the same id. - * If Id is not explicitly set it will be autogenerated by Hook.Add and Hook.AddHandler. - */ - interface Handler { - /** - * Func defines the handler function to execute. - * - * Note that users need to call e.Next() in order to proceed with - * the execution of the hook chain. - */ - func: (_arg0: T) => void - /** - * Id is the unique identifier of the handler. - * - * It could be used later to remove the handler from a hook via [Hook.Remove]. - * - * If missing, an autogenerated value will be assigned when adding - * the handler to a hook. - */ - id: string - /** - * Priority allows changing the default exec priority of the handler within a hook. - * - * If 0, the handler will be executed in the same order it was registered. - */ - priority: number - } - /** - * Hook defines a generic concurrent safe structure for managing event hooks. - * - * When using custom event it must embed the base [hook.Event]. - * - * Example: - * - * ``` - * type CustomEvent struct { - * hook.Event - * SomeField int - * } - * - * h := Hook[*CustomEvent]{} - * - * h.BindFunc(func(e *CustomEvent) error { - * println(e.SomeField) - * - * return e.Next() - * }) - * - * h.Trigger(&CustomEvent{ SomeField: 123 }) - * ``` - */ - interface Hook { - } - interface Hook { - /** - * Bind registers the provided handler to the current hooks queue. - * - * If handler.Id is empty it is updated with autogenerated value. - * - * If a handler from the current hook list has Id matching handler.Id - * then the old handler is replaced with the new one. - */ - bind(handler: Handler): string - } - interface Hook { - /** - * BindFunc is similar to Bind but registers a new handler from just the provided function. - * - * The registered handler is added with a default 0 priority and the id will be autogenerated. - * - * If you want to register a handler with custom priority or id use the [Hook.Bind] method. - */ - bindFunc(fn: (e: T) => void): string - } - interface Hook { - /** - * Unbind removes one or many hook handler by their id. - */ - unbind(...idsToRemove: string[]): void - } - interface Hook { - /** - * UnbindAll removes all registered handlers. - */ - unbindAll(): void - } - interface Hook { - /** - * Length returns to total number of registered hook handlers. - */ - length(): number - } - interface Hook { - /** - * Trigger executes all registered hook handlers one by one - * with the specified event as an argument. - * - * Optionally, this method allows also to register additional one off - * handler funcs that will be temporary appended to the handlers queue. - * - * NB! Each hook handler must call event.Next() in order the hook chain to proceed. - */ - trigger(event: T, ...oneOffHandlerFuncs: ((_arg0: T) => void)[]): void - } - /** - * TaggedHook defines a proxy hook which register handlers that are triggered only - * if the TaggedHook.tags are empty or includes at least one of the event data tag(s). - */ - type _sdgUcvX = mainHook - interface TaggedHook extends _sdgUcvX { - } - interface TaggedHook { - /** - * CanTriggerOn checks if the current TaggedHook can be triggered with - * the provided event data tags. - * - * It returns always true if the hook doesn't have any tags. - */ - canTriggerOn(tagsToCheck: Array): boolean - } - interface TaggedHook { - /** - * Bind registers the provided handler to the current hooks queue. - * - * It is similar to [Hook.Bind] with the difference that the handler - * function is invoked only if the event data tags satisfy h.CanTriggerOn. - */ - bind(handler: Handler): string - } - interface TaggedHook { - /** - * BindFunc registers a new handler with the specified function. - * - * It is similar to [Hook.Bind] with the difference that the handler - * function is invoked only if the event data tags satisfy h.CanTriggerOn. - */ - bindFunc(fn: (e: T) => void): string - } -} - -namespace search { - /** - * Result defines the returned search result structure. - */ - interface Result { - items: any - page: number - perPage: number - totalItems: number - totalPages: number - } - /** - * ResolverResult defines a single FieldResolver.Resolve() successfully parsed result. - */ - interface ResolverResult { - /** - * Identifier is the plain SQL identifier/column that will be used - * in the final db expression as left or right operand. - */ - identifier: string - /** - * NullFallback specify the preference for how NULL or empty values - * should be resolved (default to "auto"). - * - * Set to NullFallbackDisabled to prevent any COALESCE or NULL fallbacks. - * Set to NullFallbackEnforced to prefer COALESCE or NULL fallbacks when needed. - */ - nullFallback: NullFallbackPreference - /** - * Params is a map with db placeholder->value pairs that will be added - * to the query when building both resolved operands/sides in a single expression. - */ - params: dbx.Params - /** - * MultiMatchSubQuery is an optional sub query expression that will be added - * in addition to the combined ResolverResult expression during build. - */ - multiMatchSubQuery?: MultiMatchSubquery - /** - * AfterBuild is an optional function that will be called after building - * and combining the result of both resolved operands/sides in a single expression. - */ - afterBuild: (expr: dbx.Expression) => dbx.Expression - } -} - -namespace router { - // @ts-ignore - import validation = ozzo_validation - /** - * ApiError defines the struct for a basic api error response. - */ - interface ApiError { - data: _TygojaDict - message: string - status: number - } - interface ApiError { - /** - * Error makes it compatible with the `error` interface. - */ - error(): string - } - interface ApiError { - /** - * RawData returns the unformatted error data (could be an internal error, text, etc.) - */ - rawData(): any - } - interface ApiError { - /** - * Is reports whether the current ApiError wraps the target. - */ - is(target: Error): boolean - } + * slog.Debug("frobbing", "value", expensive{arg}) + * ``` + * + * Now computeExpensiveValue will only be called when the line is enabled. + * + * The built-in handlers acquire a lock before calling [io.Writer.Write] + * to ensure that exactly one [Record] is written at a time in its entirety. + * Although each log record has a timestamp, + * the built-in handlers do not use that time to sort the written records. + * User-defined handlers are responsible for their own locking and sorting. + * + * # Writing a handler + * + * For a guide to writing a custom handler, see https://golang.org/s/slog-handler-guide. + */ +namespace slog { + // @ts-ignore + import loginternal = internal /** - * Event specifies based Route handler event that is usually intended - * to be embedded as part of a custom event struct. + * A Logger records structured information about each call to its + * Log, Debug, Info, Warn, and Error methods. + * For each call, it creates a [Record] and passes it to a [Handler]. * - * NB! It is expected that the Response and Request fields are always set. + * To create a new Logger, call [New] or a Logger method + * that begins "With". */ - type _spTaHbt = hook.Event - interface Event extends _spTaHbt { - response: http.ResponseWriter - request?: http.Request - } - interface Event { - /** - * Written reports whether the current response has already been written. - * - * This method always returns false if e.ResponseWritter doesn't implement the WriteTracker interface - * (all router package handlers receives a ResponseWritter that implements it unless explicitly replaced with a custom one). - */ - written(): boolean - } - interface Event { - /** - * Status reports the status code of the current response. - * - * This method always returns 0 if e.Response doesn't implement the StatusTracker interface - * (all router package handlers receives a ResponseWritter that implements it unless explicitly replaced with a custom one). - */ - status(): number - } - interface Event { - /** - * Flush flushes buffered data to the current response. - * - * Returns [http.ErrNotSupported] if e.Response doesn't implement the [http.Flusher] interface - * (all router package handlers receives a ResponseWritter that implements it unless explicitly replaced with a custom one). - */ - flush(): void + interface Logger { } - interface Event { + interface Logger { /** - * IsTLS reports whether the connection on which the request was received is TLS. + * Handler returns l's Handler. */ - isTLS(): boolean + handler(): Handler } - interface Event { + interface Logger { /** - * SetCookie is an alias for [http.SetCookie]. - * - * SetCookie adds a Set-Cookie header to the current response's headers. - * The provided cookie must have a valid Name. - * Invalid cookies may be silently dropped. + * With returns a Logger that includes the given attributes + * in each output operation. Arguments are converted to + * attributes as if by [Logger.Log]. */ - setCookie(cookie: http.Cookie): void + with(...args: any[]): (Logger) } - interface Event { + interface Logger { /** - * RemoteIP returns the IP address of the client that sent the request. - * - * IPv6 addresses are returned expanded. - * For example, "2001:db8::1" becomes "2001:0db8:0000:0000:0000:0000:0000:0001". + * WithGroup returns a Logger that starts a group, if name is non-empty. + * The keys of all attributes added to the Logger will be qualified by the given + * name. (How that qualification happens depends on the [Handler.WithGroup] + * method of the Logger's Handler.) * - * Note that if you are behind reverse proxy(ies), this method returns - * the IP of the last connecting proxy. - */ - remoteIP(): string - } - interface Event { - /** - * FindUploadedFiles extracts all form files of "key" from a http request - * and returns a slice with filesystem.File instances (if any). - */ - findUploadedFiles(key: string): Array<(filesystem.File | undefined)> - } - interface Event { - /** - * Get retrieves single value from the current event data store. - */ - get(key: string): any - } - interface Event { - /** - * GetAll returns a copy of the current event data store. - */ - getAll(): _TygojaDict - } - interface Event { - /** - * Set saves single value into the current event data store. - */ - set(key: string, value: any): void - } - interface Event { - /** - * SetAll saves all items from m into the current event data store. - */ - setAll(m: _TygojaDict): void - } - interface Event { - /** - * String writes a plain string response. + * If name is empty, WithGroup returns the receiver. */ - string(status: number, data: string): void + withGroup(name: string): (Logger) } - interface Event { + interface Logger { /** - * HTML writes an HTML response. + * Enabled reports whether l emits log records at the given context and level. */ - html(status: number, data: string): void + enabled(ctx: context.Context, level: Level): boolean } - interface Event { + interface Logger { /** - * JSON writes a JSON response. - * - * It also provides a generic response data fields picker if the "fields" query parameter is set. - * For example, if you are requesting `?fields=a,b` for `e.JSON(200, map[string]int{ "a":1, "b":2, "c":3 })`, - * it should result in a JSON response like: `{"a":1, "b": 2}`. + * Log emits a log record with the current time and the given level and message. + * The Record's Attrs consist of the Logger's attributes followed by + * the Attrs specified by args. * - * Note that invalid UTF8 characters are mangled for compatibility - * with earlier versions and to prevent unnecessary causing a response error. + * The attribute arguments are processed as follows: + * ``` + * - If an argument is an Attr, it is used as is. + * - If an argument is a string and this is not the last argument, + * the following argument is treated as the value and the two are combined + * into an Attr. + * - Otherwise, the argument is treated as a value with key "!BADKEY". + * ``` */ - json(status: number, data: any): void + log(ctx: context.Context, level: Level, msg: string, ...args: any[]): void } - interface Event { + interface Logger { /** - * XML writes an XML response. - * It automatically prepends the generic [xml.Header] string to the response. + * LogAttrs is a more efficient version of [Logger.Log] that accepts only Attrs. */ - xml(status: number, data: any): void + logAttrs(ctx: context.Context, level: Level, msg: string, ...attrs: Attr[]): void } - interface Event { + interface Logger { /** - * Stream streams the specified reader into the response. + * Debug logs at [LevelDebug]. + * It uses [context.Background] internally; to specify the context, use + * [Logger.DebugContext]. */ - stream(status: number, contentType: string, reader: io.Reader): void + debug(msg: string, ...args: any[]): void } - interface Event { + interface Logger { /** - * Blob writes a blob (bytes slice) response. + * DebugContext logs at [LevelDebug] with the given context. */ - blob(status: number, contentType: string, b: string|Array): void + debugContext(ctx: context.Context, msg: string, ...args: any[]): void } - interface Event { + interface Logger { /** - * FileFS serves the specified filename from fsys. - * - * It is similar to [echo.FileFS] for consistency with earlier versions. + * Info logs at [LevelInfo]. + * It uses [context.Background] internally; to specify the context, use + * [Logger.InfoContext]. */ - fileFS(fsys: fs.FS, filename: string): void + info(msg: string, ...args: any[]): void } - interface Event { + interface Logger { /** - * NoContent writes a response with no body (ex. 204). + * InfoContext logs at [LevelInfo] with the given context. */ - noContent(status: number): void + infoContext(ctx: context.Context, msg: string, ...args: any[]): void } - interface Event { + interface Logger { /** - * Redirect writes a redirect response to the specified url. - * The status code must be in between 300 – 399 range. + * Warn logs at [LevelWarn]. + * It uses [context.Background] internally; to specify the context, use + * [Logger.WarnContext]. */ - redirect(status: number, url: string): void - } - interface Event { - error(status: number, message: string, errData: any): (ApiError) - } - interface Event { - badRequestError(message: string, errData: any): (ApiError) - } - interface Event { - notFoundError(message: string, errData: any): (ApiError) - } - interface Event { - forbiddenError(message: string, errData: any): (ApiError) - } - interface Event { - unauthorizedError(message: string, errData: any): (ApiError) - } - interface Event { - tooManyRequestsError(message: string, errData: any): (ApiError) - } - interface Event { - internalServerError(message: string, errData: any): (ApiError) + warn(msg: string, ...args: any[]): void } - interface Event { - /** - * BindBody unmarshal the request body into the provided dst. - * - * dst must be either a struct pointer or map[string]any. - * - * The rules how the body will be scanned depends on the request Content-Type. - * - * Currently the following Content-Types are supported: - * ``` - * - application/json - * - text/xml, application/xml - * - multipart/form-data, application/x-www-form-urlencoded - * ``` - * - * Respectively the following struct tags are supported (again, which one will be used depends on the Content-Type): - * ``` - * - "json" (json body)- uses the builtin Go json package for unmarshaling. - * - "xml" (xml body) - uses the builtin Go xml package for unmarshaling. - * - "form" (form data) - utilizes the custom [router.UnmarshalRequestData] method. - * ``` - * - * NB! When dst is a struct make sure that it doesn't have public fields - * that shouldn't be bindable and it is advisible such fields to be unexported - * or have a separate struct just for the binding. For example: - * - * ``` - * data := struct{ - * somethingPrivate string - * - * Title string `json:"title" form:"title"` - * Total int `json:"total" form:"total"` - * }{} - * err := e.BindBody(&data) - * ``` + interface Logger { + /** + * WarnContext logs at [LevelWarn] with the given context. */ - bindBody(dst: any): void + warnContext(ctx: context.Context, msg: string, ...args: any[]): void } - /** - * Router defines a thin wrapper around the standard Go [http.ServeMux] by - * adding support for routing sub-groups, middlewares and other common utils. - * - * Example: - * - * ``` - * r := NewRouter[*MyEvent](eventFactory) - * - * // middlewares - * r.BindFunc(m1, m2) - * - * // routes - * r.GET("/test", handler1) - * - * // sub-routers/groups - * api := r.Group("/api") - * api.GET("/admins", handler2) - * - * // generate a http.ServeMux instance based on the router configurations - * mux, _ := r.BuildMux() - * - * http.ListenAndServe("localhost:8090", mux) - * ``` - */ - type _sEiobfY = RouterGroup - interface Router extends _sEiobfY { + interface Logger { + /** + * Error logs at [LevelError]. + * It uses [context.Background] internally; to specify the context, use + * [Logger.ErrorContext]. + */ + error(msg: string, ...args: any[]): void } - interface Router { + interface Logger { /** - * BuildMux constructs a new mux [http.Handler] instance from the current router configurations. + * ErrorContext logs at [LevelError] with the given context. */ - buildMux(): http.Handler + errorContext(ctx: context.Context, msg: string, ...args: any[]): void } } @@ -22246,142 +21688,452 @@ namespace cobra { * ValidateFlagGroups validates the mutuallyExclusive/oneRequired/requiredAsGroup logic and returns the * first error encountered. */ - validateFlagGroups(): void - } - interface Command { + validateFlagGroups(): void + } + interface Command { + /** + * GenPowerShellCompletionFile generates powershell completion file without descriptions. + */ + genPowerShellCompletionFile(filename: string): void + } + interface Command { + /** + * GenPowerShellCompletion generates powershell completion file without descriptions + * and writes it to the passed writer. + */ + genPowerShellCompletion(w: io.Writer): void + } + interface Command { + /** + * GenPowerShellCompletionFileWithDesc generates powershell completion file with descriptions. + */ + genPowerShellCompletionFileWithDesc(filename: string): void + } + interface Command { + /** + * GenPowerShellCompletionWithDesc generates powershell completion file with descriptions + * and writes it to the passed writer. + */ + genPowerShellCompletionWithDesc(w: io.Writer): void + } + interface Command { + /** + * MarkFlagRequired instructs the various shell completion implementations to + * prioritize the named flag when performing completion, + * and causes your command to report an error if invoked without the flag. + */ + markFlagRequired(name: string): void + } + interface Command { + /** + * MarkPersistentFlagRequired instructs the various shell completion implementations to + * prioritize the named persistent flag when performing completion, + * and causes your command to report an error if invoked without the flag. + */ + markPersistentFlagRequired(name: string): void + } + interface Command { + /** + * MarkFlagFilename instructs the various shell completion implementations to + * limit completions for the named flag to the specified file extensions. + */ + markFlagFilename(name: string, ...extensions: string[]): void + } + interface Command { + /** + * MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists. + * The bash completion script will call the bash function f for the flag. + * + * This will only work for bash completion. + * It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows + * to register a Go function which will work across all shells. + */ + markFlagCustom(name: string, f: string): void + } + interface Command { + /** + * MarkPersistentFlagFilename instructs the various shell completion + * implementations to limit completions for the named persistent flag to the + * specified file extensions. + */ + markPersistentFlagFilename(name: string, ...extensions: string[]): void + } + interface Command { + /** + * MarkFlagDirname instructs the various shell completion implementations to + * limit completions for the named flag to directory names. + */ + markFlagDirname(name: string): void + } + interface Command { + /** + * MarkPersistentFlagDirname instructs the various shell completion + * implementations to limit completions for the named persistent flag to + * directory names. + */ + markPersistentFlagDirname(name: string): void + } + interface Command { + /** + * GenZshCompletionFile generates zsh completion file including descriptions. + */ + genZshCompletionFile(filename: string): void + } + interface Command { + /** + * GenZshCompletion generates zsh completion file including descriptions + * and writes it to the passed writer. + */ + genZshCompletion(w: io.Writer): void + } + interface Command { + /** + * GenZshCompletionFileNoDesc generates zsh completion file without descriptions. + */ + genZshCompletionFileNoDesc(filename: string): void + } + interface Command { + /** + * GenZshCompletionNoDesc generates zsh completion file without descriptions + * and writes it to the passed writer. + */ + genZshCompletionNoDesc(w: io.Writer): void + } + interface Command { + /** + * MarkZshCompPositionalArgumentFile only worked for zsh and its behavior was + * not consistent with Bash completion. It has therefore been disabled. + * Instead, when no other completion is specified, file completion is done by + * default for every argument. One can disable file completion on a per-argument + * basis by using ValidArgsFunction and ShellCompDirectiveNoFileComp. + * To achieve file extension filtering, one can use ValidArgsFunction and + * ShellCompDirectiveFilterFileExt. + * + * Deprecated + */ + markZshCompPositionalArgumentFile(argPosition: number, ...patterns: string[]): void + } + interface Command { + /** + * MarkZshCompPositionalArgumentWords only worked for zsh. It has therefore + * been disabled. + * To achieve the same behavior across all shells, one can use + * ValidArgs (for the first argument only) or ValidArgsFunction for + * any argument (can include the first one also). + * + * Deprecated + */ + markZshCompPositionalArgumentWords(argPosition: number, ...words: string[]): void + } +} + +namespace exec { + /** + * Cmd represents an external command being prepared or run. + * + * A Cmd cannot be reused after calling its [Cmd.Start], [Cmd.Run], + * [Cmd.Output], or [Cmd.CombinedOutput] methods. + */ + interface Cmd { + /** + * Path is the path of the command to run. + * + * This is the only field that must be set to a non-zero + * value. If Path is relative, it is evaluated relative + * to Dir. + */ + path: string + /** + * Args holds command line arguments, including the command as Args[0]. + * If the Args field is empty or nil, Run uses {Path}. + * + * In typical use, both Path and Args are set by calling Command. + */ + args: Array + /** + * Env specifies the environment of the process. + * Each entry is of the form "key=value". + * If Env is nil, the new process uses the current process's + * environment. + * If Env contains duplicate environment keys, only the last + * value in the slice for each duplicate key is used. + * As a special case on Windows, SYSTEMROOT is always added if + * missing and not explicitly set to the empty string. + * + * See also the Dir field, which may set PWD in the environment. + */ + env: Array + /** + * Dir specifies the working directory of the command. + * If Dir is the empty string, Run runs the command in the + * calling process's current directory. + * + * On Unix systems, the value of Dir also determines the + * child process's PWD environment variable if not otherwise + * specified. A Unix process represents its working directory + * not by name but as an implicit reference to a node in the + * file tree. So, if the child process obtains its working + * directory by calling a function such as C's getcwd, which + * computes the canonical name by walking up the file tree, it + * will not recover the original value of Dir if that value + * was an alias involving symbolic links. However, if the + * child process calls Go's [os.Getwd] or GNU C's + * get_current_dir_name, and the value of PWD is an alias for + * the current directory, those functions will return the + * value of PWD, which matches the value of Dir. + */ + dir: string + /** + * Stdin specifies the process's standard input. + * + * If Stdin is nil, the process reads from the null device (os.DevNull). + * + * If Stdin is an *os.File, the process's standard input is connected + * directly to that file. + * + * Otherwise, during the execution of the command a separate + * goroutine reads from Stdin and delivers that data to the command + * over a pipe. In this case, Wait does not complete until the goroutine + * stops copying, either because it has reached the end of Stdin + * (EOF or a read error), or because writing to the pipe returned an error, + * or because a nonzero WaitDelay was set and expired. + * + * Regardless of WaitDelay, Wait can block until a Read from + * Stdin completes. If you need to use a blocking io.Reader, + * use the StdinPipe method to get a pipe, copy from the Reader + * to the pipe, and arrange to close the Reader after Wait returns. + */ + stdin: io.Reader /** - * GenPowerShellCompletionFile generates powershell completion file without descriptions. + * Stdout and Stderr specify the process's standard output and error. + * + * If either is nil, Run connects the corresponding file descriptor + * to the null device (os.DevNull). + * + * If either is an *os.File, the corresponding output from the process + * is connected directly to that file. + * + * Otherwise, during the execution of the command a separate goroutine + * reads from the process over a pipe and delivers that data to the + * corresponding Writer. In this case, Wait does not complete until the + * goroutine reaches EOF or encounters an error or a nonzero WaitDelay + * expires. + * + * Regardless of WaitDelay, Wait can block until a Write to + * Stdout or Stderr completes. If you need to use a blocking io.Writer, + * use the StdoutPipe or StderrPipe method to get a pipe, + * copy from the pipe to the Writer, and arrange to close the + * Writer after Wait returns. + * + * If Stdout and Stderr are the same writer, and have a type that can + * be compared with ==, at most one goroutine at a time will call Write. */ - genPowerShellCompletionFile(filename: string): void - } - interface Command { + stdout: io.Writer + stderr: io.Writer /** - * GenPowerShellCompletion generates powershell completion file without descriptions - * and writes it to the passed writer. + * ExtraFiles specifies additional open files to be inherited by the + * new process. It does not include standard input, standard output, or + * standard error. If non-nil, entry i becomes file descriptor 3+i. + * + * ExtraFiles is not supported on Windows. */ - genPowerShellCompletion(w: io.Writer): void - } - interface Command { + extraFiles: Array<(os.File | undefined)> /** - * GenPowerShellCompletionFileWithDesc generates powershell completion file with descriptions. + * SysProcAttr holds optional, operating system-specific attributes. + * Run passes it to os.StartProcess as the os.ProcAttr's Sys field. */ - genPowerShellCompletionFileWithDesc(filename: string): void - } - interface Command { + sysProcAttr?: syscall.SysProcAttr /** - * GenPowerShellCompletionWithDesc generates powershell completion file with descriptions - * and writes it to the passed writer. + * Process is the underlying process, once started. */ - genPowerShellCompletionWithDesc(w: io.Writer): void - } - interface Command { + process?: os.Process /** - * MarkFlagRequired instructs the various shell completion implementations to - * prioritize the named flag when performing completion, - * and causes your command to report an error if invoked without the flag. + * ProcessState contains information about an exited process. + * If the process was started successfully, Wait or Run will + * populate its ProcessState when the command completes. */ - markFlagRequired(name: string): void - } - interface Command { + processState?: os.ProcessState + err: Error // LookPath error, if any. /** - * MarkPersistentFlagRequired instructs the various shell completion implementations to - * prioritize the named persistent flag when performing completion, - * and causes your command to report an error if invoked without the flag. + * If Cancel is non-nil, the command must have been created with + * CommandContext and Cancel will be called when the command's + * Context is done. By default, CommandContext sets Cancel to + * call the Kill method on the command's Process. + * + * Typically a custom Cancel will send a signal to the command's + * Process, but it may instead take other actions to initiate cancellation, + * such as closing a stdin or stdout pipe or sending a shutdown request on a + * network socket. + * + * If the command exits with a success status after Cancel is + * called, and Cancel does not return an error equivalent to + * os.ErrProcessDone, then Wait and similar methods will return a non-nil + * error: either an error wrapping the one returned by Cancel, + * or the error from the Context. + * (If the command exits with a non-success status, or Cancel + * returns an error that wraps os.ErrProcessDone, Wait and similar methods + * continue to return the command's usual exit status.) + * + * If Cancel is set to nil, nothing will happen immediately when the command's + * Context is done, but a nonzero WaitDelay will still take effect. That may + * be useful, for example, to work around deadlocks in commands that do not + * support shutdown signals but are expected to always finish quickly. + * + * Cancel will not be called if Start returns a non-nil error. */ - markPersistentFlagRequired(name: string): void - } - interface Command { + cancel: () => void /** - * MarkFlagFilename instructs the various shell completion implementations to - * limit completions for the named flag to the specified file extensions. + * If WaitDelay is non-zero, it bounds the time spent waiting on two sources + * of unexpected delay in Wait: a child process that fails to exit after the + * associated Context is canceled, and a child process that exits but leaves + * its I/O pipes unclosed. + * + * The WaitDelay timer starts when either the associated Context is done or a + * call to Wait observes that the child process has exited, whichever occurs + * first. When the delay has elapsed, the command shuts down the child process + * and/or its I/O pipes. + * + * If the child process has failed to exit — perhaps because it ignored or + * failed to receive a shutdown signal from a Cancel function, or because no + * Cancel function was set — then it will be terminated using os.Process.Kill. + * + * Then, if the I/O pipes communicating with the child process are still open, + * those pipes are closed in order to unblock any goroutines currently blocked + * on Read or Write calls. + * + * If pipes are closed due to WaitDelay, no Cancel call has occurred, + * and the command has otherwise exited with a successful status, Wait and + * similar methods will return ErrWaitDelay instead of nil. + * + * If WaitDelay is zero (the default), I/O pipes will be read until EOF, + * which might not occur until orphaned subprocesses of the command have + * also closed their descriptors for the pipes. */ - markFlagFilename(name: string, ...extensions: string[]): void + waitDelay: time.Duration } - interface Command { + interface Cmd { /** - * MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists. - * The bash completion script will call the bash function f for the flag. - * - * This will only work for bash completion. - * It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows - * to register a Go function which will work across all shells. + * String returns a human-readable description of c. + * It is intended only for debugging. + * In particular, it is not suitable for use as input to a shell. + * The output of String may vary across Go releases. */ - markFlagCustom(name: string, f: string): void + string(): string } - interface Command { + interface Cmd { /** - * MarkPersistentFlagFilename instructs the various shell completion - * implementations to limit completions for the named persistent flag to the - * specified file extensions. + * Run starts the specified command and waits for it to complete. + * + * The returned error is nil if the command runs, has no problems + * copying stdin, stdout, and stderr, and exits with a zero exit + * status. + * + * If the command starts but does not complete successfully, the error is of + * type [*ExitError]. Other error types may be returned for other situations. + * + * If the calling goroutine has locked the operating system thread + * with [runtime.LockOSThread] and modified any inheritable OS-level + * thread state (for example, Linux or Plan 9 name spaces), the new + * process will inherit the caller's thread state. */ - markPersistentFlagFilename(name: string, ...extensions: string[]): void + run(): void } - interface Command { + interface Cmd { /** - * MarkFlagDirname instructs the various shell completion implementations to - * limit completions for the named flag to directory names. + * Start starts the specified command but does not wait for it to complete. + * + * If Start returns successfully, the c.Process field will be set. + * + * After a successful call to Start the [Cmd.Wait] method must be called in + * order to release associated system resources. */ - markFlagDirname(name: string): void + start(): void } - interface Command { + interface Cmd { /** - * MarkPersistentFlagDirname instructs the various shell completion - * implementations to limit completions for the named persistent flag to - * directory names. + * Wait waits for the command to exit and waits for any copying to + * stdin or copying from stdout or stderr to complete. + * + * The command must have been started by [Cmd.Start]. + * + * The returned error is nil if the command runs, has no problems + * copying stdin, stdout, and stderr, and exits with a zero exit + * status. + * + * If the command fails to run or doesn't complete successfully, the + * error is of type [*ExitError]. Other error types may be + * returned for I/O problems. + * + * If any of c.Stdin, c.Stdout or c.Stderr are not an [*os.File], Wait also waits + * for the respective I/O loop copying to or from the process to complete. + * + * Wait must not be called concurrently from multiple goroutines. + * A custom Cmd.Cancel function should not call Wait. + * + * Wait releases any resources associated with the [Cmd]. */ - markPersistentFlagDirname(name: string): void + wait(): void } - interface Command { + interface Cmd { /** - * GenZshCompletionFile generates zsh completion file including descriptions. + * Output runs the command and returns its standard output. + * Any returned error will usually be of type [*ExitError]. + * If c.Stderr was nil and the returned error is of type + * [*ExitError], Output populates the Stderr field of the + * returned error. */ - genZshCompletionFile(filename: string): void + output(): string|Array } - interface Command { + interface Cmd { /** - * GenZshCompletion generates zsh completion file including descriptions - * and writes it to the passed writer. + * CombinedOutput runs the command and returns its combined standard + * output and standard error. */ - genZshCompletion(w: io.Writer): void + combinedOutput(): string|Array } - interface Command { + interface Cmd { /** - * GenZshCompletionFileNoDesc generates zsh completion file without descriptions. + * StdinPipe returns a pipe that will be connected to the command's + * standard input when the command starts. + * The pipe will be closed automatically after [Cmd.Wait] sees the command exit. + * A caller need only call Close to force the pipe to close sooner. + * For example, if the command being run will not exit until standard input + * is closed, the caller must close the pipe. */ - genZshCompletionFileNoDesc(filename: string): void + stdinPipe(): io.WriteCloser } - interface Command { + interface Cmd { /** - * GenZshCompletionNoDesc generates zsh completion file without descriptions - * and writes it to the passed writer. + * StdoutPipe returns a pipe that will be connected to the command's + * standard output when the command starts. + * + * [Cmd.Wait] will close the pipe after seeing the command exit, so most callers + * need not close the pipe themselves. It is thus incorrect to call Wait + * before all reads from the pipe have completed. + * For the same reason, it is incorrect to call [Cmd.Run] when using StdoutPipe. + * See the example for idiomatic usage. */ - genZshCompletionNoDesc(w: io.Writer): void + stdoutPipe(): io.ReadCloser } - interface Command { + interface Cmd { /** - * MarkZshCompPositionalArgumentFile only worked for zsh and its behavior was - * not consistent with Bash completion. It has therefore been disabled. - * Instead, when no other completion is specified, file completion is done by - * default for every argument. One can disable file completion on a per-argument - * basis by using ValidArgsFunction and ShellCompDirectiveNoFileComp. - * To achieve file extension filtering, one can use ValidArgsFunction and - * ShellCompDirectiveFilterFileExt. + * StderrPipe returns a pipe that will be connected to the command's + * standard error when the command starts. * - * Deprecated + * [Cmd.Wait] will close the pipe after seeing the command exit, so most callers + * need not close the pipe themselves. It is thus incorrect to call Wait + * before all reads from the pipe have completed. + * For the same reason, it is incorrect to use [Cmd.Run] when using StderrPipe. + * See the StdoutPipe example for idiomatic usage. */ - markZshCompPositionalArgumentFile(argPosition: number, ...patterns: string[]): void + stderrPipe(): io.ReadCloser } - interface Command { + interface Cmd { /** - * MarkZshCompPositionalArgumentWords only worked for zsh. It has therefore - * been disabled. - * To achieve the same behavior across all shells, one can use - * ValidArgs (for the first argument only) or ValidArgsFunction for - * any argument (can include the first one also). - * - * Deprecated + * Environ returns a copy of the environment in which the command would be run + * as it is currently configured. */ - markZshCompPositionalArgumentWords(argPosition: number, ...words: string[]): void + environ(): Array } } @@ -22413,412 +22165,294 @@ namespace mailer { } } -namespace sync { - // @ts-ignore - import isync = sync - /** - * A Locker represents an object that can be locked and unlocked. - */ - interface Locker { - [key:string]: any; - lock(): void - unlock(): void - } - // @ts-ignore - import rtatomic = atomic -} - -namespace syscall { - // @ts-ignore - import errpkg = errors +namespace auth { /** - * SysProcIDMap holds Container ID to Host ID mappings used for User Namespaces in Linux. - * See user_namespaces(7). + * @todo refactor and consider replace with a plain struct * - * Note that User Namespaces are not available on a number of popular Linux - * versions (due to security issues), or are available but subject to AppArmor - * restrictions like in Ubuntu 24.04. - */ - interface SysProcIDMap { - containerID: number // Container ID. - hostID: number // Host ID. - size: number // Size. - } - // @ts-ignore - import errorspkg = errors - /** - * Credential holds user and group identities to be assumed - * by a child process started by [StartProcess]. - */ - interface Credential { - uid: number // User ID. - gid: number // Group ID. - groups: Array // Supplementary group IDs. - noSetGroups: boolean // If true, don't set supplementary groups - } - /** - * A Signal is a number describing a process signal. - * It implements the [os.Signal] interface. - */ - interface Signal extends Number{} - interface Signal { - signal(): void - } - interface Signal { - string(): string - } -} - -namespace time { - /** - * A Month specifies a month of the year (January = 1, ...). + * Provider defines a common interface for an OAuth2 client. */ - interface Month extends Number{} - interface Month { + interface Provider { + [key:string]: any; /** - * String returns the English name of the month ("January", "February", ...). + * @todo temp backport + * + * Order returns the sorting order of the provider usually used in the auth methods list response. */ - string(): string - } - /** - * A Weekday specifies a day of the week (Sunday = 0, ...). - */ - interface Weekday extends Number{} - interface Weekday { + logo(): string /** - * String returns the English name of the day ("Sunday", "Monday", ...). + * @todo temp backport + * + * Order returns the sorting order of the provider usually used in the auth methods list response. */ - string(): string - } - /** - * A Location maps time instants to the zone in use at that time. - * Typically, the Location represents the collection of time offsets - * in use in a geographical area. For many Locations the time offset varies - * depending on whether daylight savings time is in use at the time instant. - * - * Location is used to provide a time zone in a printed Time value and for - * calculations involving intervals that may cross daylight savings time - * boundaries. - */ - interface Location { - } - interface Location { + order(): number /** - * String returns a descriptive name for the time zone information, - * corresponding to the name argument to [LoadLocation] or [FixedZone]. + * Context returns the context associated with the provider (if any). */ - string(): string - } -} - -namespace context { -} - -namespace io { - /** - * WriteCloser is the interface that groups the basic Write and Close methods. - */ - interface WriteCloser { - [key:string]: any; - } -} - -namespace fs { -} - -namespace net { - /** - * Addr represents a network end point address. - * - * The two methods [Addr.Network] and [Addr.String] conventionally return strings - * that can be passed as the arguments to [Dial], but the exact form - * and meaning of the strings is up to the implementation. - */ - interface Addr { - [key:string]: any; - network(): string // name of the network (for example, "tcp", "udp") - string(): string // string form of address (for example, "192.0.2.1:25", "[2001:db8::1]:80") - } - // @ts-ignore - import _cgopackage = cgo -} - -/** - * Package url parses URLs and implements query escaping. - * - * See RFC 3986. This package generally follows RFC 3986, except where - * it deviates for compatibility reasons. - * RFC 6874 followed for IPv6 zone literals. - */ -namespace url { - /** - * A URL represents a parsed URL (technically, a URI reference). - * - * The general form represented is: - * - * ``` - * [scheme:][//[userinfo@]host][/]path[?query][#fragment] - * ``` - * - * URLs that do not start with a slash after the scheme are interpreted as: - * - * ``` - * scheme:opaque[?query][#fragment] - * ``` - * - * The Host field contains the host and port subcomponents of the URL. - * When the port is present, it is separated from the host with a colon. - * When the host is an IPv6 address, it must be enclosed in square brackets: - * "[fe80::1]:80". The [net.JoinHostPort] function combines a host and port - * into a string suitable for the Host field, adding square brackets to - * the host when necessary. - * - * Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/. - * A consequence is that it is impossible to tell which slashes in the Path were - * slashes in the raw URL and which were %2f. This distinction is rarely important, - * but when it is, the code should use the [URL.EscapedPath] method, which preserves - * the original encoding of Path. The Fragment field is also stored in decoded form, - * use [URL.EscapedFragment] to retrieve the original encoding. - * - * The [URL.String] method uses the [URL.EscapedPath] method to obtain the path. - */ - interface URL { - scheme: string - opaque: string // encoded opaque data - user?: Userinfo // username and password information - host: string // "host" or "host:port" (see Hostname and Port methods) - path: string // path (relative paths may omit leading slash) - fragment: string // fragment for references (without '#') + context(): context.Context + /** + * SetContext assigns the specified context to the current provider. + */ + setContext(ctx: context.Context): void + /** + * PKCE indicates whether the provider can use the PKCE flow. + */ + pkce(): boolean + /** + * SetPKCE toggles the state whether the provider can use the PKCE flow or not. + */ + setPKCE(enable: boolean): void + /** + * DisplayName usually returns provider name as it is officially written + * and it could be used directly in the UI. + */ + displayName(): string + /** + * SetDisplayName sets the provider's display name. + */ + setDisplayName(displayName: string): void + /** + * Scopes returns the provider access permissions that will be requested. + */ + scopes(): Array + /** + * SetScopes sets the provider access permissions that will be requested later. + */ + setScopes(scopes: Array): void + /** + * ClientId returns the provider client's app ID. + */ + clientId(): string + /** + * SetClientId sets the provider client's ID. + */ + setClientId(clientId: string): void + /** + * ClientSecret returns the provider client's app secret. + */ + clientSecret(): string + /** + * SetClientSecret sets the provider client's app secret. + */ + setClientSecret(secret: string): void + /** + * RedirectURL returns the end address to redirect the user + * going through the OAuth flow. + */ + redirectURL(): string + /** + * SetRedirectURL sets the provider's RedirectURL. + */ + setRedirectURL(url: string): void /** - * RawQuery contains the encoded query values, without the initial '?'. - * Use URL.Query to decode the query. + * AuthURL returns the provider's authorization service url. */ - rawQuery: string + authURL(): string /** - * RawPath is an optional field containing an encoded path hint. - * See the EscapedPath method for more details. - * - * In general, code should call EscapedPath instead of reading RawPath. + * SetAuthURL sets the provider's AuthURL. */ - rawPath: string + setAuthURL(url: string): void /** - * RawFragment is an optional field containing an encoded fragment hint. - * See the EscapedFragment method for more details. - * - * In general, code should call EscapedFragment instead of reading RawFragment. + * TokenURL returns the provider's token exchange service url. */ - rawFragment: string + tokenURL(): string /** - * ForceQuery indicates whether the original URL contained a query ('?') character. - * When set, the String method will include a trailing '?', even when RawQuery is empty. + * SetTokenURL sets the provider's TokenURL. */ - forceQuery: boolean + setTokenURL(url: string): void /** - * OmitHost indicates the URL has an empty host (authority). - * When set, the String method will not include the host when it is empty. + * UserInfoURL returns the provider's user info api url. */ - omitHost: boolean - } - interface URL { + userInfoURL(): string /** - * EscapedPath returns the escaped form of u.Path. - * In general there are multiple possible escaped forms of any path. - * EscapedPath returns u.RawPath when it is a valid escaping of u.Path. - * Otherwise EscapedPath ignores u.RawPath and computes an escaped - * form on its own. - * The [URL.String] and [URL.RequestURI] methods use EscapedPath to construct - * their results. - * In general, code should call EscapedPath instead of - * reading u.RawPath directly. + * SetUserInfoURL sets the provider's UserInfoURL. */ - escapedPath(): string - } - interface URL { + setUserInfoURL(url: string): void /** - * EscapedFragment returns the escaped form of u.Fragment. - * In general there are multiple possible escaped forms of any fragment. - * EscapedFragment returns u.RawFragment when it is a valid escaping of u.Fragment. - * Otherwise EscapedFragment ignores u.RawFragment and computes an escaped - * form on its own. - * The [URL.String] method uses EscapedFragment to construct its result. - * In general, code should call EscapedFragment instead of - * reading u.RawFragment directly. + * Extra returns a shallow copy of any custom config data + * that the provider may need. */ - escapedFragment(): string - } - interface URL { + extra(): _TygojaDict /** - * String reassembles the [URL] into a valid URL string. - * The general form of the result is one of: - * - * ``` - * scheme:opaque?query#fragment - * scheme://userinfo@host/path?query#fragment - * ``` - * - * If u.Opaque is non-empty, String uses the first form; - * otherwise it uses the second form. - * Any non-ASCII characters in host are escaped. - * To obtain the path, String uses u.EscapedPath(). - * - * In the second form, the following rules apply: - * ``` - * - if u.Scheme is empty, scheme: is omitted. - * - if u.User is nil, userinfo@ is omitted. - * - if u.Host is empty, host/ is omitted. - * - if u.Scheme and u.Host are empty and u.User is nil, - * the entire scheme://userinfo@host/ is omitted. - * - if u.Host is non-empty and u.Path begins with a /, - * the form host/path does not add its own /. - * - if u.RawQuery is empty, ?query is omitted. - * - if u.Fragment is empty, #fragment is omitted. - * ``` + * SetExtra updates the provider's custom config data. */ - string(): string - } - interface URL { + setExtra(data: _TygojaDict): void /** - * Redacted is like [URL.String] but replaces any password with "xxxxx". - * Only the password in u.User is redacted. + * Client returns an http client using the provided token. */ - redacted(): string - } - /** - * Values maps a string key to a list of values. - * It is typically used for query parameters and form values. - * Unlike in the http.Header map, the keys in a Values map - * are case-sensitive. - */ - interface Values extends _TygojaDict{} - interface Values { + client(token: oauth2.Token): (any) /** - * Get gets the first value associated with the given key. - * If there are no values associated with the key, Get returns - * the empty string. To access multiple values, use the map - * directly. + * BuildAuthURL returns a URL to the provider's consent page + * that asks for permissions for the required scopes explicitly. */ - get(key: string): string - } - interface Values { + buildAuthURL(state: string, ...opts: oauth2.AuthCodeOption[]): string /** - * Set sets the key to value. It replaces any existing - * values. + * FetchToken converts an authorization code to token. */ - set(key: string, value: string): void - } - interface Values { + fetchToken(code: string, ...opts: oauth2.AuthCodeOption[]): (oauth2.Token) /** - * Add adds the value to key. It appends to any existing - * values associated with key. + * FetchRawUserInfo requests and marshalizes into `result` the + * the OAuth user api response. */ - add(key: string, value: string): void + fetchRawUserInfo(token: oauth2.Token): string|Array + /** + * FetchAuthUser is similar to FetchRawUserInfo, but normalizes and + * marshalizes the user api response into a standardized AuthUser struct. + */ + fetchAuthUser(token: oauth2.Token): (AuthUser) } - interface Values { + /** + * AuthUser defines a standardized OAuth2 user data structure. + */ + interface AuthUser { + expiry: types.DateTime + rawUser: _TygojaDict + id: string + name: string + username: string + avatarURL: string + accessToken: string + refreshToken: string /** - * Del deletes the values associated with key. + * The VERIFIED OAuth2 account email. + * + * It must be empty if the provider is not able to verify the email ownership. */ - del(key: string): void + email: string + /** + * @todo + * deprecated: use AvatarURL instead + * AvatarUrl will be removed after dropping v0.22 support + */ + avatarUrl: string } - interface Values { + interface AuthUser { /** - * Has checks whether a given key is set. + * MarshalJSON implements the [json.Marshaler] interface. + * + * @todo remove after dropping v0.22 support */ - has(key: string): boolean + marshalJSON(): string|Array } - interface Values { +} + +/** + * Package cron implements a crontab-like service to execute and schedule + * repeative tasks/jobs. + * + * Example: + * + * ``` + * c := cron.New() + * c.MustAdd("dailyReport", "0 0 * * *", func() { ... }) + * c.Start() + * ``` + */ +namespace cron { + /** + * Cron is a crontab-like struct for tasks/jobs scheduling. + */ + interface Cron { + } + interface Cron { /** - * Clone creates a deep copy of the subject [Values]. + * SetInterval changes the current cron tick interval + * (it usually should be >= 1 minute). */ - clone(): Values + setInterval(d: time.Duration): void } - interface Values { + interface Cron { /** - * Encode encodes the values into “URL encoded” form - * ("bar=baz&foo=quux") sorted by key. + * SetTimezone changes the current cron tick timezone. */ - encode(): string + setTimezone(l: time.Location): void } - interface URL { + interface Cron { /** - * IsAbs reports whether the [URL] is absolute. - * Absolute means that it has a non-empty scheme. + * MustAdd is similar to Add() but panic on failure. */ - isAbs(): boolean + mustAdd(jobId: string, cronExpr: string, run: () => void): void } - interface URL { + interface Cron { /** - * Parse parses a [URL] in the context of the receiver. The provided URL - * may be relative or absolute. Parse returns nil, err on parse - * failure, otherwise its return value is the same as [URL.ResolveReference]. + * Add registers a single cron job. + * + * If there is already a job with the provided id, then the old job + * will be replaced with the new one. + * + * cronExpr is a regular cron expression, eg. "0 *\/3 * * *" (aka. at minute 0 past every 3rd hour). + * Check cron.NewSchedule() for the supported tokens. */ - parse(ref: string): (URL) + add(jobId: string, cronExpr: string, fn: () => void): void } - interface URL { + interface Cron { /** - * ResolveReference resolves a URI reference to an absolute URI from - * an absolute base URI u, per RFC 3986 Section 5.2. The URI reference - * may be relative or absolute. ResolveReference always returns a new - * [URL] instance, even if the returned URL is identical to either the - * base or reference. If ref is an absolute URL, then ResolveReference - * ignores base and returns a copy of ref. + * Remove removes a single cron job by its id. */ - resolveReference(ref: URL): (URL) + remove(jobId: string): void } - interface URL { + interface Cron { /** - * Query parses RawQuery and returns the corresponding values. - * It silently discards malformed value pairs. - * To check errors use [ParseQuery]. + * RemoveAll removes all registered cron jobs. */ - query(): Values + removeAll(): void } - interface URL { + interface Cron { /** - * RequestURI returns the encoded path?query or opaque?query - * string that would be used in an HTTP request for u. + * Total returns the current total number of registered cron jobs. */ - requestURI(): string + total(): number } - interface URL { + interface Cron { /** - * Hostname returns u.Host, stripping any valid port number if present. - * - * If the result is enclosed in square brackets, as literal IPv6 addresses are, - * the square brackets are removed from the result. + * Jobs returns a shallow copy of the currently registered cron jobs. */ - hostname(): string + jobs(): Array<(Job | undefined)> } - interface URL { + interface Cron { /** - * Port returns the port part of u.Host, without the leading colon. + * Stop stops the current cron ticker (if not already). * - * If u.Host doesn't contain a valid numeric port, Port returns an empty string. + * You can resume the ticker by calling Start(). */ - port(): string - } - interface URL { - marshalBinary(): string|Array - } - interface URL { - appendBinary(b: string|Array): string|Array - } - interface URL { - unmarshalBinary(text: string|Array): void + stop(): void } - interface URL { + interface Cron { /** - * JoinPath returns a new [URL] with the provided path elements joined to - * any existing path and the resulting path cleaned of any ./ or ../ elements. - * Any sequences of multiple / characters will be reduced to a single /. - * Path elements must already be in escaped form, as produced by [PathEscape]. + * Start starts the cron ticker. + * + * Calling Start() on already started cron will restart the ticker. */ - joinPath(...elem: string[]): (URL) + start(): void } - interface URL { + interface Cron { /** - * Clone creates a deep copy of the fields of the subject [URL]. + * HasStarted checks whether the current Cron ticker has been started. */ - clone(): (URL) + hasStarted(): boolean + } +} + +namespace sync { + // @ts-ignore + import isync = sync + /** + * A Locker represents an object that can be locked and unlocked. + */ + interface Locker { + [key:string]: any; + lock(): void + unlock(): void + } + // @ts-ignore + import rtatomic = atomic +} + +namespace io { + /** + * WriteCloser is the interface that groups the basic Write and Close methods. + */ + interface WriteCloser { + [key:string]: any; } } @@ -23086,6 +22720,112 @@ namespace bufio { } } +namespace syscall { + // @ts-ignore + import errpkg = errors + /** + * SysProcIDMap holds Container ID to Host ID mappings used for User Namespaces in Linux. + * See user_namespaces(7). + * + * Note that User Namespaces are not available on a number of popular Linux + * versions (due to security issues), or are available but subject to AppArmor + * restrictions like in Ubuntu 24.04. + */ + interface SysProcIDMap { + containerID: number // Container ID. + hostID: number // Host ID. + size: number // Size. + } + // @ts-ignore + import errorspkg = errors + /** + * Credential holds user and group identities to be assumed + * by a child process started by [StartProcess]. + */ + interface Credential { + uid: number // User ID. + gid: number // Group ID. + groups: Array // Supplementary group IDs. + noSetGroups: boolean // If true, don't set supplementary groups + } + /** + * A Signal is a number describing a process signal. + * It implements the [os.Signal] interface. + */ + interface Signal extends Number{} + interface Signal { + signal(): void + } + interface Signal { + string(): string + } +} + +namespace time { + /** + * A Month specifies a month of the year (January = 1, ...). + */ + interface Month extends Number{} + interface Month { + /** + * String returns the English name of the month ("January", "February", ...). + */ + string(): string + } + /** + * A Weekday specifies a day of the week (Sunday = 0, ...). + */ + interface Weekday extends Number{} + interface Weekday { + /** + * String returns the English name of the day ("Sunday", "Monday", ...). + */ + string(): string + } + /** + * A Location maps time instants to the zone in use at that time. + * Typically, the Location represents the collection of time offsets + * in use in a geographical area. For many Locations the time offset varies + * depending on whether daylight savings time is in use at the time instant. + * + * Location is used to provide a time zone in a printed Time value and for + * calculations involving intervals that may cross daylight savings time + * boundaries. + */ + interface Location { + } + interface Location { + /** + * String returns a descriptive name for the time zone information, + * corresponding to the name argument to [LoadLocation] or [FixedZone]. + */ + string(): string + } +} + +namespace fs { +} + +namespace context { +} + +namespace net { + /** + * Addr represents a network end point address. + * + * The two methods [Addr.Network] and [Addr.String] conventionally return strings + * that can be passed as the arguments to [Dial], but the exact form + * and meaning of the strings is up to the implementation. + */ + interface Addr { + [key:string]: any; + network(): string // name of the network (for example, "tcp", "udp") + string(): string // string form of address (for example, "192.0.2.1:25", "[2001:db8::1]:80") + } + // @ts-ignore + import _cgopackage = cgo +} + /** * Package textproto implements generic support for text-based request/response * protocols in the style of HTTP, NNTP, and SMTP. @@ -23228,732 +22968,915 @@ namespace multipart { } } -namespace http { +/** + * Package url parses URLs and implements query escaping. + * + * See RFC 3986. This package generally follows RFC 3986, except where + * it deviates for compatibility reasons. + * RFC 6874 followed for IPv6 zone literals. + */ +namespace url { /** - * A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an - * HTTP response or the Cookie header of an HTTP request. + * A URL represents a parsed URL (technically, a URI reference). * - * See https://tools.ietf.org/html/rfc6265 for details. + * The general form represented is: + * + * ``` + * [scheme:][//[userinfo@]host][/]path[?query][#fragment] + * ``` + * + * URLs that do not start with a slash after the scheme are interpreted as: + * + * ``` + * scheme:opaque[?query][#fragment] + * ``` + * + * The Host field contains the host and port subcomponents of the URL. + * When the port is present, it is separated from the host with a colon. + * When the host is an IPv6 address, it must be enclosed in square brackets: + * "[fe80::1]:80". The [net.JoinHostPort] function combines a host and port + * into a string suitable for the Host field, adding square brackets to + * the host when necessary. + * + * Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/. + * A consequence is that it is impossible to tell which slashes in the Path were + * slashes in the raw URL and which were %2f. This distinction is rarely important, + * but when it is, the code should use the [URL.EscapedPath] method, which preserves + * the original encoding of Path. The Fragment field is also stored in decoded form, + * use [URL.EscapedFragment] to retrieve the original encoding. + * + * The [URL.String] method uses the [URL.EscapedPath] method to obtain the path. */ - interface Cookie { - name: string - value: string - quoted: boolean // indicates whether the Value was originally quoted - path: string // optional - domain: string // optional - expires: time.Time // optional - rawExpires: string // for reading cookies only - /** - * MaxAge=0 means no 'Max-Age' attribute specified. - * MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0' - * MaxAge>0 means Max-Age attribute present and given in seconds - */ - maxAge: number - secure: boolean - httpOnly: boolean - sameSite: SameSite - partitioned: boolean - raw: string - unparsed: Array // Raw text of unparsed attribute-value pairs - } - interface Cookie { - /** - * String returns the serialization of the cookie for use in a [Cookie] - * header (if only Name and Value are set) or a Set-Cookie response - * header (if other fields are set). - * If c is nil or c.Name is invalid, the empty string is returned. - */ - string(): string - } - interface Cookie { + interface URL { + scheme: string + opaque: string // encoded opaque data + user?: Userinfo // username and password information + host: string // "host" or "host:port" (see Hostname and Port methods) + path: string // path (relative paths may omit leading slash) + fragment: string // fragment for references (without '#') /** - * Valid reports whether the cookie is valid. + * RawQuery contains the encoded query values, without the initial '?'. + * Use URL.Query to decode the query. */ - valid(): void - } - /** - * A Header represents the key-value pairs in an HTTP header. - * - * The keys should be in canonical form, as returned by - * [CanonicalHeaderKey]. - */ - interface Header extends _TygojaDict{} - interface Header { + rawQuery: string /** - * Add adds the key, value pair to the header. - * It appends to any existing values associated with key. - * The key is case insensitive; it is canonicalized by - * [CanonicalHeaderKey]. + * RawPath is an optional field containing an encoded path hint. + * See the EscapedPath method for more details. + * + * In general, code should call EscapedPath instead of reading RawPath. */ - add(key: string, value: string): void - } - interface Header { + rawPath: string /** - * Set sets the header entries associated with key to the - * single element value. It replaces any existing values - * associated with key. The key is case insensitive; it is - * canonicalized by [textproto.CanonicalMIMEHeaderKey]. - * To use non-canonical keys, assign to the map directly. + * RawFragment is an optional field containing an encoded fragment hint. + * See the EscapedFragment method for more details. + * + * In general, code should call EscapedFragment instead of reading RawFragment. */ - set(key: string, value: string): void - } - interface Header { + rawFragment: string /** - * Get gets the first value associated with the given key. If - * there are no values associated with the key, Get returns "". - * It is case insensitive; [textproto.CanonicalMIMEHeaderKey] is - * used to canonicalize the provided key. Get assumes that all - * keys are stored in canonical form. To use non-canonical keys, - * access the map directly. + * ForceQuery indicates whether the original URL contained a query ('?') character. + * When set, the String method will include a trailing '?', even when RawQuery is empty. */ - get(key: string): string - } - interface Header { + forceQuery: boolean /** - * Values returns all values associated with the given key. - * It is case insensitive; [textproto.CanonicalMIMEHeaderKey] is - * used to canonicalize the provided key. To use non-canonical - * keys, access the map directly. - * The returned slice is not a copy. + * OmitHost indicates the URL has an empty host (authority). + * When set, the String method will not include the host when it is empty. */ - values(key: string): Array + omitHost: boolean } - interface Header { + interface URL { /** - * Del deletes the values associated with key. - * The key is case insensitive; it is canonicalized by - * [CanonicalHeaderKey]. + * EscapedPath returns the escaped form of u.Path. + * In general there are multiple possible escaped forms of any path. + * EscapedPath returns u.RawPath when it is a valid escaping of u.Path. + * Otherwise EscapedPath ignores u.RawPath and computes an escaped + * form on its own. + * The [URL.String] and [URL.RequestURI] methods use EscapedPath to construct + * their results. + * In general, code should call EscapedPath instead of + * reading u.RawPath directly. */ - del(key: string): void + escapedPath(): string } - interface Header { + interface URL { /** - * Write writes a header in wire format. + * EscapedFragment returns the escaped form of u.Fragment. + * In general there are multiple possible escaped forms of any fragment. + * EscapedFragment returns u.RawFragment when it is a valid escaping of u.Fragment. + * Otherwise EscapedFragment ignores u.RawFragment and computes an escaped + * form on its own. + * The [URL.String] method uses EscapedFragment to construct its result. + * In general, code should call EscapedFragment instead of + * reading u.RawFragment directly. */ - write(w: io.Writer): void + escapedFragment(): string } - interface Header { + interface URL { /** - * Clone returns a copy of h or nil if h is nil. + * String reassembles the [URL] into a valid URL string. + * The general form of the result is one of: + * + * ``` + * scheme:opaque?query#fragment + * scheme://userinfo@host/path?query#fragment + * ``` + * + * If u.Opaque is non-empty, String uses the first form; + * otherwise it uses the second form. + * Any non-ASCII characters in host are escaped. + * To obtain the path, String uses u.EscapedPath(). + * + * In the second form, the following rules apply: + * ``` + * - if u.Scheme is empty, scheme: is omitted. + * - if u.User is nil, userinfo@ is omitted. + * - if u.Host is empty, host/ is omitted. + * - if u.Scheme and u.Host are empty and u.User is nil, + * the entire scheme://userinfo@host/ is omitted. + * - if u.Host is non-empty and u.Path begins with a /, + * the form host/path does not add its own /. + * - if u.RawQuery is empty, ?query is omitted. + * - if u.Fragment is empty, #fragment is omitted. + * ``` */ - clone(): Header + string(): string } - interface Header { + interface URL { /** - * WriteSubset writes a header in wire format. - * If exclude is not nil, keys where exclude[key] == true are not written. - * Keys are not canonicalized before checking the exclude map. + * Redacted is like [URL.String] but replaces any password with "xxxxx". + * Only the password in u.User is redacted. */ - writeSubset(w: io.Writer, exclude: _TygojaDict): void + redacted(): string } /** - * Protocols is a set of HTTP protocols. - * The zero value is an empty set of protocols. - * - * The supported protocols are: - * - * ``` - * - HTTP1 is the HTTP/1.0 and HTTP/1.1 protocols. - * HTTP1 is supported on both unsecured TCP and secured TLS connections. - * - * - HTTP2 is the HTTP/2 protocol over a TLS connection. - * - * - UnencryptedHTTP2 is the HTTP/2 protocol over an unsecured TCP connection. - * ``` + * Values maps a string key to a list of values. + * It is typically used for query parameters and form values. + * Unlike in the http.Header map, the keys in a Values map + * are case-sensitive. */ - interface Protocols { - } - interface Protocols { + interface Values extends _TygojaDict{} + interface Values { /** - * HTTP1 reports whether p includes HTTP/1. + * Get gets the first value associated with the given key. + * If there are no values associated with the key, Get returns + * the empty string. To access multiple values, use the map + * directly. */ - http1(): boolean + get(key: string): string } - interface Protocols { + interface Values { /** - * SetHTTP1 adds or removes HTTP/1 from p. + * Set sets the key to value. It replaces any existing + * values. */ - setHTTP1(ok: boolean): void + set(key: string, value: string): void } - interface Protocols { + interface Values { /** - * HTTP2 reports whether p includes HTTP/2. + * Add adds the value to key. It appends to any existing + * values associated with key. */ - http2(): boolean + add(key: string, value: string): void } - interface Protocols { + interface Values { /** - * SetHTTP2 adds or removes HTTP/2 from p. + * Del deletes the values associated with key. */ - setHTTP2(ok: boolean): void + del(key: string): void } - interface Protocols { + interface Values { /** - * UnencryptedHTTP2 reports whether p includes unencrypted HTTP/2. + * Has checks whether a given key is set. */ - unencryptedHTTP2(): boolean + has(key: string): boolean } - interface Protocols { + interface Values { /** - * SetUnencryptedHTTP2 adds or removes unencrypted HTTP/2 from p. + * Clone creates a deep copy of the subject [Values]. */ - setUnencryptedHTTP2(ok: boolean): void - } - interface Protocols { - string(): string + clone(): Values } - /** - * HTTP2Config defines HTTP/2 configuration parameters common to - * both [Transport] and [Server]. - */ - interface HTTP2Config { + interface Values { /** - * MaxConcurrentStreams optionally specifies the number of - * concurrent streams that a client may have open at a time. - * If zero, MaxConcurrentStreams defaults to at least 100. - * - * This parameter only applies to Servers. + * Encode encodes the values into “URL encoded” form + * ("bar=baz&foo=quux") sorted by key. */ - maxConcurrentStreams: number + encode(): string + } + interface URL { /** - * StrictMaxConcurrentRequests controls whether an HTTP/2 server's - * concurrency limit should be respected across all connections - * to that server. - * If true, new requests sent when a connection's concurrency limit - * has been exceeded will block until an existing request completes. - * If false, an additional connection will be opened if all - * existing connections are at their limit. - * - * This parameter only applies to Transports. + * IsAbs reports whether the [URL] is absolute. + * Absolute means that it has a non-empty scheme. */ - strictMaxConcurrentRequests: boolean + isAbs(): boolean + } + interface URL { /** - * MaxDecoderHeaderTableSize optionally specifies an upper limit for the - * size of the header compression table used for decoding headers sent - * by the peer. - * A valid value is less than 4MiB. - * If zero or invalid, a default value is used. + * Parse parses a [URL] in the context of the receiver. The provided URL + * may be relative or absolute. Parse returns nil, err on parse + * failure, otherwise its return value is the same as [URL.ResolveReference]. */ - maxDecoderHeaderTableSize: number + parse(ref: string): (URL) + } + interface URL { /** - * MaxEncoderHeaderTableSize optionally specifies an upper limit for the - * header compression table used for sending headers to the peer. - * A valid value is less than 4MiB. - * If zero or invalid, a default value is used. + * ResolveReference resolves a URI reference to an absolute URI from + * an absolute base URI u, per RFC 3986 Section 5.2. The URI reference + * may be relative or absolute. ResolveReference always returns a new + * [URL] instance, even if the returned URL is identical to either the + * base or reference. If ref is an absolute URL, then ResolveReference + * ignores base and returns a copy of ref. */ - maxEncoderHeaderTableSize: number + resolveReference(ref: URL): (URL) + } + interface URL { /** - * MaxReadFrameSize optionally specifies the largest frame - * this endpoint is willing to read. - * A valid value is between 16KiB and 16MiB, inclusive. - * If zero or invalid, a default value is used. + * Query parses RawQuery and returns the corresponding values. + * It silently discards malformed value pairs. + * To check errors use [ParseQuery]. */ - maxReadFrameSize: number + query(): Values + } + interface URL { /** - * MaxReceiveBufferPerConnection is the maximum size of the - * flow control window for data received on a connection. - * A valid value is at least 64KiB and less than 4MiB. - * If invalid, a default value is used. + * RequestURI returns the encoded path?query or opaque?query + * string that would be used in an HTTP request for u. + */ + requestURI(): string + } + interface URL { + /** + * Hostname returns u.Host, stripping any valid port number if present. + * + * If the result is enclosed in square brackets, as literal IPv6 addresses are, + * the square brackets are removed from the result. */ - maxReceiveBufferPerConnection: number + hostname(): string + } + interface URL { /** - * MaxReceiveBufferPerStream is the maximum size of - * the flow control window for data received on a stream (request). - * A valid value is less than 4MiB. - * If zero or invalid, a default value is used. + * Port returns the port part of u.Host, without the leading colon. + * + * If u.Host doesn't contain a valid numeric port, Port returns an empty string. */ - maxReceiveBufferPerStream: number + port(): string + } + interface URL { + marshalBinary(): string|Array + } + interface URL { + appendBinary(b: string|Array): string|Array + } + interface URL { + unmarshalBinary(text: string|Array): void + } + interface URL { /** - * SendPingTimeout is the timeout after which a health check using a ping - * frame will be carried out if no frame is received on a connection. - * If zero, no health check is performed. + * JoinPath returns a new [URL] with the provided path elements joined to + * any existing path and the resulting path cleaned of any ./ or ../ elements. + * Any sequences of multiple / characters will be reduced to a single /. + * Path elements must already be in escaped form, as produced by [PathEscape]. */ - sendPingTimeout: time.Duration + joinPath(...elem: string[]): (URL) + } + interface URL { /** - * PingTimeout is the timeout after which a connection will be closed - * if a response to a ping is not received. - * If zero, a default of 15 seconds is used. + * Clone creates a deep copy of the fields of the subject [URL]. */ - pingTimeout: time.Duration + clone(): (URL) + } +} + +namespace sql { + /** + * IsolationLevel is the transaction isolation level used in [TxOptions]. + */ + interface IsolationLevel extends Number{} + interface IsolationLevel { /** - * WriteByteTimeout is the timeout after which a connection will be - * closed if no data can be written to it. The timeout begins when data is - * available to write, and is extended whenever any bytes are written. + * String returns the name of the transaction isolation level. */ - writeByteTimeout: time.Duration + string(): string + } + /** + * DBStats contains database statistics. + */ + interface DBStats { + maxOpenConnections: number // Maximum number of open connections to the database. /** - * PermitProhibitedCipherSuites, if true, permits the use of - * cipher suites prohibited by the HTTP/2 spec. + * Pool Status */ - permitProhibitedCipherSuites: boolean + openConnections: number // The number of established connections both in use and idle. + inUse: number // The number of connections currently in use. + idle: number // The number of idle connections. /** - * CountError, if non-nil, is called on HTTP/2 errors. - * It is intended to increment a metric for monitoring. - * The errType contains only lowercase letters, digits, and underscores - * (a-z, 0-9, _). + * Counters */ - countError: (errType: string) => void + waitCount: number // The total number of connections waited for. + waitDuration: time.Duration // The total time blocked waiting for a new connection. + maxIdleClosed: number // The total number of connections closed due to SetMaxIdleConns. + maxIdleTimeClosed: number // The total number of connections closed due to SetConnMaxIdleTime. + maxLifetimeClosed: number // The total number of connections closed due to SetConnMaxLifetime. } - // @ts-ignore - import urlpkg = url /** - * Response represents the response from an HTTP request. + * Conn represents a single database connection rather than a pool of database + * connections. Prefer running queries from [DB] unless there is a specific + * need for a continuous single database connection. * - * The [Client] and [Transport] return Responses from servers once - * the response headers have been received. The response body - * is streamed on demand as the Body field is read. + * A Conn must call [Conn.Close] to return the connection to the database pool + * and may do so concurrently with a running query. + * + * After a call to [Conn.Close], all operations on the + * connection fail with [ErrConnDone]. */ - interface Response { - status: string // e.g. "200 OK" - statusCode: number // e.g. 200 - proto: string // e.g. "HTTP/1.0" - protoMajor: number // e.g. 1 - protoMinor: number // e.g. 0 + interface Conn { + } + interface Conn { /** - * Header maps header keys to values. If the response had multiple - * headers with the same key, they may be concatenated, with comma - * delimiters. (RFC 7230, section 3.2.2 requires that multiple headers - * be semantically equivalent to a comma-delimited sequence.) When - * Header values are duplicated by other fields in this struct (e.g., - * ContentLength, TransferEncoding, Trailer), the field values are - * authoritative. - * - * Keys in the map are canonicalized (see CanonicalHeaderKey). + * PingContext verifies the connection to the database is still alive. */ - header: Header + pingContext(ctx: context.Context): void + } + interface Conn { /** - * Body represents the response body. - * - * The response body is streamed on demand as the Body field - * is read. If the network connection fails or the server - * terminates the response, Body.Read calls return an error. - * - * The http Client and Transport guarantee that Body is always - * non-nil, even on responses without a body or responses with - * a zero-length body. It is the caller's responsibility to - * close Body. The default HTTP client's Transport may not - * reuse HTTP/1.x "keep-alive" TCP connections if the Body is - * not read to completion and closed; however, manually reading - * the body to completion should not be needed in most cases, - * as closing the body will also cause the body to be read to - * completion asynchronously, up to a conservative limit. - * - * The Body is automatically dechunked if the server replied - * with a "chunked" Transfer-Encoding. - * - * As of Go 1.12, the Body will also implement io.Writer - * on a successful "101 Switching Protocols" response, - * as used by WebSockets and HTTP/2's "h2c" mode. + * ExecContext executes a query without returning any rows. + * The args are for any placeholder parameters in the query. */ - body: io.ReadCloser + execContext(ctx: context.Context, query: string, ...args: any[]): Result + } + interface Conn { /** - * ContentLength records the length of the associated content. The - * value -1 indicates that the length is unknown. Unless Request.Method - * is "HEAD", values >= 0 indicate that the given number of bytes may - * be read from Body. + * QueryContext executes a query that returns rows, typically a SELECT. + * The args are for any placeholder parameters in the query. */ - contentLength: number + queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows) + } + interface Conn { /** - * Contains transfer encodings from outer-most to inner-most. Value is - * nil, means that "identity" encoding is used. + * QueryRowContext executes a query that is expected to return at most one row. + * QueryRowContext always returns a non-nil value. Errors are deferred until + * the [*Row.Scan] method is called. + * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. + * Otherwise, the [*Row.Scan] scans the first selected row and discards + * the rest. */ - transferEncoding: Array + queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row) + } + interface Conn { /** - * Close records whether the header directed that the connection be - * closed after reading Body. The value is advice for clients: neither - * ReadResponse nor Response.Write ever closes a connection. + * PrepareContext creates a prepared statement for later queries or executions. + * Multiple queries or executions may be run concurrently from the + * returned statement. + * The caller must call the statement's [*Stmt.Close] method + * when the statement is no longer needed. + * + * The provided context is used for the preparation of the statement, not for the + * execution of the statement. */ - close: boolean + prepareContext(ctx: context.Context, query: string): (Stmt) + } + interface Conn { /** - * Uncompressed reports whether the response was sent compressed but - * was decompressed by the http package. When true, reading from - * Body yields the uncompressed content instead of the compressed - * content actually set from the server, ContentLength is set to -1, - * and the "Content-Length" and "Content-Encoding" fields are deleted - * from the responseHeader. To get the original response from - * the server, set Transport.DisableCompression to true. + * Raw executes f exposing the underlying driver connection for the + * duration of f. The driverConn must not be used outside of f. + * + * Once f returns and err is not [driver.ErrBadConn], the [Conn] will continue to be usable + * until [Conn.Close] is called. */ - uncompressed: boolean + raw(f: (driverConn: any) => void): void + } + interface Conn { /** - * Trailer maps trailer keys to values in the same - * format as Header. - * - * The Trailer initially contains only nil values, one for - * each key specified in the server's "Trailer" header - * value. Those values are not added to Header. + * BeginTx starts a transaction. * - * Trailer must not be accessed concurrently with Read calls - * on the Body. + * The provided context is used until the transaction is committed or rolled back. + * If the context is canceled, the sql package will roll back + * the transaction. [Tx.Commit] will return an error if the context provided to + * BeginTx is canceled. * - * After Body.Read has returned io.EOF, Trailer will contain - * any trailer values sent by the server. + * The provided [TxOptions] is optional and may be nil if defaults should be used. + * If a non-default isolation level is used that the driver doesn't support, + * an error will be returned. */ - trailer: Header + beginTx(ctx: context.Context, opts: TxOptions): (Tx) + } + interface Conn { /** - * Request is the request that was sent to obtain this Response. - * Request's Body is nil (having already been consumed). - * This is only populated for Client requests. + * Close returns the connection to the connection pool. + * All operations after a Close will return with [ErrConnDone]. + * Close is safe to call concurrently with other operations and will + * block until all other operations finish. It may be useful to first + * cancel any used context and then call close directly after. */ - request?: Request + close(): void + } + /** + * ColumnType contains the name and type of a column. + */ + interface ColumnType { + } + interface ColumnType { /** - * TLS contains information about the TLS connection on which the - * response was received. It is nil for unencrypted responses. - * The pointer is shared between responses and should not be - * modified. + * Name returns the name or alias of the column. + */ + name(): string + } + interface ColumnType { + /** + * Length returns the column type length for variable length column types such + * as text and binary field types. If the type length is unbounded the value will + * be [math.MaxInt64] (any database limits will still apply). + * If the column type is not variable length, such as an int, or if not supported + * by the driver ok is false. */ - tls?: any + length(): [number, boolean] } - interface Response { + interface ColumnType { /** - * Cookies parses and returns the cookies set in the Set-Cookie headers. + * DecimalSize returns the scale and precision of a decimal type. + * If not applicable or if not supported ok is false. */ - cookies(): Array<(Cookie | undefined)> + decimalSize(): [number, number, boolean] } - interface Response { + interface ColumnType { /** - * Location returns the URL of the response's "Location" header, - * if present. Relative redirects are resolved relative to - * [Response.Request]. [ErrNoLocation] is returned if no - * Location header is present. + * ScanType returns a Go type suitable for scanning into using [Rows.Scan]. + * If a driver does not support this property ScanType will return + * the type of an empty interface. */ - location(): (url.URL) + scanType(): any } - interface Response { + interface ColumnType { /** - * ProtoAtLeast reports whether the HTTP protocol used - * in the response is at least major.minor. + * Nullable reports whether the column may be null. + * If a driver does not support this property ok will be false. */ - protoAtLeast(major: number, minor: number): boolean + nullable(): [boolean, boolean] } - interface Response { + interface ColumnType { /** - * Write writes r to w in the HTTP/1.x server response format, - * including the status line, headers, body, and optional trailer. - * - * This method consults the following fields of the response r: - * - * ``` - * StatusCode - * ProtoMajor - * ProtoMinor - * Request.Method - * TransferEncoding - * Trailer - * Body - * ContentLength - * Header, values for non-canonical keys will have unpredictable behavior - * ``` - * - * The Response Body is closed after it is sent. + * DatabaseTypeName returns the database system name of the column type. If an empty + * string is returned, then the driver type name is not supported. + * Consult your driver documentation for a list of driver data types. [ColumnType.Length] specifiers + * are not included. + * Common type names include "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL", + * "INT", and "BIGINT". */ - write(w: io.Writer): void + databaseTypeName(): string } /** - * A ConnState represents the state of a client connection to a server. - * It's used by the optional [Server.ConnState] hook. + * Row is the result of calling [DB.QueryRow] to select a single row. */ - interface ConnState extends Number{} - interface ConnState { - string(): string + interface Row { + } + interface Row { + /** + * Scan copies the columns from the matched row into the values + * pointed at by dest. See the documentation on [Rows.Scan] for details. + * If more than one row matches the query, + * Scan uses the first row and discards the rest. If no row matches + * the query, Scan returns [ErrNoRows]. + */ + scan(...dest: any[]): void + } + interface Row { + /** + * Err provides a way for wrapping packages to check for + * query errors without calling [Row.Scan]. + * Err returns the error, if any, that was encountered while running the query. + * If this error is not nil, this error will also be returned from [Row.Scan]. + */ + err(): void } } -/** - * Package oauth2 provides support for making - * OAuth2 authorized and authenticated HTTP requests, - * as specified in RFC 6749. - * It can additionally grant authorization with Bearer JWT. - */ -namespace oauth2 { +namespace http { /** - * An AuthCodeOption is passed to Config.AuthCodeURL. + * A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an + * HTTP response or the Cookie header of an HTTP request. + * + * See https://tools.ietf.org/html/rfc6265 for details. */ - interface AuthCodeOption { - [key:string]: any; + interface Cookie { + name: string + value: string + quoted: boolean // indicates whether the Value was originally quoted + path: string // optional + domain: string // optional + expires: time.Time // optional + rawExpires: string // for reading cookies only + /** + * MaxAge=0 means no 'Max-Age' attribute specified. + * MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0' + * MaxAge>0 means Max-Age attribute present and given in seconds + */ + maxAge: number + secure: boolean + httpOnly: boolean + sameSite: SameSite + partitioned: boolean + raw: string + unparsed: Array // Raw text of unparsed attribute-value pairs + } + interface Cookie { + /** + * String returns the serialization of the cookie for use in a [Cookie] + * header (if only Name and Value are set) or a Set-Cookie response + * header (if other fields are set). + * If c is nil or c.Name is invalid, the empty string is returned. + */ + string(): string + } + interface Cookie { + /** + * Valid reports whether the cookie is valid. + */ + valid(): void } /** - * Token represents the credentials used to authorize - * the requests to access protected resources on the OAuth 2.0 - * provider's backend. + * A Header represents the key-value pairs in an HTTP header. * - * Most users of this package should not access fields of Token - * directly. They're exported mostly for use by related packages - * implementing derivative OAuth2 flows. + * The keys should be in canonical form, as returned by + * [CanonicalHeaderKey]. */ - interface Token { + interface Header extends _TygojaDict{} + interface Header { /** - * AccessToken is the token that authorizes and authenticates - * the requests. + * Add adds the key, value pair to the header. + * It appends to any existing values associated with key. + * The key is case insensitive; it is canonicalized by + * [CanonicalHeaderKey]. */ - accessToken: string + add(key: string, value: string): void + } + interface Header { /** - * TokenType is the type of token. - * The Type method returns either this or "Bearer", the default. + * Set sets the header entries associated with key to the + * single element value. It replaces any existing values + * associated with key. The key is case insensitive; it is + * canonicalized by [textproto.CanonicalMIMEHeaderKey]. + * To use non-canonical keys, assign to the map directly. */ - tokenType: string + set(key: string, value: string): void + } + interface Header { /** - * RefreshToken is a token that's used by the application - * (as opposed to the user) to refresh the access token - * if it expires. + * Get gets the first value associated with the given key. If + * there are no values associated with the key, Get returns "". + * It is case insensitive; [textproto.CanonicalMIMEHeaderKey] is + * used to canonicalize the provided key. Get assumes that all + * keys are stored in canonical form. To use non-canonical keys, + * access the map directly. */ - refreshToken: string + get(key: string): string + } + interface Header { /** - * Expiry is the optional expiration time of the access token. - * - * If zero, [TokenSource] implementations will reuse the same - * token forever and RefreshToken or equivalent - * mechanisms for that TokenSource will not be used. + * Values returns all values associated with the given key. + * It is case insensitive; [textproto.CanonicalMIMEHeaderKey] is + * used to canonicalize the provided key. To use non-canonical + * keys, access the map directly. + * The returned slice is not a copy. */ - expiry: time.Time + values(key: string): Array + } + interface Header { /** - * ExpiresIn is the OAuth2 wire format "expires_in" field, - * which specifies how many seconds later the token expires, - * relative to an unknown time base approximately around "now". - * It is the application's responsibility to populate - * `Expiry` from `ExpiresIn` when required. + * Del deletes the values associated with key. + * The key is case insensitive; it is canonicalized by + * [CanonicalHeaderKey]. */ - expiresIn: number + del(key: string): void } - interface Token { + interface Header { /** - * Type returns t.TokenType if non-empty, else "Bearer". + * Write writes a header in wire format. */ - type(): string + write(w: io.Writer): void } - interface Token { + interface Header { /** - * SetAuthHeader sets the Authorization header to r using the access - * token in t. - * - * This method is unnecessary when using [Transport] or an HTTP Client - * returned by this package. + * Clone returns a copy of h or nil if h is nil. + */ + clone(): Header + } + interface Header { + /** + * WriteSubset writes a header in wire format. + * If exclude is not nil, keys where exclude[key] == true are not written. + * Keys are not canonicalized before checking the exclude map. + */ + writeSubset(w: io.Writer, exclude: _TygojaDict): void + } + /** + * Protocols is a set of HTTP protocols. + * The zero value is an empty set of protocols. + * + * The supported protocols are: + * + * ``` + * - HTTP1 is the HTTP/1.0 and HTTP/1.1 protocols. + * HTTP1 is supported on both unsecured TCP and secured TLS connections. + * + * - HTTP2 is the HTTP/2 protocol over a TLS connection. + * + * - UnencryptedHTTP2 is the HTTP/2 protocol over an unsecured TCP connection. + * ``` + */ + interface Protocols { + } + interface Protocols { + /** + * HTTP1 reports whether p includes HTTP/1. + */ + http1(): boolean + } + interface Protocols { + /** + * SetHTTP1 adds or removes HTTP/1 from p. */ - setAuthHeader(r: http.Request): void + setHTTP1(ok: boolean): void } - interface Token { + interface Protocols { /** - * WithExtra returns a new [Token] that's a clone of t, but using the - * provided raw extra map. This is only intended for use by packages - * implementing derivative OAuth2 flows. + * HTTP2 reports whether p includes HTTP/2. */ - withExtra(extra: any): (Token) + http2(): boolean } - interface Token { + interface Protocols { /** - * Extra returns an extra field. - * Extra fields are key-value pairs returned by the server as - * part of the token retrieval response. + * SetHTTP2 adds or removes HTTP/2 from p. */ - extra(key: string): any + setHTTP2(ok: boolean): void } - interface Token { + interface Protocols { /** - * Valid reports whether t is non-nil, has an AccessToken, and is not expired. + * UnencryptedHTTP2 reports whether p includes unencrypted HTTP/2. */ - valid(): boolean + unencryptedHTTP2(): boolean } -} - -namespace sql { - /** - * IsolationLevel is the transaction isolation level used in [TxOptions]. - */ - interface IsolationLevel extends Number{} - interface IsolationLevel { + interface Protocols { /** - * String returns the name of the transaction isolation level. + * SetUnencryptedHTTP2 adds or removes unencrypted HTTP/2 from p. */ + setUnencryptedHTTP2(ok: boolean): void + } + interface Protocols { string(): string } /** - * DBStats contains database statistics. + * HTTP2Config defines HTTP/2 configuration parameters common to + * both [Transport] and [Server]. */ - interface DBStats { - maxOpenConnections: number // Maximum number of open connections to the database. + interface HTTP2Config { /** - * Pool Status + * MaxConcurrentStreams optionally specifies the number of + * concurrent streams that a client may have open at a time. + * If zero, MaxConcurrentStreams defaults to at least 100. + * + * This parameter only applies to Servers. */ - openConnections: number // The number of established connections both in use and idle. - inUse: number // The number of connections currently in use. - idle: number // The number of idle connections. + maxConcurrentStreams: number /** - * Counters + * StrictMaxConcurrentRequests controls whether an HTTP/2 server's + * concurrency limit should be respected across all connections + * to that server. + * If true, new requests sent when a connection's concurrency limit + * has been exceeded will block until an existing request completes. + * If false, an additional connection will be opened if all + * existing connections are at their limit. + * + * This parameter only applies to Transports. */ - waitCount: number // The total number of connections waited for. - waitDuration: time.Duration // The total time blocked waiting for a new connection. - maxIdleClosed: number // The total number of connections closed due to SetMaxIdleConns. - maxIdleTimeClosed: number // The total number of connections closed due to SetConnMaxIdleTime. - maxLifetimeClosed: number // The total number of connections closed due to SetConnMaxLifetime. - } - /** - * Conn represents a single database connection rather than a pool of database - * connections. Prefer running queries from [DB] unless there is a specific - * need for a continuous single database connection. - * - * A Conn must call [Conn.Close] to return the connection to the database pool - * and may do so concurrently with a running query. - * - * After a call to [Conn.Close], all operations on the - * connection fail with [ErrConnDone]. - */ - interface Conn { - } - interface Conn { + strictMaxConcurrentRequests: boolean /** - * PingContext verifies the connection to the database is still alive. + * MaxDecoderHeaderTableSize optionally specifies an upper limit for the + * size of the header compression table used for decoding headers sent + * by the peer. + * A valid value is less than 4MiB. + * If zero or invalid, a default value is used. */ - pingContext(ctx: context.Context): void - } - interface Conn { + maxDecoderHeaderTableSize: number /** - * ExecContext executes a query without returning any rows. - * The args are for any placeholder parameters in the query. + * MaxEncoderHeaderTableSize optionally specifies an upper limit for the + * header compression table used for sending headers to the peer. + * A valid value is less than 4MiB. + * If zero or invalid, a default value is used. */ - execContext(ctx: context.Context, query: string, ...args: any[]): Result - } - interface Conn { + maxEncoderHeaderTableSize: number /** - * QueryContext executes a query that returns rows, typically a SELECT. - * The args are for any placeholder parameters in the query. + * MaxReadFrameSize optionally specifies the largest frame + * this endpoint is willing to read. + * A valid value is between 16KiB and 16MiB, inclusive. + * If zero or invalid, a default value is used. */ - queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows) - } - interface Conn { + maxReadFrameSize: number /** - * QueryRowContext executes a query that is expected to return at most one row. - * QueryRowContext always returns a non-nil value. Errors are deferred until - * the [*Row.Scan] method is called. - * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. - * Otherwise, the [*Row.Scan] scans the first selected row and discards - * the rest. + * MaxReceiveBufferPerConnection is the maximum size of the + * flow control window for data received on a connection. + * A valid value is at least 64KiB and less than 4MiB. + * If invalid, a default value is used. */ - queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row) - } - interface Conn { + maxReceiveBufferPerConnection: number /** - * PrepareContext creates a prepared statement for later queries or executions. - * Multiple queries or executions may be run concurrently from the - * returned statement. - * The caller must call the statement's [*Stmt.Close] method - * when the statement is no longer needed. - * - * The provided context is used for the preparation of the statement, not for the - * execution of the statement. + * MaxReceiveBufferPerStream is the maximum size of + * the flow control window for data received on a stream (request). + * A valid value is less than 4MiB. + * If zero or invalid, a default value is used. */ - prepareContext(ctx: context.Context, query: string): (Stmt) + maxReceiveBufferPerStream: number + /** + * SendPingTimeout is the timeout after which a health check using a ping + * frame will be carried out if no frame is received on a connection. + * If zero, no health check is performed. + */ + sendPingTimeout: time.Duration + /** + * PingTimeout is the timeout after which a connection will be closed + * if a response to a ping is not received. + * If zero, a default of 15 seconds is used. + */ + pingTimeout: time.Duration + /** + * WriteByteTimeout is the timeout after which a connection will be + * closed if no data can be written to it. The timeout begins when data is + * available to write, and is extended whenever any bytes are written. + */ + writeByteTimeout: time.Duration + /** + * PermitProhibitedCipherSuites, if true, permits the use of + * cipher suites prohibited by the HTTP/2 spec. + */ + permitProhibitedCipherSuites: boolean + /** + * CountError, if non-nil, is called on HTTP/2 errors. + * It is intended to increment a metric for monitoring. + * The errType contains only lowercase letters, digits, and underscores + * (a-z, 0-9, _). + */ + countError: (errType: string) => void } - interface Conn { + // @ts-ignore + import urlpkg = url + /** + * Response represents the response from an HTTP request. + * + * The [Client] and [Transport] return Responses from servers once + * the response headers have been received. The response body + * is streamed on demand as the Body field is read. + */ + interface Response { + status: string // e.g. "200 OK" + statusCode: number // e.g. 200 + proto: string // e.g. "HTTP/1.0" + protoMajor: number // e.g. 1 + protoMinor: number // e.g. 0 /** - * Raw executes f exposing the underlying driver connection for the - * duration of f. The driverConn must not be used outside of f. + * Header maps header keys to values. If the response had multiple + * headers with the same key, they may be concatenated, with comma + * delimiters. (RFC 7230, section 3.2.2 requires that multiple headers + * be semantically equivalent to a comma-delimited sequence.) When + * Header values are duplicated by other fields in this struct (e.g., + * ContentLength, TransferEncoding, Trailer), the field values are + * authoritative. * - * Once f returns and err is not [driver.ErrBadConn], the [Conn] will continue to be usable - * until [Conn.Close] is called. + * Keys in the map are canonicalized (see CanonicalHeaderKey). */ - raw(f: (driverConn: any) => void): void - } - interface Conn { + header: Header /** - * BeginTx starts a transaction. + * Body represents the response body. * - * The provided context is used until the transaction is committed or rolled back. - * If the context is canceled, the sql package will roll back - * the transaction. [Tx.Commit] will return an error if the context provided to - * BeginTx is canceled. + * The response body is streamed on demand as the Body field + * is read. If the network connection fails or the server + * terminates the response, Body.Read calls return an error. * - * The provided [TxOptions] is optional and may be nil if defaults should be used. - * If a non-default isolation level is used that the driver doesn't support, - * an error will be returned. + * The http Client and Transport guarantee that Body is always + * non-nil, even on responses without a body or responses with + * a zero-length body. It is the caller's responsibility to + * close Body. The default HTTP client's Transport may not + * reuse HTTP/1.x "keep-alive" TCP connections if the Body is + * not read to completion and closed; however, manually reading + * the body to completion should not be needed in most cases, + * as closing the body will also cause the body to be read to + * completion asynchronously, up to a conservative limit. + * + * The Body is automatically dechunked if the server replied + * with a "chunked" Transfer-Encoding. + * + * As of Go 1.12, the Body will also implement io.Writer + * on a successful "101 Switching Protocols" response, + * as used by WebSockets and HTTP/2's "h2c" mode. + */ + body: io.ReadCloser + /** + * ContentLength records the length of the associated content. The + * value -1 indicates that the length is unknown. Unless Request.Method + * is "HEAD", values >= 0 indicate that the given number of bytes may + * be read from Body. + */ + contentLength: number + /** + * Contains transfer encodings from outer-most to inner-most. Value is + * nil, means that "identity" encoding is used. + */ + transferEncoding: Array + /** + * Close records whether the header directed that the connection be + * closed after reading Body. The value is advice for clients: neither + * ReadResponse nor Response.Write ever closes a connection. + */ + close: boolean + /** + * Uncompressed reports whether the response was sent compressed but + * was decompressed by the http package. When true, reading from + * Body yields the uncompressed content instead of the compressed + * content actually set from the server, ContentLength is set to -1, + * and the "Content-Length" and "Content-Encoding" fields are deleted + * from the responseHeader. To get the original response from + * the server, set Transport.DisableCompression to true. */ - beginTx(ctx: context.Context, opts: TxOptions): (Tx) - } - interface Conn { + uncompressed: boolean /** - * Close returns the connection to the connection pool. - * All operations after a Close will return with [ErrConnDone]. - * Close is safe to call concurrently with other operations and will - * block until all other operations finish. It may be useful to first - * cancel any used context and then call close directly after. + * Trailer maps trailer keys to values in the same + * format as Header. + * + * The Trailer initially contains only nil values, one for + * each key specified in the server's "Trailer" header + * value. Those values are not added to Header. + * + * Trailer must not be accessed concurrently with Read calls + * on the Body. + * + * After Body.Read has returned io.EOF, Trailer will contain + * any trailer values sent by the server. */ - close(): void - } - /** - * ColumnType contains the name and type of a column. - */ - interface ColumnType { - } - interface ColumnType { + trailer: Header /** - * Name returns the name or alias of the column. + * Request is the request that was sent to obtain this Response. + * Request's Body is nil (having already been consumed). + * This is only populated for Client requests. */ - name(): string - } - interface ColumnType { + request?: Request /** - * Length returns the column type length for variable length column types such - * as text and binary field types. If the type length is unbounded the value will - * be [math.MaxInt64] (any database limits will still apply). - * If the column type is not variable length, such as an int, or if not supported - * by the driver ok is false. + * TLS contains information about the TLS connection on which the + * response was received. It is nil for unencrypted responses. + * The pointer is shared between responses and should not be + * modified. */ - length(): [number, boolean] + tls?: any } - interface ColumnType { + interface Response { /** - * DecimalSize returns the scale and precision of a decimal type. - * If not applicable or if not supported ok is false. + * Cookies parses and returns the cookies set in the Set-Cookie headers. */ - decimalSize(): [number, number, boolean] + cookies(): Array<(Cookie | undefined)> } - interface ColumnType { + interface Response { /** - * ScanType returns a Go type suitable for scanning into using [Rows.Scan]. - * If a driver does not support this property ScanType will return - * the type of an empty interface. + * Location returns the URL of the response's "Location" header, + * if present. Relative redirects are resolved relative to + * [Response.Request]. [ErrNoLocation] is returned if no + * Location header is present. */ - scanType(): any + location(): (url.URL) } - interface ColumnType { + interface Response { /** - * Nullable reports whether the column may be null. - * If a driver does not support this property ok will be false. + * ProtoAtLeast reports whether the HTTP protocol used + * in the response is at least major.minor. */ - nullable(): [boolean, boolean] + protoAtLeast(major: number, minor: number): boolean } - interface ColumnType { + interface Response { /** - * DatabaseTypeName returns the database system name of the column type. If an empty - * string is returned, then the driver type name is not supported. - * Consult your driver documentation for a list of driver data types. [ColumnType.Length] specifiers - * are not included. - * Common type names include "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL", - * "INT", and "BIGINT". + * Write writes r to w in the HTTP/1.x server response format, + * including the status line, headers, body, and optional trailer. + * + * This method consults the following fields of the response r: + * + * ``` + * StatusCode + * ProtoMajor + * ProtoMinor + * Request.Method + * TransferEncoding + * Trailer + * Body + * ContentLength + * Header, values for non-canonical keys will have unpredictable behavior + * ``` + * + * The Response Body is closed after it is sent. */ - databaseTypeName(): string + write(w: io.Writer): void } /** - * Row is the result of calling [DB.QueryRow] to select a single row. + * A ConnState represents the state of a client connection to a server. + * It's used by the optional [Server.ConnState] hook. */ - interface Row { - } - interface Row { - /** - * Scan copies the columns from the matched row into the values - * pointed at by dest. See the documentation on [Rows.Scan] for details. - * If more than one row matches the query, - * Scan uses the first row and discards the rest. If no row matches - * the query, Scan returns [ErrNoRows]. - */ - scan(...dest: any[]): void - } - interface Row { - /** - * Err provides a way for wrapping packages to check for - * query errors without calling [Row.Scan]. - * Err returns the error, if any, that was encountered while running the query. - * If this error is not nil, this error will also be returned from [Row.Scan]. - */ - err(): void + interface ConnState extends Number{} + interface ConnState { + string(): string } } @@ -23965,8 +23888,8 @@ namespace jwt { * NumericDate represents a JSON numeric date value, as referenced at * https://datatracker.ietf.org/doc/html/rfc7519#section-2. */ - type _sTZpnRR = time.Time - interface NumericDate extends _sTZpnRR { + type _saFtyBo = time.Time + interface NumericDate extends _saFtyBo { } interface NumericDate { /** @@ -23998,6 +23921,15 @@ namespace jwt { } } +namespace hook { + /** + * wrapped local Hook embedded struct to limit the public API surface. + */ + type _spOkxix = Hook + interface mainHook extends _spOkxix { + } +} + namespace types { } @@ -24024,15 +23956,6 @@ namespace search { interface NullFallbackPreference extends Number{} } -namespace hook { - /** - * wrapped local Hook embedded struct to limit the public API surface. - */ - type _siCQuEg = Hook - interface mainHook extends _siCQuEg { - } -} - namespace router { // @ts-ignore import validation = ozzo_validation @@ -24138,134 +24061,32 @@ namespace router { /** * PUT is a shorthand for [RouterGroup.AddRoute] with PUT as route method. */ - put(path: string, action: (e: T) => void): (Route) - } - interface RouterGroup { - /** - * HEAD is a shorthand for [RouterGroup.AddRoute] with HEAD as route method. - */ - head(path: string, action: (e: T) => void): (Route) - } - interface RouterGroup { - /** - * OPTIONS is a shorthand for [RouterGroup.AddRoute] with OPTIONS as route method. - */ - options(path: string, action: (e: T) => void): (Route) - } - interface RouterGroup { - /** - * HasRoute checks whether the specified route pattern (method + path) - * is registered in the current group or its children. - * - * This could be useful to conditionally register and checks for routes - * in order prevent panic on duplicated routes. - * - * Note that routes with anonymous and named wildcard placeholder are treated as equal, - * aka. "GET /abc/" is considered the same as "GET /abc/{something...}". - */ - hasRoute(method: string, path: string): boolean - } -} - -namespace cobra { - interface PositionalArgs {(cmd: Command, args: Array): void } - // @ts-ignore - import flag = pflag - /** - * FParseErrWhitelist configures Flag parse errors to be ignored - */ - interface FParseErrWhitelist extends _TygojaAny{} - /** - * Group Structure to manage groups for commands - */ - interface Group { - id: string - title: string - } - /** - * CompletionOptions are the options to control shell completion - */ - interface CompletionOptions { - /** - * DisableDefaultCmd prevents Cobra from creating a default 'completion' command - */ - disableDefaultCmd: boolean - /** - * DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag - * for shells that support completion descriptions - */ - disableNoDescFlag: boolean - /** - * DisableDescriptions turns off all completion descriptions for shells - * that support them - */ - disableDescriptions: boolean - /** - * HiddenDefaultCmd makes the default 'completion' command hidden - */ - hiddenDefaultCmd: boolean - /** - * DefaultShellCompDirective sets the ShellCompDirective that is returned - * if no special directive can be determined - */ - defaultShellCompDirective?: ShellCompDirective - } - interface CompletionOptions { - setDefaultShellCompDirective(directive: ShellCompDirective): void - } - /** - * Completion is a string that can be used for completions - * - * two formats are supported: - * ``` - * - the completion choice - * - the completion choice with a textual description (separated by a TAB). - * ``` - * - * [CompletionWithDesc] can be used to create a completion string with a textual description. - * - * Note: Go type alias is used to provide a more descriptive name in the documentation, but any string can be used. - */ - interface Completion extends String{} - /** - * CompletionFunc is a function that provides completion results. - */ - interface CompletionFunc {(cmd: Command, args: Array, toComplete: string): [Array, ShellCompDirective] } -} - -namespace subscriptions { -} - -namespace cron { - /** - * Job defines a single registered cron job. - */ - interface Job { - } - interface Job { - /** - * Id returns the cron job id. - */ - id(): string + put(path: string, action: (e: T) => void): (Route) } - interface Job { + interface RouterGroup { /** - * Expression returns the plain cron job schedule expression. + * HEAD is a shorthand for [RouterGroup.AddRoute] with HEAD as route method. */ - expression(): string + head(path: string, action: (e: T) => void): (Route) } - interface Job { + interface RouterGroup { /** - * Run runs the cron job function. + * OPTIONS is a shorthand for [RouterGroup.AddRoute] with OPTIONS as route method. */ - run(): void + options(path: string, action: (e: T) => void): (Route) } - interface Job { + interface RouterGroup { /** - * MarshalJSON implements [json.Marshaler] and export the current - * jobs data into valid JSON. + * HasRoute checks whether the specified route pattern (method + path) + * is registered in the current group or its children. + * + * This could be useful to conditionally register and checks for routes + * in order prevent panic on duplicated routes. + * + * Note that routes with anonymous and named wildcard placeholder are treated as equal, + * aka. "GET /abc/" is considered the same as "GET /abc/{something...}". */ - marshalJSON(): string|Array + hasRoute(method: string, path: string): boolean } } @@ -24447,6 +24268,204 @@ namespace slog { import loginternal = internal } +namespace cobra { + interface PositionalArgs {(cmd: Command, args: Array): void } + // @ts-ignore + import flag = pflag + /** + * FParseErrWhitelist configures Flag parse errors to be ignored + */ + interface FParseErrWhitelist extends _TygojaAny{} + /** + * Group Structure to manage groups for commands + */ + interface Group { + id: string + title: string + } + /** + * CompletionOptions are the options to control shell completion + */ + interface CompletionOptions { + /** + * DisableDefaultCmd prevents Cobra from creating a default 'completion' command + */ + disableDefaultCmd: boolean + /** + * DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag + * for shells that support completion descriptions + */ + disableNoDescFlag: boolean + /** + * DisableDescriptions turns off all completion descriptions for shells + * that support them + */ + disableDescriptions: boolean + /** + * HiddenDefaultCmd makes the default 'completion' command hidden + */ + hiddenDefaultCmd: boolean + /** + * DefaultShellCompDirective sets the ShellCompDirective that is returned + * if no special directive can be determined + */ + defaultShellCompDirective?: ShellCompDirective + } + interface CompletionOptions { + setDefaultShellCompDirective(directive: ShellCompDirective): void + } + /** + * Completion is a string that can be used for completions + * + * two formats are supported: + * ``` + * - the completion choice + * - the completion choice with a textual description (separated by a TAB). + * ``` + * + * [CompletionWithDesc] can be used to create a completion string with a textual description. + * + * Note: Go type alias is used to provide a more descriptive name in the documentation, but any string can be used. + */ + interface Completion extends String{} + /** + * CompletionFunc is a function that provides completion results. + */ + interface CompletionFunc {(cmd: Command, args: Array, toComplete: string): [Array, ShellCompDirective] } +} + +namespace cron { + /** + * Job defines a single registered cron job. + */ + interface Job { + } + interface Job { + /** + * Id returns the cron job id. + */ + id(): string + } + interface Job { + /** + * Expression returns the plain cron job schedule expression. + */ + expression(): string + } + interface Job { + /** + * Run runs the cron job function. + */ + run(): void + } + interface Job { + /** + * MarshalJSON implements [json.Marshaler] and export the current + * jobs data into valid JSON. + */ + marshalJSON(): string|Array + } +} + +namespace subscriptions { +} + +/** + * Package oauth2 provides support for making + * OAuth2 authorized and authenticated HTTP requests, + * as specified in RFC 6749. + * It can additionally grant authorization with Bearer JWT. + */ +namespace oauth2 { + /** + * An AuthCodeOption is passed to Config.AuthCodeURL. + */ + interface AuthCodeOption { + [key:string]: any; + } + /** + * Token represents the credentials used to authorize + * the requests to access protected resources on the OAuth 2.0 + * provider's backend. + * + * Most users of this package should not access fields of Token + * directly. They're exported mostly for use by related packages + * implementing derivative OAuth2 flows. + */ + interface Token { + /** + * AccessToken is the token that authorizes and authenticates + * the requests. + */ + accessToken: string + /** + * TokenType is the type of token. + * The Type method returns either this or "Bearer", the default. + */ + tokenType: string + /** + * RefreshToken is a token that's used by the application + * (as opposed to the user) to refresh the access token + * if it expires. + */ + refreshToken: string + /** + * Expiry is the optional expiration time of the access token. + * + * If zero, [TokenSource] implementations will reuse the same + * token forever and RefreshToken or equivalent + * mechanisms for that TokenSource will not be used. + */ + expiry: time.Time + /** + * ExpiresIn is the OAuth2 wire format "expires_in" field, + * which specifies how many seconds later the token expires, + * relative to an unknown time base approximately around "now". + * It is the application's responsibility to populate + * `Expiry` from `ExpiresIn` when required. + */ + expiresIn: number + } + interface Token { + /** + * Type returns t.TokenType if non-empty, else "Bearer". + */ + type(): string + } + interface Token { + /** + * SetAuthHeader sets the Authorization header to r using the access + * token in t. + * + * This method is unnecessary when using [Transport] or an HTTP Client + * returned by this package. + */ + setAuthHeader(r: http.Request): void + } + interface Token { + /** + * WithExtra returns a new [Token] that's a clone of t, but using the + * provided raw extra map. This is only intended for use by packages + * implementing derivative OAuth2 flows. + */ + withExtra(extra: any): (Token) + } + interface Token { + /** + * Extra returns an extra field. + * Extra fields are key-value pairs returned by the server as + * part of the token retrieval response. + */ + extra(key: string): any + } + interface Token { + /** + * Valid reports whether t is non-nil, has an AccessToken, and is not expired. + */ + valid(): boolean + } +} + namespace url { /** * The Userinfo type is an immutable encapsulation of username and @@ -24530,9 +24549,6 @@ namespace http { import urlpkg = url } -namespace oauth2 { -} - namespace search { /** * Join defines common fields required for a single SQL JOIN clause. @@ -24585,16 +24601,6 @@ namespace router { } } -namespace cobra { - // @ts-ignore - import flag = pflag - /** - * ShellCompDirective is a bit map representing the different behaviors the shell - * can be instructed to have once completions have been provided. - */ - interface ShellCompDirective extends Number{} -} - namespace slog { // @ts-ignore import loginternal = internal @@ -24775,9 +24781,17 @@ namespace slog { } } -namespace router { +namespace cobra { // @ts-ignore - import validation = ozzo_validation + import flag = pflag + /** + * ShellCompDirective is a bit map representing the different behaviors the shell + * can be instructed to have once completions have been provided. + */ + interface ShellCompDirective extends Number{} +} + +namespace oauth2 { } namespace slog { @@ -24818,3 +24832,8 @@ namespace slog { logValue(): Value } } + +namespace router { + // @ts-ignore + import validation = ozzo_validation +} diff --git a/pocketbase.go b/pocketbase.go index 509364c390..dbf8fcc807 100644 --- a/pocketbase.go +++ b/pocketbase.go @@ -210,7 +210,7 @@ func (pb *PocketBase) Execute() error { event := new(core.TerminateEvent) event.App = pb return pb.OnTerminate().Trigger(event, func(e *core.TerminateEvent) error { - return errors.Join(e.App.ResetBootstrapState(), execErr) + return errors.Join(e.App.ClearBootstrap(), execErr) }) } diff --git a/tests/app.go b/tests/app.go index c22b9d2e6b..31b4f11216 100644 --- a/tests/app.go +++ b/tests/app.go @@ -37,9 +37,9 @@ func (t *TestApp) Cleanup() { event.App = t t.OnTerminate().Trigger(event, func(e *core.TerminateEvent) error { + t.ClearBootstrap() t.TestMailer.Reset() t.ResetEventCalls() - t.ResetBootstrapState() return e.Next() }) @@ -144,6 +144,14 @@ func NewTestAppWithConfig(config core.BaseAppConfig) (*TestApp, error) { Priority: -99999, }) + t.OnClearBootstrap().Bind(&hook.Handler[*core.BootstrapEvent]{ + Func: func(e *core.BootstrapEvent) error { + t.registerEventCall("OnClearBootstrap") + return e.Next() + }, + Priority: -99999, + }) + t.OnServe().Bind(&hook.Handler[*core.ServeEvent]{ Func: func(e *core.ServeEvent) error { t.registerEventCall("OnServe") diff --git a/tools/logger/batch_handler.go b/tools/logger/batch_handler.go index 08b22a5104..cf72a4f533 100644 --- a/tools/logger/batch_handler.go +++ b/tools/logger/batch_handler.go @@ -11,6 +11,13 @@ import ( "github.com/pocketbase/pocketbase/tools/types" ) +// contextKey is an alias type to prevent collisions with other log context keys. +type contextKey int + +// BlockKey is a context key usually used to indicate that the +// batched logs write should block until writes are completed. +var BlockKey contextKey + var _ slog.Handler = (*BatchHandler)(nil) // BatchOptions are options for the BatchHandler. diff --git a/ui/.env b/ui/.env index 959e41dd60..6fbcd7bdad 100644 --- a/ui/.env +++ b/ui/.env @@ -12,4 +12,4 @@ PB_DOCS_URL = "https://pocketbase.io/docs" PB_JS_SDK_URL = "https://github.com/pocketbase/js-sdk" PB_DART_SDK_URL = "https://github.com/pocketbase/dart-sdk" PB_RELEASES = "https://github.com/pocketbase/pocketbase/releases" -PB_VERSION = "v0.40.3" +PB_VERSION = "v0.40.4-dev" diff --git a/ui/dist/assets/index-VdywtJWb.js b/ui/dist/assets/index-BdKjfEsN.js similarity index 99% rename from ui/dist/assets/index-VdywtJWb.js rename to ui/dist/assets/index-BdKjfEsN.js index b96b014e01..56fb8d0beb 100644 --- a/ui/dist/assets/index-VdywtJWb.js +++ b/ui/dist/assets/index-BdKjfEsN.js @@ -3,7 +3,7 @@ var e=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i= `),i=new Blob([r],{type:`text/csv;charset=utf-8;`}),a=window.URL.createObjectURL(i);f.download(a,n)},getApiExampleURL(){let e;if(app.pb.baseURL.startsWith(`http://`)||app.pb.baseURL.startsWith(`https://`))e=app.pb.baseURL;else{e=window.location.href;let n=e.indexOf(`/_/`);e=n>=0?e.substring(0,n):window.location.origin}return e.replace(`//localhost`,`//127.0.0.1`)},isActivePath(e,n=!0,r=``){r||=d.hash;let i;return i=RegExp(n?`^`+RegExp.escape(e)+`\\/?.*$`:`^`+RegExp.escape(e)+`\\/?(?:\\?.+)?$`),i.test(r)},getHashQueryParams(e=``){e||=d.hash;let n=``,r=e.indexOf(`?`);return r>-1&&(n=window.location.hash.substring(r+1)),Object.fromEntries(new URLSearchParams(n))},replaceHashQueryParams(e,n=null){e||={};let r=``,i=window.location.hash,a=i.indexOf(`?`);a>-1&&(r=i.substring(a+1),i=i.substring(0,a));let o=new URLSearchParams(r);for(let n in e){let r=e[n];f.isEmpty(r)?o.delete(n):o.set(n,r)}r=o.toString(),r!=``&&(i+=`?`+r);let s=window.location.href,c=s.indexOf(`#`);c>-1&&(s=s.substring(0,c));let l=s+i;return n===!1||(n===!0?window.history.pushState(null,``,l):window.history.replaceState(null,``,l)),l},getLocalHistory(e,n=null){try{let r=window.localStorage.getItem(e);if(r)return JSON.parse(r)||n}catch(n){console.log(`failed to load local history:`,e,n)}return n},saveLocalHistory(e,n){try{app.utils.isEmpty(n)?window.localStorage.removeItem(e):typeof n==`string`?window.localStorage.setItem(e,n):window.localStorage.setItem(e,JSON.stringify(n))}catch(n){console.log(`failed to save local history:`,e,n)}},generateThumb(e,n=100,r=100){return new Promise(i=>{let a=new FileReader;a.onload=function(a){let o=new Image;o.onload=function(){let a=document.createElement(`canvas`),s=a.getContext(`2d`),c=o.width,l=o.height;return a.width=n,a.height=r,s.drawImage(o,c>l?(c-l)/2:0,0,c>l?l:c,c>l?l:c,0,0,n,r),i(a.toDataURL(e.type))},o.src=a.target.result},a.readAsDataURL(e)})},normalizeSearchFilter(e,n=[]){if(e=(e||``).trim(),!e||!n.length)return e;for(let n of[`=`,`~`,`>`,`<`])if(e.includes(n))return e;return e=isNaN(e)&&e!=`true`&&e!=`false`?e.replace(/^[\"\'\`]|[\"\'\`]$/gm,``):e,n.map(n=>app.pb.filter(`${n}?~{:searchTerm}`,{searchTerm:e})).join(`||`)},logLevels:{[-4]:{label:`DEBUG`,class:``},0:{label:`INFO`,class:`success`},4:{label:`WARN`,class:`warning`},8:{label:`ERROR`,class:`danger`}},logDataFormatters:{execTime:function(e){return e?.data?.execTime===void 0?`N/A`:e.data.execTime+`ms`}},extendStore(e,n={},...r){let i=[];for(let a in n){let o=n[a];typeof e.__raw?.[a]==`function`||typeof o!=`function`||a.length>2&&a.startsWith(`on`)||r.includes(a)?e[a]=o:i.push(watch(o,n=>{e[a]=n}))}return i},cssTimeToMs(e){return e?(e=e.toLowerCase(),e.endsWith(`ms`)?Number(e.substring(0,e.length-2)):e.endsWith(`s`)?Number(e.substring(0,e.length-1)):Number(e)||0):0},isDarkEnoughForWhiteText(e){if(e=e?.startsWith(`#`)?e.substring(1):e,e?.length!=6)return!1;let n=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),i=parseInt(e.substring(4,6),16);return(n*299+r*587+i*114)/1e3<128},bulkSelectRange(e,n,r,i){let a=e.findIndex(e=>e.id==r.id);if(a==-1)return;let o=Object.keys(n),s=o[o.length-1],c=e.findIndex(e=>e.id==s);if(c==-1)return;let l=c,u=a;l>u&&([l,u]=[u,l]);for(let r=l;r<=u;r++)i?n[e[r].id]=e[r]:delete n[e[r].id]},imageExtensions:[`.jpg`,`.jpeg`,`.png`,`.svg`,`.gif`,`.jfif`,`.webp`,`.avif`],videoExtensions:[`.mp4`,`.avi`,`.mov`,`.3gp`,`.wmv`],audioExtensions:[`.aa`,`.aac`,`.m4v`,`.mp3`,`.ogg`,`.oga`,`.mogg`,`.amr`],documentExtensions:[`.pdf`,`.doc`,`.docx`,`.xls`,`.xlsx`,`.ppt`,`.pptx`,`.odp`,`.odt`,`.ods`,`.txt`],archiveExtensions:[`.zip`,`.gz`,`.tar`,`.rar`,`.7z`],hasExtension(e,n){return typeof n==`string`&&(n=n.toLowerCase(),!!e?.find(e=>n.endsWith(e)))},hasImageExtension(e){return app.utils.hasExtension(app.utils.imageExtensions,e)},hasVideoExtension(e){return app.utils.hasExtension(app.utils.videoExtensions,e)},hasAudioExtension(e){return app.utils.hasExtension(app.utils.audioExtensions,e)},hasDocumentExtension(e){return app.utils.hasExtension(app.utils.documentExtensions,e)},hasArchiveExtension(e){return app.utils.hasExtension(app.utils.archiveExtensions,e)},getFileType(e){return app.utils.hasImageExtension(e)?`image`:app.utils.hasVideoExtension(e)?`video`:app.utils.hasAudioExtension(e)?`audio`:app.utils.hasDocumentExtension(e)?`document`:app.utils.hasArchiveExtension(e)?`archive`:`file`},fileTypeIcons:{image:`ri-image-line`,video:`ri-movie-line`,audio:`ri-music-2-line`,document:`ri-file-line`,archive:`ri-file-zip-line`,file:`ri-file-line`},fallbackFieldIcon:`ri-puzzle-line`,fallbackCollectionIcon:`ri-puzzle-line`,fallbackProviderIcon:`ri-puzzle-line`,fallbackPresentableProps:[`title`,`name`,`slug`,`email`,`username`,`nickname`,`displayName`,`label`,`subject`,`topic`,`message`,`heading`,`headline`,`header`,`caption`,`key`,`identifier`,`id`],sortedCollections(e=[]){let n,r;function i(e,i){return n=e.name.startsWith(`_`),r=i.name.startsWith(`_`),n&&!r?1:!n&&r?-1:e.name>i.name?1:e.namee?.id&&!a.find(n=>n.id==e.id)),s=a.filter(e=>e?.id&&!i.find(n=>n.id==e.id)),c=a.filter(e=>{let n=app.utils.isObject(e)&&i.find(n=>n.id==e.id);if(!n)return!1;for(let r in n)if(JSON.stringify(e[r])!=JSON.stringify(n[r]))return!0;return!1});return!!(s.length||c.length||r&&o.length)},extractColumnsFromQuery(e){let n=`__PBGROUP__`;e=(e||``).replace(/\([\s\S]+?\)/gm,n).replace(/[\t\r\n]|(?:\s\s)+/g,` `);let r=e.match(/select\s+([\s\S]+)\s+from/)?.[1]?.split(`,`)||[],i=[];for(let e of r){let r=e.trim().split(` `).pop();r!=``&&r!=n&&i.push(r.replace(/[\'\"\`\[\]\s]/g,``))}return i},getAllCollectionIdentifiers(e,n=``){if(!e)return[];let r=[n+`id`],i=e.type==`auth`;if(e.type===`view`)for(let i of app.utils.extractColumnsFromQuery(e.viewQuery))app.utils.pushUnique(r,n+i);let a=e.fields||[];for(let e of a)if(!(e.type==`password`||i&&e.name==`tokenKey`)){if(app.fieldTypes[e.type]?.identifierExtractor){let i=app.utils.toArray(app.fieldTypes[e.type]?.identifierExtractor(e,n));for(let e of i)app.utils.pushUnique(r,e)}else app.utils.pushUnique(r,n+e.name)}return r},getDummyFieldsData(e,n=!1){let r=e?.fields||[],i={};for(let e of r)if(!e.hidden){if(app.fieldTypes[e.type]?.dummyData){let r=app.fieldTypes[e.type].dummyData(e,n);r!==void 0&&(i[e.name]=r)}else i[e.name]=`[[DATA]]`}return i},parseIndex(e){let n={unique:!1,optional:!1,schemaName:``,indexName:``,tableName:``,columns:[],where:``},r=/\s*create\s+(unique\s+)?\s*index\s*(if\s+not\s+exists\s+)?(\S*)\s+on\s+(\S*)\s*\(([\s\S]*?)\)(?:\s*where\s+([\s\S]*?))?\s*$/gi.exec((e||``).trim());if(r?.length!=7)return n;let i=/^[\"\'\`\[\{}]|[\"\'\`\]\}]$/g;n.unique=r[1]?.trim().toLowerCase()===`unique`,n.optional=!app.utils.isEmpty(r[2]?.trim());let a=(r[3]||``).split(`.`);a.length==2?(n.schemaName=a[0].replace(i,``),n.indexName=a[1].replace(i,``)):(n.schemaName=``,n.indexName=a[0].replace(i,``)),n.tableName=(r[4]||``).replace(i,``);let o=(r[5]||``).replace(/,(?=[^\(]*\))/gi,`{PB_TEMP}`).split(`,`);for(let e of o){e=e.trim().replaceAll(`{PB_TEMP}`,`,`);let r=/^([\s\S]+?)(?:\s+collate\s+([\w]+))?(?:\s+(asc|desc))?\s*$/gi.exec(e);if(r?.length!=4)continue;let a=r[1]?.trim()?.replace(i,``);a&&n.columns.push({name:a,collate:r[2]||``,sort:r[3]?.toUpperCase()||``})}return n.where=r[6]||``,n},buildIndex(e){let n=`CREATE `;e.unique&&(n+=`UNIQUE `),n+=`INDEX `,e.optional&&(n+=`IF NOT EXISTS `),e.schemaName&&(n+=`\`${e.schemaName}\`.`),n+=`\`${e.indexName||`idx_`+app.utils.randomString(10)}\` `,n+=`ON \`${e.tableName}\` (`;let r=e.columns.filter(e=>!!e?.name);return r.length>1&&(n+=` `),n+=r.map(e=>{let n=``;return e.name.includes(`(`)||e.name.includes(` `)?n+=e.name:n+="`"+e.name+"`",e.collate&&(n+=` COLLATE `+e.collate),e.sort&&(n+=` `+e.sort.toUpperCase()),n}).join(`, `),r.length>1&&(n+=` -`),n+=`)`,e.where&&(n+=` WHERE ${e.where}`),n},replaceIndexFields(e,n){let r=app.utils.parseIndex(e);return typeof n==`function`?Object.assign(r,n(r)||{}):Object.assign(r,n||{}),app.utils.buildIndex(r)},replaceIndexColumn(e,n,r){if(n===r)return e;let i=app.utils.parseIndex(e),a=!1;for(let e of i.columns)e.name===n&&(e.name=r,a=!0);return a?app.utils.buildIndex(i):e}};window.app=window.app||{},window.app.utils=f,window.app=window.app||{},window.app.utils=window.app.utils||{},window.app.utils.mimeTypes=[{ext:``,mimeType:`application/octet-stream`},{ext:`.xpm`,mimeType:`image/x-xpixmap`},{ext:`.7z`,mimeType:`application/x-7z-compressed`},{ext:`.zip`,mimeType:`application/zip`},{ext:`.xlsx`,mimeType:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`},{ext:`.docx`,mimeType:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`},{ext:`.pptx`,mimeType:`application/vnd.openxmlformats-officedocument.presentationml.presentation`},{ext:`.epub`,mimeType:`application/epub+zip`},{ext:`.apk`,mimeType:`application/vnd.android.package-archive`},{ext:`.jar`,mimeType:`application/jar`},{ext:`.odt`,mimeType:`application/vnd.oasis.opendocument.text`},{ext:`.ott`,mimeType:`application/vnd.oasis.opendocument.text-template`},{ext:`.ods`,mimeType:`application/vnd.oasis.opendocument.spreadsheet`},{ext:`.ots`,mimeType:`application/vnd.oasis.opendocument.spreadsheet-template`},{ext:`.odp`,mimeType:`application/vnd.oasis.opendocument.presentation`},{ext:`.otp`,mimeType:`application/vnd.oasis.opendocument.presentation-template`},{ext:`.odg`,mimeType:`application/vnd.oasis.opendocument.graphics`},{ext:`.otg`,mimeType:`application/vnd.oasis.opendocument.graphics-template`},{ext:`.odf`,mimeType:`application/vnd.oasis.opendocument.formula`},{ext:`.odc`,mimeType:`application/vnd.oasis.opendocument.chart`},{ext:`.sxc`,mimeType:`application/vnd.sun.xml.calc`},{ext:`.pdf`,mimeType:`application/pdf`},{ext:`.fdf`,mimeType:`application/vnd.fdf`},{ext:``,mimeType:`application/x-ole-storage`},{ext:`.msi`,mimeType:`application/x-ms-installer`},{ext:`.aaf`,mimeType:`application/octet-stream`},{ext:`.msg`,mimeType:`application/vnd.ms-outlook`},{ext:`.xls`,mimeType:`application/vnd.ms-excel`},{ext:`.pub`,mimeType:`application/vnd.ms-publisher`},{ext:`.ppt`,mimeType:`application/vnd.ms-powerpoint`},{ext:`.doc`,mimeType:`application/msword`},{ext:`.ps`,mimeType:`application/postscript`},{ext:`.psd`,mimeType:`image/vnd.adobe.photoshop`},{ext:`.p7s`,mimeType:`application/pkcs7-signature`},{ext:`.ogg`,mimeType:`application/ogg`},{ext:`.oga`,mimeType:`audio/ogg`},{ext:`.ogv`,mimeType:`video/ogg`},{ext:`.png`,mimeType:`image/png`},{ext:`.png`,mimeType:`image/vnd.mozilla.apng`},{ext:`.jpg`,mimeType:`image/jpeg`},{ext:`.jxl`,mimeType:`image/jxl`},{ext:`.jp2`,mimeType:`image/jp2`},{ext:`.jpf`,mimeType:`image/jpx`},{ext:`.jpm`,mimeType:`image/jpm`},{ext:`.jxs`,mimeType:`image/jxs`},{ext:`.gif`,mimeType:`image/gif`},{ext:`.webp`,mimeType:`image/webp`},{ext:`.exe`,mimeType:`application/vnd.microsoft.portable-executable`},{ext:``,mimeType:`application/x-elf`},{ext:``,mimeType:`application/x-object`},{ext:``,mimeType:`application/x-executable`},{ext:`.so`,mimeType:`application/x-sharedlib`},{ext:``,mimeType:`application/x-coredump`},{ext:`.a`,mimeType:`application/x-archive`},{ext:`.deb`,mimeType:`application/vnd.debian.binary-package`},{ext:`.tar`,mimeType:`application/x-tar`},{ext:`.xar`,mimeType:`application/x-xar`},{ext:`.bz2`,mimeType:`application/x-bzip2`},{ext:`.fits`,mimeType:`application/fits`},{ext:`.tiff`,mimeType:`image/tiff`},{ext:`.bmp`,mimeType:`image/bmp`},{ext:`.ico`,mimeType:`image/x-icon`},{ext:`.mp3`,mimeType:`audio/mpeg`},{ext:`.flac`,mimeType:`audio/flac`},{ext:`.midi`,mimeType:`audio/midi`},{ext:`.ape`,mimeType:`audio/ape`},{ext:`.mpc`,mimeType:`audio/musepack`},{ext:`.amr`,mimeType:`audio/amr`},{ext:`.wav`,mimeType:`audio/wav`},{ext:`.aiff`,mimeType:`audio/aiff`},{ext:`.au`,mimeType:`audio/basic`},{ext:`.mpeg`,mimeType:`video/mpeg`},{ext:`.mov`,mimeType:`video/quicktime`},{ext:`.mp4`,mimeType:`video/mp4`},{ext:`.avif`,mimeType:`image/avif`},{ext:`.3gp`,mimeType:`video/3gpp`},{ext:`.3g2`,mimeType:`video/3gpp2`},{ext:`.mp4`,mimeType:`audio/mp4`},{ext:`.mqv`,mimeType:`video/quicktime`},{ext:`.m4a`,mimeType:`audio/x-m4a`},{ext:`.m4v`,mimeType:`video/x-m4v`},{ext:`.heic`,mimeType:`image/heic`},{ext:`.heic`,mimeType:`image/heic-sequence`},{ext:`.heif`,mimeType:`image/heif`},{ext:`.heif`,mimeType:`image/heif-sequence`},{ext:`.mj2`,mimeType:`video/mj2`},{ext:`.dvb`,mimeType:`video/vnd.dvb.file`},{ext:`.webm`,mimeType:`video/webm`},{ext:`.avi`,mimeType:`video/x-msvideo`},{ext:`.flv`,mimeType:`video/x-flv`},{ext:`.mkv`,mimeType:`video/x-matroska`},{ext:`.asf`,mimeType:`video/x-ms-asf`},{ext:`.asf`,mimeType:`video/x-ms-wmv`},{ext:`.asf`,mimeType:`video/asf`},{ext:`.aac`,mimeType:`audio/aac`},{ext:`.voc`,mimeType:`audio/x-unknown`},{ext:`.m3u`,mimeType:`application/vnd.apple.mpegurl`},{ext:`.rmvb`,mimeType:`application/vnd.rn-realmedia-vbr`},{ext:`.gz`,mimeType:`application/gzip`},{ext:`.class`,mimeType:`application/x-java-applet`},{ext:`.swf`,mimeType:`application/x-shockwave-flash`},{ext:`.crx`,mimeType:`application/x-chrome-extension`},{ext:`.ttf`,mimeType:`font/ttf`},{ext:`.woff`,mimeType:`font/woff`},{ext:`.woff2`,mimeType:`font/woff2`},{ext:`.otf`,mimeType:`font/otf`},{ext:`.ttc`,mimeType:`font/collection`},{ext:`.eot`,mimeType:`application/vnd.ms-fontobject`},{ext:`.wasm`,mimeType:`application/wasm`},{ext:`.shx`,mimeType:`application/vnd.shx`},{ext:`.shp`,mimeType:`application/vnd.shp`},{ext:`.dbf`,mimeType:`application/x-dbf`},{ext:`.dcm`,mimeType:`application/dicom`},{ext:`.rar`,mimeType:`application/x-rar-compressed`},{ext:`.djvu`,mimeType:`image/vnd.djvu`},{ext:`.mobi`,mimeType:`application/x-mobipocket-ebook`},{ext:`.lit`,mimeType:`application/x-ms-reader`},{ext:`.bpg`,mimeType:`image/bpg`},{ext:`.cbor`,mimeType:`application/cbor`},{ext:`.sqlite`,mimeType:`application/vnd.sqlite3`},{ext:`.dwg`,mimeType:`image/vnd.dwg`},{ext:`.nes`,mimeType:`application/vnd.nintendo.snes.rom`},{ext:`.lnk`,mimeType:`application/x-ms-shortcut`},{ext:`.macho`,mimeType:`application/x-mach-binary`},{ext:`.qcp`,mimeType:`audio/qcelp`},{ext:`.icns`,mimeType:`image/x-icns`},{ext:`.hdr`,mimeType:`image/vnd.radiance`},{ext:`.mrc`,mimeType:`application/marc`},{ext:`.mdb`,mimeType:`application/x-msaccess`},{ext:`.accdb`,mimeType:`application/x-msaccess`},{ext:`.zst`,mimeType:`application/zstd`},{ext:`.cab`,mimeType:`application/vnd.ms-cab-compressed`},{ext:`.rpm`,mimeType:`application/x-rpm`},{ext:`.xz`,mimeType:`application/x-xz`},{ext:`.lz`,mimeType:`application/lzip`},{ext:`.torrent`,mimeType:`application/x-bittorrent`},{ext:`.cpio`,mimeType:`application/x-cpio`},{ext:``,mimeType:`application/tzif`},{ext:`.xcf`,mimeType:`image/x-xcf`},{ext:`.pat`,mimeType:`image/x-gimp-pat`},{ext:`.gbr`,mimeType:`image/x-gimp-gbr`},{ext:`.glb`,mimeType:`model/gltf-binary`},{ext:`.cab`,mimeType:`application/x-installshield`},{ext:`.jxr`,mimeType:`image/jxr`},{ext:`.parquet`,mimeType:`application/vnd.apache.parquet`},{ext:`.txt`,mimeType:`text/plain`},{ext:`.html`,mimeType:`text/html`},{ext:`.svg`,mimeType:`image/svg+xml`},{ext:`.xml`,mimeType:`text/xml`},{ext:`.rss`,mimeType:`application/rss+xml`},{ext:`.atom`,mimeType:`application/atom+xml`},{ext:`.x3d`,mimeType:`model/x3d+xml`},{ext:`.kml`,mimeType:`application/vnd.google-earth.kml+xml`},{ext:`.xlf`,mimeType:`application/x-xliff+xml`},{ext:`.dae`,mimeType:`model/vnd.collada+xml`},{ext:`.gml`,mimeType:`application/gml+xml`},{ext:`.gpx`,mimeType:`application/gpx+xml`},{ext:`.tcx`,mimeType:`application/vnd.garmin.tcx+xml`},{ext:`.amf`,mimeType:`application/x-amf`},{ext:`.3mf`,mimeType:`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`},{ext:`.xfdf`,mimeType:`application/vnd.adobe.xfdf`},{ext:`.owl`,mimeType:`application/owl+xml`},{ext:`.php`,mimeType:`text/x-php`},{ext:`.js`,mimeType:`text/javascript`},{ext:`.lua`,mimeType:`text/x-lua`},{ext:`.pl`,mimeType:`text/x-perl`},{ext:`.py`,mimeType:`text/x-python`},{ext:`.json`,mimeType:`application/json`},{ext:`.geojson`,mimeType:`application/geo+json`},{ext:`.har`,mimeType:`application/json`},{ext:`.ndjson`,mimeType:`application/x-ndjson`},{ext:`.rtf`,mimeType:`text/rtf`},{ext:`.srt`,mimeType:`application/x-subrip`},{ext:`.tcl`,mimeType:`text/x-tcl`},{ext:`.csv`,mimeType:`text/csv`},{ext:`.tsv`,mimeType:`text/tab-separated-values`},{ext:`.vcf`,mimeType:`text/vcard`},{ext:`.ics`,mimeType:`text/calendar`},{ext:`.warc`,mimeType:`application/warc`},{ext:`.vtt`,mimeType:`text/vtt`},{ext:`.pbm`,mimeType:`image/x-portable-bitmap`},{ext:`.pgm`,mimeType:`image/x-portable-graymap`},{ext:`.ppm`,mimeType:`image/x-portable-pixmap`},{ext:`.eml`,mimeType:`message/rfc822`}];var p=new BroadcastChannel(`tabsSync`),m=`pbSettings`,h=`pbColorScheme`;window.app=window.app||{},window.app.store=store({_ready:!1,superuser:null,showHeader:!0,page:t.div({className:`page`},()=>{if(!app.store._ready)return t.span({className:`loader lg m-auto`,title:`Loading plugins...`})}),mainLogo:`./images/logo.svg`,headerLogo:`./images/logo_white.svg`,favicon:``,title:``,_mediaColorScheme:``,userColorScheme:window.localStorage.getItem(h)||``,get activeColorScheme(){return app.store.userColorScheme?app.store.userColorScheme:app.store._mediaColorScheme||`light`},errors:null,creditLinks:[{href:`https://pocketbase.io/docs`,icon:`ri-book-open-line`,label:`Docs`},{href:`https://github.com/pocketbase/pocketbase/releases`,icon:`ri-github-line`,label:`PocketBase v0.40.3`}],headerLinks:[{href:`#/collections`,icon:`ri-database-2-line`,label:`Collections`},{href:`#/logs`,icon:`ri-bar-chart-box-line`,label:`Logs`},{href:`#/settings`,icon:`ri-settings-3-line`,label:`Settings`}],settingsNavGroups:{System:[{href:`#/settings`,icon:`ri-home-gear-line`,label:`Application`},{href:`#/settings/mail`,icon:`ri-send-plane-2-line`,label:`Mail settings`},{href:`#/settings/storage`,icon:`ri-archive-drawer-line`,label:`Files storage`},{href:`#/settings/backups`,icon:`ri-archive-line`,label:`Backups`},{href:`#/settings/crons`,icon:`ri-time-line`,label:`Crons`}],Sync:[{href:`#/settings/export-collections`,icon:`ri-uninstall-line`,label:`Export collections`},{href:`#/settings/import-collections`,icon:`ri-install-line`,label:`Import collections`}],Debug:[{href:`#/settings/sql`,icon:`ri-terminal-box-line`,label:`SQL console`}]},predefinedAccentColors:[`#1055c9`,`#a3142a`,`#096d5c`,`#e6620a`,`#007d9c`,`#3f3da9`],settings:app.utils.getLocalHistory(m,{}),isLoadingSettings:!1,async loadSettings(){app.store.isLoadingSettings=!0;try{let e=await app.pb.settings.getAll({requestKey:`appStore.loadSettings`});app.store.settings=e,app.store.isLoadingSettings=!1}catch(e){e.isAbort||(app.store.isLoadingSettings=!1,app.checkApiError(e))}},collections:[],collectionScaffolds:{},isLoadingCollections:!1,_activeCollectionIdOrName:``,get activeCollection(){let e=app.store._activeCollectionIdOrName;return app.store.collections.find(n=>n.id==e||n.name==e)||app.store.collections[0]},set activeCollection(e){typeof e==`string`?app.store._activeCollectionIdOrName=e:app.store._activeCollectionIdOrName=e?.id},async silentlyReloadCollections(){try{let e=await app.pb.collections.getFullList({requestKey:`appStore.silentlyReloadCollections`});e=app.utils.sortedCollectionsByType(e),JSON.stringify(e)!=JSON.stringify(app.store.collections)&&(app.store.collections=e)}catch(e){e.isAbort||console.warn(`failed to reload app store collections:`,e)}},async loadCollections(e=null){app.store.isLoadingCollections=!0;try{let[n,r]=await Promise.all([app.pb.collections.getScaffolds({requestKey:`appStore.loadCollections.getScaffolds`}),app.pb.collections.getFullList({requestKey:`appStore.loadCollections.getFullList`})]);r=app.utils.sortedCollectionsByType(r),JSON.stringify(app.store.collections)!=JSON.stringify(r)&&(app.store.collections=r),app.store.collectionScaffolds=n,app.store._activeCollectionIdOrName=e||app.store._activeCollectionIdOrName||app.store.collections[0]?.id||``,app.store.isLoadingCollections=!1}catch(e){e.isAbort||(app.store.isLoadingCollections=!1,app.checkApiError(e))}},addOrUpdateCollection(e){let n=app.store.collections.findIndex(n=>n.id==e.id);n>=0?(app.store.activeCollection?.id==e.id&&(app.store._activeCollectionIdOrName=e.id),app.store.collections[n]=e):app.store.collections.push(e),app.store.collections=app.utils.sortedCollectionsByType(app.store.collections)},oauth2Providers:[],isLoadingOAuth2Providers:!1,async loadOAuth2Providers(){app.store.isLoadingOAuth2Providers=!0;try{app.store.oauth2Providers=await app.pb.collections.getAllOAuth2Providers(),app.store.isLoadingOAuth2Providers=!1}catch(e){e.isAbort||(app.checkApiError(e),app.store.isLoadingOAuth2Providers=!1)}}}),window.addEventListener(`hashchange`,()=>{app.store.title=``,app.store.errors=null}),watch(()=>{let e=app.utils.toArray(app.store.title),n=app.store.settings?.meta?.appName||``;n&&e.push(n),document.title=e.join(` - `)});var g;watch(()=>app.store.settings?.meta?.accentColor,e=>{g||(g=t.meta({name:`theme-color`}),document.head.appendChild(g)),e?(g?.setAttribute(`content`,e),document.documentElement.style.setProperty(`--accentColor`,e)):(g?.removeAttribute(`content`),document.documentElement.style.removeProperty(`--accentColor`))});var _;watch(()=>app.store.favicon,e=>{_||(_=t.link({rel:`icon`}),document.head.appendChild(_)),e?_.href=e:_.href=window.location.href.startsWith(`https://`)?`./images/favicon_prod.png`:`./images/favicon.png`});var v=window.matchMedia(`(prefers-color-scheme: dark)`);app.store._mediaColorScheme=v.matches?`dark`:`light`,v.addEventListener(`change`,({matches:e})=>{app.store._mediaColorScheme=e?`dark`:`light`}),watch(()=>app.store.userColorScheme,e=>{e?window.localStorage.setItem(h,e):window.localStorage.removeItem(h),p?.postMessage({colorScheme:e})});var ee;watch(()=>app.store.activeColorScheme,e=>{clearTimeout(ee),document.documentElement.style.setProperty(`--animationSpeed`,`0`),document.documentElement.setAttribute(`data-color-scheme`,e),ee=setTimeout(()=>{document.documentElement.style.removeProperty(`--animationSpeed`)},100)});function te(e,n){e.__errListener&&=(e.removeEventListener(`input`,e.__errListener),e.removeEventListener(`change`,e.__errListener),null),e.setCustomValidity&&(e.setCustomValidity(``),e._oldTitle?e.setAttribute(`title`,e._oldTitle):e.removeAttribute(`title`)),e.removeAttribute(`data-error`);let r=n.nextSibling;r&&r.classList?.contains(`generated-error`)&&r.getAttribute(`data-input-name`)==e.getAttribute(`name`)&&r.remove(),n.querySelector(`[data-error]`)||n.classList.remove(`error`)}watch(()=>JSON.stringify(app.store.errors)&&app.store.errors,e=>{let n=document.querySelectorAll(`[name]`);for(let r of n){if(r.classList.contains(`no-error`))continue;let n=r.closest(`.field-list`)||r.closest(`.fields`)||r.closest(`.field`);if(!n)continue;let i=r.getAttribute(`name`);te(r,n);let a=app.utils.getByPath(e,i),o=a?.message||``;if(!o&&!app.utils.isEmpty(a)){let e=[];for(let n in a)a[n]?.message&&e.push(`${n}: ${a[n]?.message}`);o=e.join(` +`),n+=`)`,e.where&&(n+=` WHERE ${e.where}`),n},replaceIndexFields(e,n){let r=app.utils.parseIndex(e);return typeof n==`function`?Object.assign(r,n(r)||{}):Object.assign(r,n||{}),app.utils.buildIndex(r)},replaceIndexColumn(e,n,r){if(n===r)return e;let i=app.utils.parseIndex(e),a=!1;for(let e of i.columns)e.name===n&&(e.name=r,a=!0);return a?app.utils.buildIndex(i):e}};window.app=window.app||{},window.app.utils=f,window.app=window.app||{},window.app.utils=window.app.utils||{},window.app.utils.mimeTypes=[{ext:``,mimeType:`application/octet-stream`},{ext:`.xpm`,mimeType:`image/x-xpixmap`},{ext:`.7z`,mimeType:`application/x-7z-compressed`},{ext:`.zip`,mimeType:`application/zip`},{ext:`.xlsx`,mimeType:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`},{ext:`.docx`,mimeType:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`},{ext:`.pptx`,mimeType:`application/vnd.openxmlformats-officedocument.presentationml.presentation`},{ext:`.epub`,mimeType:`application/epub+zip`},{ext:`.apk`,mimeType:`application/vnd.android.package-archive`},{ext:`.jar`,mimeType:`application/jar`},{ext:`.odt`,mimeType:`application/vnd.oasis.opendocument.text`},{ext:`.ott`,mimeType:`application/vnd.oasis.opendocument.text-template`},{ext:`.ods`,mimeType:`application/vnd.oasis.opendocument.spreadsheet`},{ext:`.ots`,mimeType:`application/vnd.oasis.opendocument.spreadsheet-template`},{ext:`.odp`,mimeType:`application/vnd.oasis.opendocument.presentation`},{ext:`.otp`,mimeType:`application/vnd.oasis.opendocument.presentation-template`},{ext:`.odg`,mimeType:`application/vnd.oasis.opendocument.graphics`},{ext:`.otg`,mimeType:`application/vnd.oasis.opendocument.graphics-template`},{ext:`.odf`,mimeType:`application/vnd.oasis.opendocument.formula`},{ext:`.odc`,mimeType:`application/vnd.oasis.opendocument.chart`},{ext:`.sxc`,mimeType:`application/vnd.sun.xml.calc`},{ext:`.pdf`,mimeType:`application/pdf`},{ext:`.fdf`,mimeType:`application/vnd.fdf`},{ext:``,mimeType:`application/x-ole-storage`},{ext:`.msi`,mimeType:`application/x-ms-installer`},{ext:`.aaf`,mimeType:`application/octet-stream`},{ext:`.msg`,mimeType:`application/vnd.ms-outlook`},{ext:`.xls`,mimeType:`application/vnd.ms-excel`},{ext:`.pub`,mimeType:`application/vnd.ms-publisher`},{ext:`.ppt`,mimeType:`application/vnd.ms-powerpoint`},{ext:`.doc`,mimeType:`application/msword`},{ext:`.ps`,mimeType:`application/postscript`},{ext:`.psd`,mimeType:`image/vnd.adobe.photoshop`},{ext:`.p7s`,mimeType:`application/pkcs7-signature`},{ext:`.ogg`,mimeType:`application/ogg`},{ext:`.oga`,mimeType:`audio/ogg`},{ext:`.ogv`,mimeType:`video/ogg`},{ext:`.png`,mimeType:`image/png`},{ext:`.png`,mimeType:`image/vnd.mozilla.apng`},{ext:`.jpg`,mimeType:`image/jpeg`},{ext:`.jxl`,mimeType:`image/jxl`},{ext:`.jp2`,mimeType:`image/jp2`},{ext:`.jpf`,mimeType:`image/jpx`},{ext:`.jpm`,mimeType:`image/jpm`},{ext:`.jxs`,mimeType:`image/jxs`},{ext:`.gif`,mimeType:`image/gif`},{ext:`.webp`,mimeType:`image/webp`},{ext:`.exe`,mimeType:`application/vnd.microsoft.portable-executable`},{ext:``,mimeType:`application/x-elf`},{ext:``,mimeType:`application/x-object`},{ext:``,mimeType:`application/x-executable`},{ext:`.so`,mimeType:`application/x-sharedlib`},{ext:``,mimeType:`application/x-coredump`},{ext:`.a`,mimeType:`application/x-archive`},{ext:`.deb`,mimeType:`application/vnd.debian.binary-package`},{ext:`.tar`,mimeType:`application/x-tar`},{ext:`.xar`,mimeType:`application/x-xar`},{ext:`.bz2`,mimeType:`application/x-bzip2`},{ext:`.fits`,mimeType:`application/fits`},{ext:`.tiff`,mimeType:`image/tiff`},{ext:`.bmp`,mimeType:`image/bmp`},{ext:`.ico`,mimeType:`image/x-icon`},{ext:`.mp3`,mimeType:`audio/mpeg`},{ext:`.flac`,mimeType:`audio/flac`},{ext:`.midi`,mimeType:`audio/midi`},{ext:`.ape`,mimeType:`audio/ape`},{ext:`.mpc`,mimeType:`audio/musepack`},{ext:`.amr`,mimeType:`audio/amr`},{ext:`.wav`,mimeType:`audio/wav`},{ext:`.aiff`,mimeType:`audio/aiff`},{ext:`.au`,mimeType:`audio/basic`},{ext:`.mpeg`,mimeType:`video/mpeg`},{ext:`.mov`,mimeType:`video/quicktime`},{ext:`.mp4`,mimeType:`video/mp4`},{ext:`.avif`,mimeType:`image/avif`},{ext:`.3gp`,mimeType:`video/3gpp`},{ext:`.3g2`,mimeType:`video/3gpp2`},{ext:`.mp4`,mimeType:`audio/mp4`},{ext:`.mqv`,mimeType:`video/quicktime`},{ext:`.m4a`,mimeType:`audio/x-m4a`},{ext:`.m4v`,mimeType:`video/x-m4v`},{ext:`.heic`,mimeType:`image/heic`},{ext:`.heic`,mimeType:`image/heic-sequence`},{ext:`.heif`,mimeType:`image/heif`},{ext:`.heif`,mimeType:`image/heif-sequence`},{ext:`.mj2`,mimeType:`video/mj2`},{ext:`.dvb`,mimeType:`video/vnd.dvb.file`},{ext:`.webm`,mimeType:`video/webm`},{ext:`.avi`,mimeType:`video/x-msvideo`},{ext:`.flv`,mimeType:`video/x-flv`},{ext:`.mkv`,mimeType:`video/x-matroska`},{ext:`.asf`,mimeType:`video/x-ms-asf`},{ext:`.asf`,mimeType:`video/x-ms-wmv`},{ext:`.asf`,mimeType:`video/asf`},{ext:`.aac`,mimeType:`audio/aac`},{ext:`.voc`,mimeType:`audio/x-unknown`},{ext:`.m3u`,mimeType:`application/vnd.apple.mpegurl`},{ext:`.rmvb`,mimeType:`application/vnd.rn-realmedia-vbr`},{ext:`.gz`,mimeType:`application/gzip`},{ext:`.class`,mimeType:`application/x-java-applet`},{ext:`.swf`,mimeType:`application/x-shockwave-flash`},{ext:`.crx`,mimeType:`application/x-chrome-extension`},{ext:`.ttf`,mimeType:`font/ttf`},{ext:`.woff`,mimeType:`font/woff`},{ext:`.woff2`,mimeType:`font/woff2`},{ext:`.otf`,mimeType:`font/otf`},{ext:`.ttc`,mimeType:`font/collection`},{ext:`.eot`,mimeType:`application/vnd.ms-fontobject`},{ext:`.wasm`,mimeType:`application/wasm`},{ext:`.shx`,mimeType:`application/vnd.shx`},{ext:`.shp`,mimeType:`application/vnd.shp`},{ext:`.dbf`,mimeType:`application/x-dbf`},{ext:`.dcm`,mimeType:`application/dicom`},{ext:`.rar`,mimeType:`application/x-rar-compressed`},{ext:`.djvu`,mimeType:`image/vnd.djvu`},{ext:`.mobi`,mimeType:`application/x-mobipocket-ebook`},{ext:`.lit`,mimeType:`application/x-ms-reader`},{ext:`.bpg`,mimeType:`image/bpg`},{ext:`.cbor`,mimeType:`application/cbor`},{ext:`.sqlite`,mimeType:`application/vnd.sqlite3`},{ext:`.dwg`,mimeType:`image/vnd.dwg`},{ext:`.nes`,mimeType:`application/vnd.nintendo.snes.rom`},{ext:`.lnk`,mimeType:`application/x-ms-shortcut`},{ext:`.macho`,mimeType:`application/x-mach-binary`},{ext:`.qcp`,mimeType:`audio/qcelp`},{ext:`.icns`,mimeType:`image/x-icns`},{ext:`.hdr`,mimeType:`image/vnd.radiance`},{ext:`.mrc`,mimeType:`application/marc`},{ext:`.mdb`,mimeType:`application/x-msaccess`},{ext:`.accdb`,mimeType:`application/x-msaccess`},{ext:`.zst`,mimeType:`application/zstd`},{ext:`.cab`,mimeType:`application/vnd.ms-cab-compressed`},{ext:`.rpm`,mimeType:`application/x-rpm`},{ext:`.xz`,mimeType:`application/x-xz`},{ext:`.lz`,mimeType:`application/lzip`},{ext:`.torrent`,mimeType:`application/x-bittorrent`},{ext:`.cpio`,mimeType:`application/x-cpio`},{ext:``,mimeType:`application/tzif`},{ext:`.xcf`,mimeType:`image/x-xcf`},{ext:`.pat`,mimeType:`image/x-gimp-pat`},{ext:`.gbr`,mimeType:`image/x-gimp-gbr`},{ext:`.glb`,mimeType:`model/gltf-binary`},{ext:`.cab`,mimeType:`application/x-installshield`},{ext:`.jxr`,mimeType:`image/jxr`},{ext:`.parquet`,mimeType:`application/vnd.apache.parquet`},{ext:`.txt`,mimeType:`text/plain`},{ext:`.html`,mimeType:`text/html`},{ext:`.svg`,mimeType:`image/svg+xml`},{ext:`.xml`,mimeType:`text/xml`},{ext:`.rss`,mimeType:`application/rss+xml`},{ext:`.atom`,mimeType:`application/atom+xml`},{ext:`.x3d`,mimeType:`model/x3d+xml`},{ext:`.kml`,mimeType:`application/vnd.google-earth.kml+xml`},{ext:`.xlf`,mimeType:`application/x-xliff+xml`},{ext:`.dae`,mimeType:`model/vnd.collada+xml`},{ext:`.gml`,mimeType:`application/gml+xml`},{ext:`.gpx`,mimeType:`application/gpx+xml`},{ext:`.tcx`,mimeType:`application/vnd.garmin.tcx+xml`},{ext:`.amf`,mimeType:`application/x-amf`},{ext:`.3mf`,mimeType:`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`},{ext:`.xfdf`,mimeType:`application/vnd.adobe.xfdf`},{ext:`.owl`,mimeType:`application/owl+xml`},{ext:`.php`,mimeType:`text/x-php`},{ext:`.js`,mimeType:`text/javascript`},{ext:`.lua`,mimeType:`text/x-lua`},{ext:`.pl`,mimeType:`text/x-perl`},{ext:`.py`,mimeType:`text/x-python`},{ext:`.json`,mimeType:`application/json`},{ext:`.geojson`,mimeType:`application/geo+json`},{ext:`.har`,mimeType:`application/json`},{ext:`.ndjson`,mimeType:`application/x-ndjson`},{ext:`.rtf`,mimeType:`text/rtf`},{ext:`.srt`,mimeType:`application/x-subrip`},{ext:`.tcl`,mimeType:`text/x-tcl`},{ext:`.csv`,mimeType:`text/csv`},{ext:`.tsv`,mimeType:`text/tab-separated-values`},{ext:`.vcf`,mimeType:`text/vcard`},{ext:`.ics`,mimeType:`text/calendar`},{ext:`.warc`,mimeType:`application/warc`},{ext:`.vtt`,mimeType:`text/vtt`},{ext:`.pbm`,mimeType:`image/x-portable-bitmap`},{ext:`.pgm`,mimeType:`image/x-portable-graymap`},{ext:`.ppm`,mimeType:`image/x-portable-pixmap`},{ext:`.eml`,mimeType:`message/rfc822`}];var p=new BroadcastChannel(`tabsSync`),m=`pbSettings`,h=`pbColorScheme`;window.app=window.app||{},window.app.store=store({_ready:!1,superuser:null,showHeader:!0,page:t.div({className:`page`},()=>{if(!app.store._ready)return t.span({className:`loader lg m-auto`,title:`Loading plugins...`})}),mainLogo:`./images/logo.svg`,headerLogo:`./images/logo_white.svg`,favicon:``,title:``,_mediaColorScheme:``,userColorScheme:window.localStorage.getItem(h)||``,get activeColorScheme(){return app.store.userColorScheme?app.store.userColorScheme:app.store._mediaColorScheme||`light`},errors:null,creditLinks:[{href:`https://pocketbase.io/docs`,icon:`ri-book-open-line`,label:`Docs`},{href:`https://github.com/pocketbase/pocketbase/releases`,icon:`ri-github-line`,label:`PocketBase v0.40.4-dev`}],headerLinks:[{href:`#/collections`,icon:`ri-database-2-line`,label:`Collections`},{href:`#/logs`,icon:`ri-bar-chart-box-line`,label:`Logs`},{href:`#/settings`,icon:`ri-settings-3-line`,label:`Settings`}],settingsNavGroups:{System:[{href:`#/settings`,icon:`ri-home-gear-line`,label:`Application`},{href:`#/settings/mail`,icon:`ri-send-plane-2-line`,label:`Mail settings`},{href:`#/settings/storage`,icon:`ri-archive-drawer-line`,label:`Files storage`},{href:`#/settings/backups`,icon:`ri-archive-line`,label:`Backups`},{href:`#/settings/crons`,icon:`ri-time-line`,label:`Crons`}],Sync:[{href:`#/settings/export-collections`,icon:`ri-uninstall-line`,label:`Export collections`},{href:`#/settings/import-collections`,icon:`ri-install-line`,label:`Import collections`}],Debug:[{href:`#/settings/sql`,icon:`ri-terminal-box-line`,label:`SQL console`}]},predefinedAccentColors:[`#1055c9`,`#a3142a`,`#096d5c`,`#e6620a`,`#007d9c`,`#3f3da9`],settings:app.utils.getLocalHistory(m,{}),isLoadingSettings:!1,async loadSettings(){app.store.isLoadingSettings=!0;try{let e=await app.pb.settings.getAll({requestKey:`appStore.loadSettings`});app.store.settings=e,app.store.isLoadingSettings=!1}catch(e){e.isAbort||(app.store.isLoadingSettings=!1,app.checkApiError(e))}},collections:[],collectionScaffolds:{},isLoadingCollections:!1,_activeCollectionIdOrName:``,get activeCollection(){let e=app.store._activeCollectionIdOrName;return app.store.collections.find(n=>n.id==e||n.name==e)||app.store.collections[0]},set activeCollection(e){typeof e==`string`?app.store._activeCollectionIdOrName=e:app.store._activeCollectionIdOrName=e?.id},async silentlyReloadCollections(){try{let e=await app.pb.collections.getFullList({requestKey:`appStore.silentlyReloadCollections`});e=app.utils.sortedCollectionsByType(e),JSON.stringify(e)!=JSON.stringify(app.store.collections)&&(app.store.collections=e)}catch(e){e.isAbort||console.warn(`failed to reload app store collections:`,e)}},async loadCollections(e=null){app.store.isLoadingCollections=!0;try{let[n,r]=await Promise.all([app.pb.collections.getScaffolds({requestKey:`appStore.loadCollections.getScaffolds`}),app.pb.collections.getFullList({requestKey:`appStore.loadCollections.getFullList`})]);r=app.utils.sortedCollectionsByType(r),JSON.stringify(app.store.collections)!=JSON.stringify(r)&&(app.store.collections=r),app.store.collectionScaffolds=n,app.store._activeCollectionIdOrName=e||app.store._activeCollectionIdOrName||app.store.collections[0]?.id||``,app.store.isLoadingCollections=!1}catch(e){e.isAbort||(app.store.isLoadingCollections=!1,app.checkApiError(e))}},addOrUpdateCollection(e){let n=app.store.collections.findIndex(n=>n.id==e.id);n>=0?(app.store.activeCollection?.id==e.id&&(app.store._activeCollectionIdOrName=e.id),app.store.collections[n]=e):app.store.collections.push(e),app.store.collections=app.utils.sortedCollectionsByType(app.store.collections)},oauth2Providers:[],isLoadingOAuth2Providers:!1,async loadOAuth2Providers(){app.store.isLoadingOAuth2Providers=!0;try{app.store.oauth2Providers=await app.pb.collections.getAllOAuth2Providers(),app.store.isLoadingOAuth2Providers=!1}catch(e){e.isAbort||(app.checkApiError(e),app.store.isLoadingOAuth2Providers=!1)}}}),window.addEventListener(`hashchange`,()=>{app.store.title=``,app.store.errors=null}),watch(()=>{let e=app.utils.toArray(app.store.title),n=app.store.settings?.meta?.appName||``;n&&e.push(n),document.title=e.join(` - `)});var g;watch(()=>app.store.settings?.meta?.accentColor,e=>{g||(g=t.meta({name:`theme-color`}),document.head.appendChild(g)),e?(g?.setAttribute(`content`,e),document.documentElement.style.setProperty(`--accentColor`,e)):(g?.removeAttribute(`content`),document.documentElement.style.removeProperty(`--accentColor`))});var _;watch(()=>app.store.favicon,e=>{_||(_=t.link({rel:`icon`}),document.head.appendChild(_)),e?_.href=e:_.href=window.location.href.startsWith(`https://`)?`./images/favicon_prod.png`:`./images/favicon.png`});var v=window.matchMedia(`(prefers-color-scheme: dark)`);app.store._mediaColorScheme=v.matches?`dark`:`light`,v.addEventListener(`change`,({matches:e})=>{app.store._mediaColorScheme=e?`dark`:`light`}),watch(()=>app.store.userColorScheme,e=>{e?window.localStorage.setItem(h,e):window.localStorage.removeItem(h),p?.postMessage({colorScheme:e})});var ee;watch(()=>app.store.activeColorScheme,e=>{clearTimeout(ee),document.documentElement.style.setProperty(`--animationSpeed`,`0`),document.documentElement.setAttribute(`data-color-scheme`,e),ee=setTimeout(()=>{document.documentElement.style.removeProperty(`--animationSpeed`)},100)});function te(e,n){e.__errListener&&=(e.removeEventListener(`input`,e.__errListener),e.removeEventListener(`change`,e.__errListener),null),e.setCustomValidity&&(e.setCustomValidity(``),e._oldTitle?e.setAttribute(`title`,e._oldTitle):e.removeAttribute(`title`)),e.removeAttribute(`data-error`);let r=n.nextSibling;r&&r.classList?.contains(`generated-error`)&&r.getAttribute(`data-input-name`)==e.getAttribute(`name`)&&r.remove(),n.querySelector(`[data-error]`)||n.classList.remove(`error`)}watch(()=>JSON.stringify(app.store.errors)&&app.store.errors,e=>{let n=document.querySelectorAll(`[name]`);for(let r of n){if(r.classList.contains(`no-error`))continue;let n=r.closest(`.field-list`)||r.closest(`.fields`)||r.closest(`.field`);if(!n)continue;let i=r.getAttribute(`name`);te(r,n);let a=app.utils.getByPath(e,i),o=a?.message||``;if(!o&&!app.utils.isEmpty(a)){let e=[];for(let n in a)a[n]?.message&&e.push(`${n}: ${a[n]?.message}`);o=e.join(` `)}o&&(n.classList.add(`error`),r.__errListener=function(){te(r,n),app.utils.deleteByPath(app.store.errors,i)},r.addEventListener(`input`,r.__errListener),r.addEventListener(`change`,r.__errListener),r.setAttribute(`data-error`,!0),r.setCustomValidity&&r.reportValidity&&r.classList.contains(`inline-error`)?(r.setCustomValidity(o),r.reportValidity(),r._oldTitle=r.title,r.title=o):n.after(t.div({"html-data-input-name":i,className:`field-help error generated-error`,textContent:o})))}}),p.onmessage=e=>{e.data?.collections&&JSON.stringify(app.store.collections)!=JSON.stringify(e.data.collections)&&(app.store.collections=e.data.collections),e.data?.settings&&JSON.stringify(app.store.settings)!=JSON.stringify(e.data.settings)&&(app.store.settings=e.data.settings),e.data?.colorScheme&&(app.store.userColorScheme=e.data.colorScheme)},watch(()=>JSON.stringify(app.store.collections),(e,n)=>{e&&e!=`[]`&&n&&n!=`[]`&&e!=n&&p?.postMessage({collections:JSON.parse(e)})}),watch(()=>JSON.stringify(app.store.settings),(e,n)=>{e&&e!=`{}`&&n&&n!=`{}`&&e!=n&&p?.postMessage({settings:JSON.parse(e)}),window.localStorage.setItem(m,e)});var y=class e extends Error{constructor(n){super(`ClientResponseError`),this.url=``,this.status=0,this.response={},this.isAbort=!1,this.originalError=null,Object.setPrototypeOf(this,e.prototype),typeof n==`object`&&n&&(this.originalError=n.originalError,this.url=typeof n.url==`string`?n.url:``,this.status=typeof n.status==`number`?n.status:0,this.isAbort=!!n.isAbort||n.name===`AbortError`||n.message===`Aborted`,this.response=n.response!==null&&typeof n.response==`object`?n.response:n.data!==null&&typeof n.data==`object`?n.data:{}),this.originalError||n instanceof e||(this.originalError=n),this.name=`ClientResponseError `+this.status,this.message=this.response?.message,this.message||=this.isAbort?`The request was aborted (most likely autocancelled; you can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation).`:this.originalError?.cause?.message?.includes(`ECONNREFUSED ::1`)?`Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).`:`Something went wrong.`,this.cause=this.originalError}get data(){return this.response}toJSON(){return{...this}}},ne=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function re(e,n){let r={};if(typeof e!=`string`)return r;let i=Object.assign({},n||{}).decode||ae,a=0;for(;a0&&(!r.exp||r.exp-n>Date.now()/1e3))}oe=typeof atob!=`function`||x?e=>{let n=String(e).replace(/=+$/,``);if(n.length%4==1)throw Error(`'atob' failed: The string to be decoded is not correctly encoded.`);for(var r,i,a=0,o=0,s=``;i=n.charAt(o++);~i&&(r=a%4?64*r+i:i,a++%4)&&(s+=String.fromCharCode(255&r>>(-2*a&6))))i=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=`.indexOf(i);return s}:atob;var C=`pb_auth`,ce=class{constructor(){this.baseToken=``,this.baseModel=null,this._onChangeCallbacks=[]}get token(){return this.baseToken}get record(){return this.baseModel}get model(){return this.baseModel}get isValid(){return!se(this.token)}get isSuperuser(){let e=S(this.token);return e.type==`auth`&&(this.record?.collectionName==`_superusers`||!this.record?.collectionName&&e.collectionId==`pbc_3142635823`)}get isAdmin(){return console.warn(`Please replace pb.authStore.isAdmin with pb.authStore.isSuperuser OR simply check the value of pb.authStore.record?.collectionName`),this.isSuperuser}get isAuthRecord(){return console.warn(`Please replace pb.authStore.isAuthRecord with !pb.authStore.isSuperuser OR simply check the value of pb.authStore.record?.collectionName`),S(this.token).type==`auth`&&!this.isSuperuser}save(e,n){this.baseToken=e||``,this.baseModel=n||null,this.triggerChange()}clear(){this.baseToken=``,this.baseModel=null,this.triggerChange()}loadFromCookie(e,n=C){let r=re(e||``)[n]||``,i={};try{i=JSON.parse(r),(typeof i!=`object`||Array.isArray(i))&&(i={})}catch{}this.save(i.token||``,i.record||i.model||null)}exportToCookie(e,n=C){let r={secure:!0,sameSite:!0,httpOnly:!0,path:`/`},i=S(this.token);r.expires=i?.exp?new Date(1e3*i.exp):new Date(`1970-01-01`),e=Object.assign({},r,e);let a={token:this.token,record:this.record?JSON.parse(JSON.stringify(this.record)):null},o=ie(n,JSON.stringify(a),e),s=typeof Blob<`u`?new Blob([o]).size:o.length;if(a.record&&s>4096){a.record={id:a.record?.id,email:a.record?.email};let r=[`collectionId`,`collectionName`,`verified`];for(let e in this.record)r.includes(e)&&(a.record[e]=this.record[e]);o=ie(n,JSON.stringify(a),e)}return o}onChange(e,n=!1){return this._onChangeCallbacks.push(e),n&&e(this.token,this.record),()=>{for(let n=this._onChangeCallbacks.length-1;n>=0;n--)if(this._onChangeCallbacks[n]==e)return delete this._onChangeCallbacks[n],void this._onChangeCallbacks.splice(n,1)}}triggerChange(){for(let e of this._onChangeCallbacks)e&&e(this.token,this.record)}},w=class extends ce{constructor(e=`pocketbase_auth`){super(),this.storageFallback={},this.storageKey=e,this._bindStorageEvent()}get token(){return(this._storageGet(this.storageKey)||{}).token||``}get record(){let e=this._storageGet(this.storageKey)||{};return e.record||e.model||null}get model(){return this.record}save(e,n){this._storageSet(this.storageKey,{token:e,record:n}),super.save(e,n)}clear(){this._storageRemove(this.storageKey),super.clear()}_storageGet(e){if(typeof window<`u`&&window?.localStorage){let n=window.localStorage.getItem(e)||``;try{return JSON.parse(n)}catch{return n}}return this.storageFallback[e]}_storageSet(e,n){if(typeof window<`u`&&window?.localStorage){let r=n;typeof n!=`string`&&(r=JSON.stringify(n)),window.localStorage.setItem(e,r)}else this.storageFallback[e]=n}_storageRemove(e){typeof window<`u`&&window?.localStorage&&window.localStorage?.removeItem(e),delete this.storageFallback[e]}_bindStorageEvent(){typeof window<`u`&&window?.localStorage&&window.addEventListener&&window.addEventListener(`storage`,(e=>{if(e.key!=this.storageKey)return;let n=this._storageGet(this.storageKey)||{};super.save(n.token||``,n.record||n.model||null)}))}},T=class{constructor(e){this.client=e}},E=class extends T{async getAll(e){return e=Object.assign({method:`GET`},e),this.client.send(`/api/settings`,e)}async update(e,n){return n=Object.assign({method:`PATCH`,body:e},n),this.client.send(`/api/settings`,n)}async testS3(e=`storage`,n){return n=Object.assign({method:`POST`,body:{filesystem:e}},n),this.client.send(`/api/settings/test/s3`,n).then((()=>!0))}async testEmail(e,n,r,i){return i=Object.assign({method:`POST`,body:{email:n,template:r,collection:e}},i),this.client.send(`/api/settings/test/email`,i).then((()=>!0))}async generateAppleClientSecret(e,n,r,i,a,o){return o=Object.assign({method:`POST`,body:{clientId:e,teamId:n,keyId:r,privateKey:i,duration:a}},o),this.client.send(`/api/settings/apple/generate-client-secret`,o)}},D=[`requestKey`,`$cancelKey`,`$autoCancel`,`fetch`,`headers`,`body`,`query`,`params`,`cache`,`credentials`,`headers`,`integrity`,`keepalive`,`method`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`window`];function O(e){if(e){e.query=e.query||{};for(let n in e)D.includes(n)||(e.query[n]=e[n],delete e[n])}}function k(e){let n=[];for(let r in e){let i=encodeURIComponent(r),a=Array.isArray(e[r])?e[r]:[e[r]];for(let e of a)e=A(e),e!==null&&n.push(i+`=`+e)}return n.join(`&`)}function A(e){return e==null?null:e instanceof Date?encodeURIComponent(e.toISOString().replace(`T`,` `)):encodeURIComponent(typeof e==`object`?JSON.stringify(e):e)}var j=class extends T{constructor(){super(...arguments),this.clientId=``,this.eventSource=null,this.subscriptions={},this.lastSentSubscriptions=[],this.maxConnectTimeout=15e3,this.reconnectAttempts=0,this.maxReconnectAttempts=1/0,this.predefinedReconnectIntervals=[200,300,500,1e3,1200,1500,2e3],this.pendingConnects=[],this.pendingSubmits=[],this.isProcessingPendingSubmits=!1}get isConnected(){return!!this.eventSource&&!!this.clientId&&!this.pendingConnects.length}async subscribe(e,n,r){if(!e)throw Error(`topic must be set.`);let i=e;if(r){O(r=Object.assign({},r));let e=`options=`+encodeURIComponent(JSON.stringify({query:r.query,headers:r.headers}));i+=(i.includes(`?`)?`&`:`?`)+e}let a=function(e){let r=e,i;try{i=JSON.parse(r?.data)}catch{}n(i||{})};return this.subscriptions[i]||(this.subscriptions[i]=[]),this.subscriptions[i].push(a),this.isConnected?this.subscriptions[i].length===1?await this.submitSubscriptions():this.eventSource?.addEventListener(i,a):await this.connect(),async()=>this.unsubscribeByTopicAndListener(e,a)}async unsubscribe(e){if(e){let n=this.getSubscriptionsByTopic(e);for(let e in n)if(this.hasSubscriptionListeners(e)){for(let n of this.subscriptions[e])this.eventSource?.removeEventListener(e,n);delete this.subscriptions[e]}}else this.subscriptions={};await this.submitSubscriptions()}async unsubscribeByPrefix(e){let n=!1;for(let r in this.subscriptions)if((r+`?`).startsWith(e)){n=!0;for(let e of this.subscriptions[r])this.eventSource?.removeEventListener(r,e);delete this.subscriptions[r]}n&&await this.submitSubscriptions()}async unsubscribeByTopicAndListener(e,n){let r=this.getSubscriptionsByTopic(e);for(let e in r){if(!Array.isArray(this.subscriptions[e])||!this.subscriptions[e].length)continue;let r=!1;for(let i=this.subscriptions[e].length-1;i>=0;i--)this.subscriptions[e][i]===n&&(r=!0,delete this.subscriptions[e][i],this.subscriptions[e].splice(i,1),this.eventSource?.removeEventListener(e,n));r&&(this.subscriptions[e].length||delete this.subscriptions[e])}await this.submitSubscriptions()}hasSubscriptionListeners(e){if(this.subscriptions=this.subscriptions||{},e)return!!this.subscriptions[e]?.length;for(let e in this.subscriptions)if(this.subscriptions[e]?.length)return!0;return!1}async submitSubscriptions(){return new Promise(((e,n)=>{this.pendingSubmits.push({resolve:e,reject:n}),this.pendingSubmits.length==1&&queueMicrotask((()=>this.finalizePendingSubscriptions()))}))}async finalizePendingSubscriptions(){if(this.isProcessingPendingSubmits||!this.pendingSubmits.length)return;let e=this.pendingSubmits.slice();this.pendingSubmits=[],this.isProcessingPendingSubmits=!0;try{await this.sendSubscriptions();for(let n of e)n.resolve()}catch(n){for(let r of e)n?r.reject(n):r.resolve()}finally{this.isProcessingPendingSubmits=!1,this.pendingSubmits.length>0&&await this.finalizePendingSubscriptions()}}getSubscriptionsCancelKey(){return`realtime_`+this.clientId}getSubscriptionsByTopic(e){let n={};e=e.includes(`?`)?e:e+`?`;for(let r in this.subscriptions)(r+`?`).startsWith(e)&&(n[r]=this.subscriptions[r]);return n}getNonEmptySubscriptionKeys(){let e=[];for(let n in this.subscriptions)this.subscriptions[n].length&&e.push(n);return e}hasUnsentSubscriptions(){let e=this.getNonEmptySubscriptionKeys();if(e.length!=this.lastSentSubscriptions.length)return!0;for(let n of e)if(!this.lastSentSubscriptions.includes(n))return!0;return!1}async sendSubscriptions(){if(this.clientId){if(!this.hasSubscriptionListeners())return this.disconnect();if(this.hasUnsentSubscriptions())return this.addAllSubscriptionListeners(),this.lastSentSubscriptions=this.getNonEmptySubscriptionKeys(),this.client.send(`/api/realtime`,{method:`POST`,body:{clientId:this.clientId,subscriptions:this.lastSentSubscriptions},requestKey:this.getSubscriptionsCancelKey()}).catch((e=>{if(!e?.isAbort)throw e}))}}addAllSubscriptionListeners(){if(this.eventSource){this.removeAllSubscriptionListeners();for(let e in this.subscriptions)for(let n of this.subscriptions[e])this.eventSource.addEventListener(e,n)}}removeAllSubscriptionListeners(){if(this.eventSource)for(let e in this.subscriptions)for(let n of this.subscriptions[e])this.eventSource.removeEventListener(e,n)}async connect(){if(!(this.reconnectAttempts>0))return new Promise(((e,n)=>{this.pendingConnects.push({resolve:e,reject:n}),this.pendingConnects.length==1&&queueMicrotask((()=>this.initConnect()))}))}initConnect(){this.disconnect(!0),clearTimeout(this.connectTimeoutId),this.connectTimeoutId=setTimeout((()=>{this.connectErrorHandler(Error(`EventSource connect took too long.`))}),this.maxConnectTimeout),this.eventSource=new EventSource(this.client.buildURL(`/api/realtime`)),this.eventSource.onerror=e=>{this.connectErrorHandler(Error(`Failed to establish realtime connection.`))},this.eventSource.addEventListener(`PB_CONNECT`,(e=>{let n=e;this.clientId=n?.lastEventId,this.lastSentSubscriptions=[],this.submitSubscriptions().then((async()=>{let n=3;for(;this.hasUnsentSubscriptions()&&n>0;)n--,await this.submitSubscriptions();for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[],this.reconnectAttempts=0,clearTimeout(this.reconnectTimeoutId),clearTimeout(this.connectTimeoutId);let r=this.getSubscriptionsByTopic(`PB_CONNECT`);for(let n in r)for(let i of r[n])i(e);this.hasUnsentSubscriptions()&&await this.submitSubscriptions()})).catch((e=>{this.clientId=``,this.lastSentSubscriptions=[],this.connectErrorHandler(e)}))}))}connectErrorHandler(e){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),!this.clientId&&!this.reconnectAttempts||this.reconnectAttempts>this.maxReconnectAttempts){for(let n of this.pendingConnects)n.reject(new y(e));this.pendingConnects=[],this.disconnect();return}this.disconnect(!0);let n=this.predefinedReconnectIntervals[this.reconnectAttempts]||this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length-1];this.reconnectAttempts++,this.reconnectTimeoutId=setTimeout((()=>{this.initConnect()}),n)}disconnect(e=!1){if(this.clientId&&this.onDisconnect&&this.onDisconnect(Object.keys(this.subscriptions)),clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),this.removeAllSubscriptionListeners(),this.client.cancelRequest(this.getSubscriptionsCancelKey()),this.eventSource?.close(),this.eventSource=null,this.clientId=``,this.lastSentSubscriptions=[],!e){this.reconnectAttempts=0;for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[]}}},M=class extends T{decode(e){return e}async getFullList(e,n){if(typeof e==`number`)return this._getFullList(e,n);let r=1e3;return(n=Object.assign({},e,n)).batch&&(r=n.batch,delete n.batch),this._getFullList(r,n)}async getList(e=1,n=30,r){return(r=Object.assign({method:`GET`},r)).query=Object.assign({page:e,perPage:n},r.query),this.client.send(this.baseCrudPath,r).then((e=>(e.items=e.items?.map((e=>this.decode(e)))||[],e)))}async getFirstListItem(e,n){return(n=Object.assign({requestKey:`one_by_filter_`+this.baseCrudPath+`_`+e},n)).query=Object.assign({filter:e,skipTotal:1},n.query),this.getList(1,1,n).then((e=>{if(!e?.items?.length)throw new y({status:404,response:{code:404,message:`The requested resource wasn't found.`,data:{}}});return e.items[0]}))}async getOne(e,n){if(!e)throw new y({url:this.client.buildURL(this.baseCrudPath+`/`),status:404,response:{code:404,message:`Missing required record id.`,data:{}}});return n=Object.assign({method:`GET`},n),this.client.send(this.baseCrudPath+`/`+encodeURIComponent(e),n).then((e=>this.decode(e)))}async create(e,n){return n=Object.assign({method:`POST`,body:e},n),this.client.send(this.baseCrudPath,n).then((e=>this.decode(e)))}async update(e,n,r){return r=Object.assign({method:`PATCH`,body:n},r),this.client.send(this.baseCrudPath+`/`+encodeURIComponent(e),r).then((e=>this.decode(e)))}async delete(e,n){return n=Object.assign({method:`DELETE`},n),this.client.send(this.baseCrudPath+`/`+encodeURIComponent(e),n).then((()=>!0))}_getFullList(e=1e3,n){(n||={}).query=Object.assign({skipTotal:1},n.query);let r=[],i=async a=>this.getList(a,e||1e3,n).then((e=>{let n=e.items;return r=r.concat(n),n.length==e.perPage?i(a+1):r}));return i(1)}};function N(e,n,r,i){let a=i!==void 0;return a||r!==void 0?a?(console.warn(e),n.body=Object.assign({},n.body,r),n.query=Object.assign({},n.query,i),n):Object.assign(n,r):n}function le(e){e._resetAutoRefresh?.()}var ue=class extends M{constructor(e,n){super(e),this.collectionIdOrName=n}get baseCrudPath(){return this.baseCollectionPath+`/records`}get baseCollectionPath(){return`/api/collections/`+encodeURIComponent(this.collectionIdOrName)}get isSuperusers(){return this.collectionIdOrName==`_superusers`||this.collectionIdOrName==`_pbc_2773867675`}async subscribe(e,n,r){if(!e)throw Error(`Missing topic.`);if(!n)throw Error(`Missing subscription callback.`);return this.client.realtime.subscribe(this.collectionIdOrName+`/`+e,n,r)}async unsubscribe(e){return e?this.client.realtime.unsubscribe(this.collectionIdOrName+`/`+e):this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName)}async getFullList(e,n){if(typeof e==`number`)return super.getFullList(e,n);let r=Object.assign({},e,n);return super.getFullList(r)}async getList(e=1,n=30,r){return super.getList(e,n,r)}async getFirstListItem(e,n){return super.getFirstListItem(e,n)}async getOne(e,n){return super.getOne(e,n)}async create(e,n){return super.create(e,n)}async update(e,n,r){return super.update(e,n,r).then((e=>{if(this.client.authStore.record?.id===e?.id&&(this.client.authStore.record?.collectionId===this.collectionIdOrName||this.client.authStore.record?.collectionName===this.collectionIdOrName)){let n=Object.assign({},this.client.authStore.record.expand),r=Object.assign({},this.client.authStore.record,e);n&&(r.expand=Object.assign(n,e.expand)),this.client.authStore.save(this.client.authStore.token,r)}return e}))}async delete(e,n){return super.delete(e,n).then((n=>(!n||this.client.authStore.record?.id!==e||this.client.authStore.record?.collectionId!==this.collectionIdOrName&&this.client.authStore.record?.collectionName!==this.collectionIdOrName||this.client.authStore.clear(),n)))}authResponse(e){let n=this.decode(e?.record||{});return this.client.authStore.save(e?.token,n),Object.assign({},e,{token:e?.token||``,record:n})}async listAuthMethods(e){return e=Object.assign({method:`GET`,fields:`mfa,otp,password,oauth2`},e),this.client.send(this.baseCollectionPath+`/auth-methods`,e)}async authWithPassword(e,n,r){let i;r=Object.assign({method:`POST`,body:{identity:e,password:n}},r),this.isSuperusers&&(i=r.autoRefreshThreshold,delete r.autoRefreshThreshold,r.autoRefresh||le(this.client));let a=await this.client.send(this.baseCollectionPath+`/auth-with-password`,r);return a=this.authResponse(a),i&&this.isSuperusers&&function(e,n,r,i){le(e);let a=e.beforeSend,o=e.authStore.record,s=e.authStore.onChange(((n,r)=>{(!n||r?.id!=o?.id||(r?.collectionId||o?.collectionId)&&r?.collectionId!=o?.collectionId)&&le(e)}));e._resetAutoRefresh=function(){s(),e.beforeSend=a,delete e._resetAutoRefresh},e.beforeSend=async(o,s)=>{let c=e.authStore.token;if(s.query?.autoRefresh)return a?a(o,s):{url:o,sendOptions:s};let l=e.authStore.isValid;if(l&&se(e.authStore.token,n))try{await r()}catch{l=!1}l||await i();let u=s.headers||{};for(let n in u)if(n.toLowerCase()==`authorization`&&c==u[n]&&e.authStore.token){u[n]=e.authStore.token;break}return s.headers=u,a?a(o,s):{url:o,sendOptions:s}}}(this.client,i,(()=>this.authRefresh({autoRefresh:!0})),(()=>this.authWithPassword(e,n,Object.assign({autoRefresh:!0},r)))),a}async authWithOAuth2Code(e,n,r,i,a,o,s){let c={method:`POST`,body:{provider:e,code:n,codeVerifier:r,redirectURL:i,createData:a}};return c=N(`This form of authWithOAuth2Code(provider, code, codeVerifier, redirectURL, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectURL, createData?, options?).`,c,o,s),this.client.send(this.baseCollectionPath+`/auth-with-oauth2`,c).then((e=>this.authResponse(e)))}authWithOAuth2(...e){if(e.length>1||typeof e?.[0]==`string`)return console.warn(`PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration.`),this.authWithOAuth2Code(e?.[0]||``,e?.[1]||``,e?.[2]||``,e?.[3]||``,e?.[4]||{},e?.[5]||{},e?.[6]||{});let n=e?.[0]||{},r=null;n.urlCallback||(r=de(void 0));let i=new j(this.client);function a(){r?.close(),i.unsubscribe()}let o={},s=n.requestKey;return s&&(o.requestKey=s),this.listAuthMethods(o).then((e=>{let o=e.oauth2.providers.find((e=>e.name===n.provider));if(!o)throw new y(Error(`Missing or invalid provider "${n.provider}".`));let c=this.client.buildURL(`/api/oauth2-redirect`);return new Promise((async(e,l)=>{let u=s?this.client.cancelControllers?.[s]:void 0;u&&(u.signal.onabort=()=>{a(),l(new y({isAbort:!0,message:`manually cancelled`}))}),i.onDisconnect=e=>{e.length&&l&&(a(),l(new y(Error(`realtime connection interrupted`))))};try{await i.subscribe(`@oauth2`,(async r=>{let s=i.clientId;try{if(!r.state||s!==r.state)throw Error(`State parameters don't match.`);if(r.error||!r.code)throw Error(`OAuth2 redirect error or missing code: `+r.error);let i=Object.assign({},n);delete i.provider,delete i.scopes,delete i.createData,delete i.urlCallback,u?.signal?.onabort&&(u.signal.onabort=null),e(await this.authWithOAuth2Code(o.name,r.code,o.codeVerifier,c,n.createData,i))}catch(e){l(new y(e))}a()}));let s={state:i.clientId};n.scopes?.length&&(s.scope=n.scopes.join(` `));let d=this._replaceQueryParams(o.authURL+c,s);await(n.urlCallback||function(e){r?r.location.href=e:r=de(e)})(d)}catch(e){u?.signal?.onabort&&(u.signal.onabort=null),a(),l(new y(e))}}))})).catch((e=>{throw a(),e}))}async authRefresh(e,n){let r={method:`POST`};return r=N(`This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).`,r,e,n),this.client.send(this.baseCollectionPath+`/auth-refresh`,r).then((e=>this.authResponse(e)))}async requestPasswordReset(e,n,r){let i={method:`POST`,body:{email:e}};return i=N(`This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).`,i,n,r),this.client.send(this.baseCollectionPath+`/request-password-reset`,i).then((()=>!0))}async confirmPasswordReset(e,n,r,i,a){let o={method:`POST`,body:{token:e,password:n,passwordConfirm:r}};return o=N(`This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).`,o,i,a),this.client.send(this.baseCollectionPath+`/confirm-password-reset`,o).then((()=>!0))}async requestVerification(e,n,r){let i={method:`POST`,body:{email:e}};return i=N(`This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).`,i,n,r),this.client.send(this.baseCollectionPath+`/request-verification`,i).then((()=>!0))}async confirmVerification(e,n,r){let i={method:`POST`,body:{token:e}};return i=N(`This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).`,i,n,r),this.client.send(this.baseCollectionPath+`/confirm-verification`,i).then((()=>{let n=S(e),r=this.client.authStore.record;return r&&!r.verified&&r.id===n.id&&r.collectionId===n.collectionId&&(r.verified=!0,this.client.authStore.save(this.client.authStore.token,r)),!0}))}async requestEmailChange(e,n,r){let i={method:`POST`,body:{newEmail:e}};return i=N(`This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).`,i,n,r),this.client.send(this.baseCollectionPath+`/request-email-change`,i).then((()=>!0))}async confirmEmailChange(e,n,r,i){let a={method:`POST`,body:{token:e,password:n}};return a=N(`This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).`,a,r,i),this.client.send(this.baseCollectionPath+`/confirm-email-change`,a).then((()=>{let n=S(e),r=this.client.authStore.record;return r&&r.id===n.id&&r.collectionId===n.collectionId&&this.client.authStore.clear(),!0}))}async listExternalAuths(e,n){return this.client.collection(`_externalAuths`).getFullList(Object.assign({},n,{filter:this.client.filter(`recordRef = {:id}`,{id:e})}))}async unlinkExternalAuth(e,n,r){let i=await this.client.collection(`_externalAuths`).getFirstListItem(this.client.filter(`recordRef = {:recordId} && provider = {:provider}`,{recordId:e,provider:n}));return this.client.collection(`_externalAuths`).delete(i.id,r).then((()=>!0))}async requestOTP(e,n){return n=Object.assign({method:`POST`,body:{email:e}},n),this.client.send(this.baseCollectionPath+`/request-otp`,n)}async authWithOTP(e,n,r){return r=Object.assign({method:`POST`,body:{otpId:e,password:n}},r),this.client.send(this.baseCollectionPath+`/auth-with-otp`,r).then((e=>this.authResponse(e)))}async impersonate(e,n,r){(r=Object.assign({method:`POST`,body:{duration:n}},r)).headers=r.headers||{},r.headers.Authorization||(r.headers.Authorization=this.client.authStore.token);let i=new Ee(this.client.baseURL,new ce,this.client.lang),a=await i.send(this.baseCollectionPath+`/impersonate/`+encodeURIComponent(e),r);return i.authStore.save(a?.token,this.decode(a?.record||{})),i}_replaceQueryParams(e,n={}){let r=e,i=``;e.indexOf(`?`)>=0&&(r=e.substring(0,e.indexOf(`?`)),i=e.substring(e.indexOf(`?`)+1));let a={},o=i.split(`&`);for(let e of o){if(e==``)continue;let n=e.split(`=`);a[decodeURIComponent(n[0].replace(/\+/g,` `))]=decodeURIComponent((n[1]||``).replace(/\+/g,` `))}for(let e in n)n.hasOwnProperty(e)&&(n[e]==null?delete a[e]:a[e]=n[e]);i=``;for(let e in a)a.hasOwnProperty(e)&&(i!=``&&(i+=`&`),i+=encodeURIComponent(e.replace(/%20/g,`+`))+`=`+encodeURIComponent(a[e].replace(/%20/g,`+`)));return i==``?r:r+`?`+i}};function de(e){if(typeof window>`u`||!window?.open)throw new y(Error(`Not in a browser context - please pass a custom urlCallback function.`));let n=1024,r=768,i=window.innerWidth,a=window.innerHeight;n=n>i?i:n,r=r>a?a:r;let o=i/2-n/2,s=a/2-r/2;return window.open(e,`popup_window`,`width=`+n+`,height=`+r+`,top=`+s+`,left=`+o+`,resizable,menubar=no`)}var fe=class extends M{get baseCrudPath(){return`/api/collections`}async import(e,n=!1,r){return r=Object.assign({method:`PUT`,body:{collections:e,deleteMissing:n}},r),this.client.send(this.baseCrudPath+`/import`,r).then((()=>!0))}async truncate(e,n){return n=Object.assign({method:`DELETE`},n),this.client.send(this.baseCrudPath+`/`+encodeURIComponent(e)+`/truncate`,n).then((()=>!0))}async getScaffolds(e){return e=Object.assign({method:`GET`},e),this.client.send(this.baseCrudPath+`/meta/scaffolds`,e)}async getAllOAuth2Providers(e){return e=Object.assign({method:`GET`},e),this.client.send(this.baseCrudPath+`/meta/oauth2-providers`,e)}async dryRunViewQuery(e,n){return n=Object.assign({method:`POST`,body:{query:e}},n),this.client.send(this.baseCrudPath+`/meta/dry-run-view`,n)}},pe=class extends T{async getList(e=1,n=30,r){return(r=Object.assign({method:`GET`},r)).query=Object.assign({page:e,perPage:n},r.query),this.client.send(`/api/logs`,r)}async getOne(e,n){if(!e)throw new y({url:this.client.buildURL(`/api/logs/`),status:404,response:{code:404,message:`Missing required log id.`,data:{}}});return n=Object.assign({method:`GET`},n),this.client.send(`/api/logs/`+encodeURIComponent(e),n)}async getStats(e){return e=Object.assign({method:`GET`},e),this.client.send(`/api/logs/stats`,e)}async truncate(e){return e=Object.assign({method:`DELETE`},e),this.client.send(`/api/logs`,e).then((()=>!0))}},me=class extends T{async check(e){return e=Object.assign({method:`GET`},e),this.client.send(`/api/health`,e)}},he=class extends T{getUrl(e,n,r={}){return console.warn(`Please replace pb.files.getUrl() with pb.files.getURL()`),this.getURL(e,n,r)}getURL(e,n,r={}){if(!n||!e?.id||!e?.collectionId&&!e?.collectionName)return``;let i=[];i.push(`api`),i.push(`files`),i.push(encodeURIComponent(e.collectionId||e.collectionName)),i.push(encodeURIComponent(e.id)),i.push(encodeURIComponent(n));let a=this.client.buildURL(i.join(`/`));!1===r.download&&delete r.download;let o=k(r);return o&&(a+=(a.includes(`?`)?`&`:`?`)+o),a}async getToken(e){return e=Object.assign({method:`POST`},e),this.client.send(`/api/files/token`,e).then((e=>e?.token||``))}},ge=class extends T{async getFullList(e){return e=Object.assign({method:`GET`},e),this.client.send(`/api/backups`,e)}async create(e,n){return n=Object.assign({method:`POST`,body:{name:e}},n),this.client.send(`/api/backups`,n).then((()=>!0))}async upload(e,n){return n=Object.assign({method:`POST`,body:e},n),this.client.send(`/api/backups/upload`,n).then((()=>!0))}async delete(e,n){return n=Object.assign({method:`DELETE`},n),this.client.send(`/api/backups/${encodeURIComponent(e)}`,n).then((()=>!0))}async restore(e,n){return n=Object.assign({method:`POST`},n),this.client.send(`/api/backups/${encodeURIComponent(e)}/restore`,n).then((()=>!0))}getDownloadUrl(e,n){return console.warn(`Please replace pb.backups.getDownloadUrl() with pb.backups.getDownloadURL()`),this.getDownloadURL(e,n)}getDownloadURL(e,n){return this.client.buildURL(`/api/backups/${encodeURIComponent(n)}?token=${encodeURIComponent(e)}`)}},_e=class extends T{async getFullList(e){return e=Object.assign({method:`GET`},e),this.client.send(`/api/crons`,e)}async run(e,n){return n=Object.assign({method:`POST`},n),this.client.send(`/api/crons/${encodeURIComponent(e)}`,n).then((()=>!0))}},ve=class extends T{async run(e,n){return n=Object.assign({method:`POST`,body:{query:e}},n),this.client.send(`/api/sql`,n)}};function ye(e){return typeof Blob<`u`&&e instanceof Blob||typeof File<`u`&&e instanceof File||typeof e==`object`&&!!e&&e.uri&&(typeof navigator<`u`&&navigator.product===`ReactNative`||typeof global<`u`&&global.HermesInternal)}function be(e){return e&&(e.constructor?.name===`FormData`||typeof FormData<`u`&&e instanceof FormData)}function xe(e){for(let n in e){let r=Array.isArray(e[n])?e[n]:[e[n]];for(let e of r)if(ye(e))return!0}return!1}var Se=/^[\-\.\d]+$/;function Ce(e){if(typeof e!=`string`)return e;if(e==`true`)return!0;if(e==`false`)return!1;if((e[0]===`-`||e[0]>=`0`&&e[0]<=`9`)&&Se.test(e)){let n=+e;if(``+n===e)return n}return e}var we=class extends T{constructor(){super(...arguments),this.requests=[],this.subs={}}collection(e){return this.subs[e]||(this.subs[e]=new Te(this.requests,e)),this.subs[e]}async send(e){let n=new FormData,r=[];for(let e=0;e{if(r===`@jsonPayload`&&typeof e==`string`)try{let r=JSON.parse(e);Object.assign(n,r)}catch(e){console.warn(`@jsonPayload error:`,e)}else n[r]===void 0?n[r]=Ce(e):(Array.isArray(n[r])||(n[r]=[n[r]]),n[r].push(Ce(e)))})),n}(r));for(let n in r){let i=r[n];if(ye(i))e.files[n]=e.files[n]||[],e.files[n].push(i);else if(Array.isArray(i)){let r=[],a=[];for(let e of i)ye(e)?r.push(e):a.push(e);if(r.length>0&&r.length==i.length){e.files[n]=e.files[n]||[];for(let i of r)e.files[n].push(i)}else if(e.json[n]=a,r.length>0){let i=n;n.startsWith(`+`)||n.endsWith(`+`)||(i+=`+`),e.files[i]=e.files[i]||[];for(let n of r)e.files[i].push(n)}}else e.json[n]=i}}},Ee=class{get baseUrl(){return this.baseURL}set baseUrl(e){this.baseURL=e}constructor(e=`/`,n,r=`en-US`){this.cancelControllers={},this.recordServices={},this.enableAutoCancellation=!0,this.baseURL=e,this.lang=r,this.authStore=n||(typeof window<`u`&&window.Deno?new ce:new w),this.collections=new fe(this),this.files=new he(this),this.logs=new pe(this),this.settings=new E(this),this.realtime=new j(this),this.health=new me(this),this.backups=new ge(this),this.crons=new _e(this),this.sql=new ve(this)}get admins(){return this.collection(`_superusers`)}createBatch(){return new we(this)}collection(e){return this.recordServices[e]||(this.recordServices[e]=new ue(this,e)),this.recordServices[e]}autoCancellation(e){return this.enableAutoCancellation=!!e,this}cancelRequest(e){return this.cancelControllers[e]&&(this.cancelControllers[e].abort(),delete this.cancelControllers[e]),this}cancelAllRequests(){for(let e in this.cancelControllers)this.cancelControllers[e].abort();return this.cancelControllers={},this}filter(e,n){if(!n)return e;function r(e){switch(typeof e){case`boolean`:case`number`:return``+e;case`string`:return JSON.stringify(e);default:if(e==null)return`null`;if(e instanceof Date)return JSON.stringify(e.toISOString().replace(`T`,` `));{let n=JSON.stringify(e);return n.startsWith(`[`)||n.startsWith(`{`)?JSON.stringify(n):n}}}for(let i in n)e=e.replaceAll(`{:`+i+`}`,r(n[i]));return e}getFileUrl(e,n,r={}){return console.warn(`Please replace pb.getFileUrl() with pb.files.getURL()`),this.files.getURL(e,n,r)}buildUrl(e){return console.warn(`Please replace pb.buildUrl() with pb.buildURL()`),this.buildURL(e)}buildURL(e){let n=this.baseURL;return typeof window>`u`||!window.location||n.startsWith(`https://`)||n.startsWith(`http://`)||(n=window.location.origin?.endsWith(`/`)?window.location.origin.substring(0,window.location.origin.length-1):window.location.origin||``,this.baseURL.startsWith(`/`)||(n+=window.location.pathname||`/`,n+=n.endsWith(`/`)?``:`/`),n+=this.baseURL),e&&(n+=n.endsWith(`/`)?``:`/`,n+=e.startsWith(`/`)?e.substring(1):e),n}async send(e,n){n=this.initSendOptions(e,n);let r=this.buildURL(e);if(this.beforeSend){let e=Object.assign({},await this.beforeSend(r,n));e.url!==void 0||e.options!==void 0?(r=e.url||r,n=e.options||n):Object.keys(e).length&&(n=e,console?.warn&&console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`."))}if(n.query!==void 0){let e=k(n.query);e&&(r+=(r.includes(`?`)?`&`:`?`)+e),delete n.query}return this.getHeader(n.headers,`Content-Type`)==`application/json`&&n.body&&typeof n.body!=`string`&&(n.body=JSON.stringify(n.body)),(n.fetch||fetch)(r,n).then((async e=>{let r={};try{r=await e.json()}catch(e){if(n.signal?.aborted||e?.name==`AbortError`||e?.message==`Aborted`)throw e}if(this.afterSend&&(r=await this.afterSend(e,r,n)),e.status>=400)throw new y({url:e.url,status:e.status,data:r});return r})).catch((e=>{throw new y(e)}))}initSendOptions(e,n){if((n=Object.assign({method:`GET`},n)).body=function(e){if(typeof FormData>`u`||e===void 0||typeof e!=`object`||!e||be(e)||!xe(e))return e;let n=new FormData;for(let r in e){let i=e[r];if(i!==void 0){if(typeof i!=`object`||xe({data:i})){let e=Array.isArray(i)?i:[i];for(let i of e)n.append(r,i)}else{let e={};e[r]=i,n.append(`@jsonPayload`,JSON.stringify(e))}}}return n}(n.body),O(n),n.query=Object.assign({},n.params,n.query),n.requestKey===void 0&&(!1===n.$autoCancel||!1===n.query.$autoCancel?n.requestKey=null:(n.$cancelKey||n.query.$cancelKey)&&(n.requestKey=n.$cancelKey||n.query.$cancelKey)),delete n.$autoCancel,delete n.query.$autoCancel,delete n.$cancelKey,delete n.query.$cancelKey,this.getHeader(n.headers,`Content-Type`)!==null||be(n.body)||(n.headers=Object.assign({},n.headers,{"Content-Type":`application/json`})),this.getHeader(n.headers,`Accept-Language`)===null&&(n.headers=Object.assign({},n.headers,{"Accept-Language":this.lang})),this.authStore.token&&this.getHeader(n.headers,`Authorization`)===null&&(n.headers=Object.assign({},n.headers,{Authorization:this.authStore.token})),this.enableAutoCancellation&&n.requestKey!==null){let r=n.requestKey||(n.method||`GET`)+e;delete n.requestKey,this.cancelRequest(r);let i=new AbortController;this.cancelControllers[r]=i,n.signal=i.signal}return n}getHeader(e,n){e||={},n=n.toLowerCase();for(let r in e)if(r.toLowerCase()==n)return e[r];return null}},De=`#/login`,Oe=window.location.pathname.endsWith(`/`)?window.location.pathname.substring(0,window.location.pathname.length-1):window.location.pathname;window.app=window.app||{},window.app.pb=new Ee(`../`,new w(`__pb_superusers__`+Oe)),app.pb.beforeSend=function(e,n){return n.headers[`x-request-source`]=`pbui`,{url:e,options:n}},app.store.superuser=app.pb.authStore.record,app.pb.authStore.onChange((e,n)=>{!n&&window.location.hash!=De&&(app.modals.close(),window.location.hash=De),app.store.superuser=n}),app.pb.authStore.isValid&&app.pb.collection(app.pb.authStore.record?.collectionName||`_superusers`).authRefresh().catch(e=>{console.warn(`Failed to refresh the existing auth token:`,e);let n=e?.status<<0;(n==401||n==403)&&(app.pb.cancelAllRequests(),app.pb.authStore.clear())}),app.pb.authStore.onChange((e,n)=>{n?.id&&(app.store.loadCollections(),app.store.loadSettings(),app.store.loadOAuth2Providers())});var ke=app.pb.collection;app.pb.collection=function(e){let n=ke.call(this,e);return Ae(n),n};function Ae(e){if(e.__customUIEvents)return;e.__customUIEvents=!0;let n=e.create;e.create=function(){return n.apply(e,arguments).then(e=>(setTimeout(()=>{document.dispatchEvent(new CustomEvent(`record:create`,{detail:e})),document.dispatchEvent(new CustomEvent(`record:save`,{detail:e}))},0),e))};let r=e.update;e.update=function(){return r.apply(e,arguments).then(e=>(setTimeout(()=>{document.dispatchEvent(new CustomEvent(`record:update`,{detail:e})),document.dispatchEvent(new CustomEvent(`record:save`,{detail:e}))},0),e))};let i=e.delete;e.delete=function(){return i.apply(e,arguments).then(n=>{let r={id:arguments[0],collectionId:e.collectionIdOrName,collectionName:e.collectionIdOrName};return setTimeout(()=>{document.dispatchEvent(new CustomEvent(`record:delete`,{detail:r}))},0),n})}}var je=`pbLastFileToken`,Me=!1,Ne=[];app.pb.authStore.onChange((e,n)=>{n?.id||window.localStorage.removeItem(je)}),window.app.getFileToken=async function(e=``){let n=e&&app.store.collections?.find(n=>n.id==e||n.name==e);if(n&&!n.fields?.find(e=>e.type==`file`&&e.protected))return;let r=window.localStorage.getItem(je);return(!r||se(r,60))&&(r=await Pe()),r};async function Pe(){return new Promise(async(e,n)=>{if(Ne.push({resolve:e,reject:n}),!Me){Me=!0;try{let e=await app.pb.files.getToken();window.localStorage.setItem(je,e),Ne.forEach(n=>n.resolve(e))}catch(e){Ne.forEach(n=>n.reject(e))}Me=!1,Ne=[]}})}window.app.checkApiError=function(e,n=!0){if(!e||!(e instanceof Error)||e.isAbort){console.warn(`checkApiError - unexpected error type:`,e);return}let r=e?.status<<0,i=e?.response||{},a=n&&(i.message||e.message||`Something went wrong!`);if(a&&app.toasts.error(a),r==0&&console.log(e),app.utils.isEmpty(i.data)||(app.store.errors=i.data),r===401&&window.location.hash!=De)return app.pb.cancelAllRequests(),app.pb.authStore.clear()};function Fe(){return()=>{if(!(!app.store._ready||!app.store.showHeader||!app.store.superuser?.id))return t.header({pbEvent:`appHeader`,rid:`appHeader`,className:`app-header accent-surface`,onmount:async e=>{await new Promise(e=>setTimeout(e,0)),e._scrollToActiveMenuItem=function(){e?.querySelector(`.app-main-nav .header-link.active`)?.scrollIntoView()},e._scrollToActiveMenuItem(),window.addEventListener(`hashchange`,e._scrollToActiveMenuItem)},onunmount:e=>{window.removeEventListener(`hashchange`,e?._scrollToActiveMenuItem)}},t.a({href:`#/`,className:`logo`},t.img({src:()=>app.store.headerLogo,alt:`App logo`})),t.nav({pbEvent:`mainNav`,className:`app-main-nav`},()=>app.store.headerLinks.map(e=>{let n=e.href.startsWith(`#/`);return t.a({href:()=>e.href,target:()=>n?void 0:`_blank`,rel:()=>n?void 0:`noopener noreferrer`,className:n=>`header-link ${e.isActive?.(n)||app.utils.isActivePath(e.href)?`active`:``}`},()=>{if(e.icon)return t.i({className:e.icon,ariaHidden:!0})},t.span({className:`txt`},()=>e.label))})),t.div({className:`flex-fill app-header-separator`}),Ie(),t.button({type:`button`,className:`header-link logged-user txt-normal`,"html-popovertarget":`logged-user-dropdown`},t.span({className:`superuser-name txt-ellipsis`},()=>app.store.superuser?.email),t.i({className:`ri-arrow-drop-down-line`,ariaHidden:!0})),t.div({pbEvent:`loggedUserDropdown`,id:`logged-user-dropdown`,className:`dropdown sm nowrap logged-user-dropdown`,popover:`auto`},t.a({className:`dropdown-item dropdown-item-manage`,href:`#/collections?collection=_superusers`,onclick:e=>{e.target.closest(`.dropdown`).hidePopover()}},t.i({className:`ri-group-line`,ariaHidden:!0}),t.span({className:`txt`},`Manage superusers`)),t.hr(),t.button({type:`button`,className:`dropdown-item txt-danger dropdown-item-logout`,onclick:()=>app.pb.authStore.clear()},t.i({className:`ri-logout-circle-line`,ariaHidden:!0}),t.span({className:`txt`},`Logout`))))}}function Ie(){let e=[{value:`light`,icon:`ri-sun-line`,label:`Light`},{value:`dark`,icon:`ri-moon-line`,label:`Dark`},{value:``,icon:`ri-subtract-line`,label:`Auto`}];return[t.button({type:`button`,className:`header-link color-scheme-picker`,"html-popovertarget":`color-scheme-dropdown`,title:`Color scheme`},t.i({className:()=>app.store.activeColorScheme==`dark`?`ri-moon-line`:`ri-sun-line`,ariaHidden:!0})),t.div({pbEvent:`colorSchemeDropdown`,id:`color-scheme-dropdown`,className:`dropdown sm nowrap color-scheme-dropdown`,popover:`auto`},()=>e.map(e=>t.button({type:`button`,className:()=>`dropdown-item dropdown-item-light ${app.store.userColorScheme==e.value?`active`:``}`,onclick:n=>{n.target.closest(`.dropdown`).hidePopover(),app.store.userColorScheme=e.value}},t.i({className:e.icon,ariaHidden:!0}),t.span({className:`txt`},e.label))))]}document.addEventListener(`invalid`,e=>{let n=e.target.closest(`details`);n&&!n.open&&!e.target.closest(`summary`)&&(n.open=!0,e.target.reportValidity&&e.target.reportValidity())},!0);var Le=`dropdown-item`;document.addEventListener(`toggle`,e=>{if(e.newState!=`open`||!e.target||e.target.__keyboardNavRegistered||!e.target.matches(`.dropdown`))return;e.target.__keyboardNavRegistered=!0;let n=e.target;function r(e){if(!n.isConnected){document.removeEventListener(`keydown`,r);return}let i;if(i=document.activeElement&&document.activeElement.classList.contains(Le)?document.activeElement:n.querySelector(`.dropdown-item:not([hidden]):not(.disabled)`),i){if(e.key==`ArrowUp`){e.preventDefault();let n=ze(i,-1);i==document.activeElement&&n?.classList?.contains(Le)?n?.focus():i.focus()}else if(e.key==`ArrowDown`){e.preventDefault();let n=ze(i,1);i==document.activeElement&&n?.classList?.contains(Le)?n?.focus():i.focus()}else if(e.keyCode>=65&&e.keyCode<=90||e.keyCode>=48&&e.keyCode<=57){let e=n.querySelectorAll(`input,textare,select`);e.length==1&&e[0].focus()}}}n.addEventListener(`toggle`,e=>{e.newState==`open`?(n.__dropdownSource=e.source,n.__dropdownSource?.setAttribute(`data-popover-state`,!0),Re(e.target.id,!0),document.addEventListener(`keydown`,r)):(n.__dropdownSource?.setAttribute(`data-popover-state`,!1),Re(e.target.id,!1),document.removeEventListener(`keydown`,r))})},!0);function Re(e,n=!1){e&&document.querySelectorAll(`[popovertarget='`+e+`']`)?.forEach(e=>e.setAttribute(`data-popover-state`,n))}function ze(e,n=-1){let r=n<0?e.previousElementSibling:e.nextElementSibling;return r&&(r.hidden||r.classList.contains(`disabled`)||!r.classList.contains(Le))?ze(r,n):r}var Be=5,P=t.div({ariaHidden:!0,popover:`manual`,className:`pb-tooltip`});document.body.appendChild(P);function Ve(e,n,r){P._relatedNode=e;let i=e.getBoundingClientRect();P.setAttribute(`data-style`,r||``),P.setAttribute(`data-position`,n),P.style.top=`0px`,P.style.left=`0px`;let a=P.offsetHeight,o=P.offsetWidth,s=0,c=0;n==`left`?(s=i.top+i.height/2-a/2,c=i.left-o-Be):n==`right`?(s=i.top+i.height/2-a/2,c=i.right+Be):n==`top`?(s=i.top-a-Be,c=i.left+i.width/2-o/2):n==`top-left`?(s=i.top-a-Be,c=i.left):n==`top-right`?(s=i.top-a-Be,c=i.right-o):n==`bottom-left`?(s=i.top+i.height+Be,c=i.left):n==`bottom-right`?(s=i.top+i.height+Be,c=i.right-o):(s=i.top+i.height+Be,c=i.left+i.width/2-o/2),c+o>document.documentElement.clientWidth&&(c=document.documentElement.clientWidth-o),c=c>=0?c:0,s+a>document.documentElement.clientHeight&&(s=document.documentElement.clientHeight-a),s=s>=0?s:0,P.style.top=s+`px`,P.style.left=c+`px`}function He(){P._relatedNode=null,P.hidePopover()}function Ue(e,n,r,i){if(!e||!n){He();return}P.showPopover(),P.textContent=n,Ve(e,r,i)}document.body.addEventListener(`mouseleave`,()=>{He()});function We(e,n=`top`,r=``){return i=>{if(!i._tooltipText){i._tooltipText=store({value:``});let e;function a(){e?.unwatch(),e=watch(()=>i._tooltipText.value,async e=>{Ue(i,e,n,r)})}async function o(){e?.unwatch(),e=null,He()}i.addEventListener(`mouseenter`,a),i.addEventListener(`focusin`,a),i.addEventListener(`mouseleave`,o),i.addEventListener(`focusout`,o),i.addEventListener(`blur`,o);let s=i.onunmount;i.onunmount=n=>{P._relatedNode==n&&He(),e?.unwatch(),n._tooltipText=null,n?.removeEventListener(`mouseenter`,a),n?.removeEventListener(`focusin`,a),n?.removeEventListener(`mouseleave`,o),n?.removeEventListener(`focusout`,o),n?.removeEventListener(`blur`,o),s(n)}}return typeof e==`function`?i._tooltipText.value=e():i._tooltipText.value=e,i._tooltipText.value}}window.app=window.app||{},window.app.attrs=window.app.attrs||{},window.app.attrs.tooltip=We,window.app=window.app||{},window.app.modals=window.app.modals||{},window.app.modals.confirm=function(e,n,r,i={className:void 0,yesButton:``,noButton:``}){F.textOrElem=e,F.yesCallback=n,F.yesCallbackWaiting=!1,F.noCallback=r,F.noCallbackWaiting=!1,F.className=typeof i.className==`string`?i.className:`sm`,F.yesButton=i.yesButton||`Yes`,F.noButton=i.noButton||`No`,Ge.isConnected||document.body.appendChild(Ge),window.app.modals.open(Ge)};var F=store({className:``,textOrElem:null,yesButton:``,yesCallback:null,yesCallbackWaiting:!1,noButton:``,noCallback:null,noCallbackWaiting:!1,get isBusy(){return F.yesCallbackWaiting||F.noCallbackWaiting}}),Ge=t.div({className:()=>`modal popup manual ${F.className||``}`},t.div({className:`modal-content`},e=>typeof F.textOrElem==`string`?t.h6({className:`block txt-center`},F.textOrElem):typeof F.textOrElem==`function`?F.textOrElem(e):F.textOrElem),t.footer({className:`modal-footer p-sm`},t.div({className:`grid sm`},t.div({className:`col-sm-6`},t.button({type:`button`,className:()=>`btn lg block secondary ${F.noCallbackWaiting?`loading`:``}`,disabled:()=>F.isBusy,onclick:async()=>{if(F.noCallback){F.noCallbackWaiting=!0;try{if(await F.noCallback()===!1)return}catch(e){console.log(`confirm noCallback error:`,e)}finally{F.noCallbackWaiting=!1}}window.app.modals.close(Ge)}},()=>typeof F.noButton==`string`?t.span({className:`txt`},F.noButton):typeof F.noButton==`function`?F.noButton(el):F.noButton)),t.div({className:`col-sm-6`},t.button({type:`button`,className:()=>`btn lg block warning ${F.yesCallbackWaiting?`loading`:``}`,disabled:()=>F.isBusy,onclick:async()=>{if(F.yesCallback){F.yesCallbackWaiting=!0;try{if(await F.yesCallback()===!1)return}catch(e){console.log(`confirm yesCallback error:`,e)}finally{F.yesCallbackWaiting=!1}}window.app.modals.close(Ge)}},()=>typeof F.yesButton==`string`?t.span({className:`txt`},F.yesButton):typeof F.yesButton==`function`?F.yesButton(el):F.yesButton)))));window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.dragline=function(e={}){let n,r=store({rid:void 0,id:void 0,hidden:void 0,inert:void 0,className:``,tolerance:0,ondragstart:function(e){},ondragstop:function(e){},ondragging:function(e,n,r){}}),i=app.utils.extendStore(r,e),a=store({dragStarted:!1}),o,s,c,l;function u(){document.addEventListener(`touchmove`,m),document.addEventListener(`mousemove`,m),document.addEventListener(`touchend`,p),document.addEventListener(`mouseup`,p)}function d(){document.removeEventListener(`touchmove`,m),document.removeEventListener(`mousemove`,m),document.removeEventListener(`touchend`,p),document.removeEventListener(`mouseup`,p)}function f(e){e.stopPropagation(),o=e.clientX,s=e.clientY,c=e.clientX-n.offsetLeft,l=e.clientY-n.offsetTop,u()}function p(e){a.dragStarted&&(e.preventDefault(),a.dragStarted=!1,r.ondragstop?.(e)),d()}function m(e){let i=e.clientX-o,u=e.clientY-s,d=e.clientX-c,f=e.clientY-l;!a.dragStarted&&Math.abs(d-n.offsetLeft)r.id,hidden:()=>r.hidden,inert:()=>r.inert,className:()=>`dragline ${a.dragStarted?`dragging`:``} ${r.className}`,onmousedown:e=>{e.button==0&&f(e)},ontouchstart:f,onunmount:()=>{d(),i.forEach(e=>e?.unwatch())}}),n},window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.slide=function(e,...n){let r;return t.div({className:n=>`block slide-block ${e?.(n)?``:`hidden`}`,onmount:e=>{r=setTimeout(()=>{e?.setAttribute(`data-slide`,`1`)},200)},onunmount:()=>{clearTimeout(r)}},...n)},window.app=window.app||{},window.app.modals=window.app.modals||{};var Ke=`data-modal-state`,qe=`manual`,Je;window.app.modals.open=async function(e){if(!e?.isConnected){console.error(`modals.open requies an active DOM element`,e);return}let n;if(e.onbeforeopen&&(n=await e.onbeforeopen(e)),n===!1)return;if(e.onafteropen){let n=new ResizeObserver(r=>{for(let i of r)i.contentRect.height>0&&e?.onafteropen&&(e.onafteropen(e),n.disconnect(),n=null)});n.observe(e)}Je=document.activeElement,Ye(e),e._forceClose=()=>app.modals.close(e,!0),window.addEventListener(`popstate`,e._forceClose);let r=Math.max(Xe(e)?.style.zIndex<<0,1e3);e.style.zIndex=r+1,e.setAttribute(Ke,`open`)},window.app.modals.close=async function(e=null,n=!1){if(e||=Xe(),e){if(window.removeEventListener(`popstate`,e._forceClose),n)e.onbeforeclose?.(e,!0),e.setAttribute(Ke,`close`),e.onafterclose?.(e,!0);else{if(e.onbeforeclose&&await e.onbeforeclose(e,!1)===!1)return;if(e.onafterclose){let n=new ResizeObserver(r=>{for(let i of r)i.contentRect.height<=0&&e?.onafterclose&&(e.onafterclose(e,!1),n.disconnect(),n=null)});n.observe(e)}e.setAttribute(Ke,`close`)}Je&&(Je.focus?.(),setTimeout(()=>{Je?.blur?.(),Je=null},0))}};function Ye(e){if(e.getAttribute(`tabindex`)||e.setAttribute(`tabindex`,`-1`),setTimeout(()=>{let n=e?.querySelector(`[autofocus]`);n?n.focus():e?.focus()},0),e.getAttribute(Ke))return;e.setAttribute(Ke,``),e.addEventListener(`keydown`,n=>{n.key!=`Escape`||e.classList.contains(qe)||n.target!==e&&e.contains(n.target)||window.app.modals.close(e)});let n=!1,r=r=>{n=r.target!==e&&e.contains(r.target)};e.addEventListener(`mousedown`,r),e.addEventListener(`touchstart`,r);let i=!1,a=n=>{i=n.target!==e&&e.contains(n.target)};e.addEventListener(`mouseup`,a),e.addEventListener(`touchend`,a),e.addEventListener(`click`,r=>{n||i||e.classList.contains(qe)||r.target!==e&&e.contains(r.target)||window.app.modals.close(e)})}function Xe(e){let n=document.querySelectorAll(`[${Ke}="open"]`),r=0,i=0,a;for(let o of n)e&&o==e||(r=o.style.zIndex<<0,r>i&&(i=r,a=o));return a}window.app.modals.getTop=function(){return Xe()};var Ze=new Map,Qe=t.div({className:`toasts-container`});function I(e,n=!0){let r=Ze.get(e);!r||!r.isConnected||(Ze.delete(e),clearTimeout(r._removeTimeout),n?(r.classList.add(`removing`),setTimeout(()=>{r.remove()},300)):r.remove())}function R(e=!0){Ze.forEach((n,r)=>{window.app.toasts.remove(r,e)})}function $e(e,n={}){n.type=`info`,n.duration=n.duration||3e3,nt(e,n)}function et(e,n={}){n.type=`success`,n.duration=n.duration||3e3,nt(e,n)}function tt(e,n={}){n.type=`error`,n.duration=n.duration||3500,nt(e,n)}function nt(e,n={}){n=Object.assign({duration:3e3,key:void 0,type:`info`},n),Qe.isConnected||document.body.appendChild(Qe);let r=n.key||e;Ze.has(r)&&I(r,!1);function i(e){e?._removeTimeout&&clearTimeout(e?._removeTimeout),e._removeTimeout=setTimeout(()=>{I(r)},n.duration)}let a=t.div({className:`toast ${n.type||``}`,onmount:e=>{i(e)},onunmount:e=>{e?._removeTimeout&&(clearTimeout(e?._removeTimeout),a=null)},onmouseover:()=>{clearTimeout(a?._removeTimeout)},onmouseout:()=>{i(a)}},t.div({className:`toast-container`},t.div({className:`toast-icon`}),t.div({className:`toast-content`},e,t.button({type:`button`,className:`m-l-auto btn circle sm transparent secondary toast-remove`,title:`Clear`,onclick:()=>I(r)},t.i({className:`ri-close-line`,ariaHidden:!0})))));Ze.set(r,a),Qe.prepend(a)}window.app=window.app||{},window.app.toasts=window.app.toasts||{},window.app.toasts.info=$e,window.app.toasts.error=tt,window.app.toasts.success=et,window.app.toasts.remove=I,window.app.toasts.removeAll=R,window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.sortable=function(e={}){let n=store({rid:void 0,id:void 0,hidden:void 0,inert:void 0,className:``,data:[],dataItem:function(e,n,r){return t.span(null,`Item `+n)},onchange:function(e,n,r){},handle:``,before:void 0,after:void 0}),r=app.utils.extendStore(n,e);function i(e){function r(){e.querySelectorAll(`:scope > [data-dragstart="true"]`)?.forEach(e=>{e.dataset.dragstart=!1}),e.querySelectorAll(`:scope > [data-dragover="true"]`)?.forEach(e=>{e.dataset.dragover=!1})}e.addEventListener(`dragstart`,r=>{if(n.handle&&!r.target.closest(n.handle)){r.preventDefault();return}let i=o(e,r.target);i&&(i.dataset.dragstart=!0)}),e.addEventListener(`dragenter`,n=>{for(let n of e.children)n.dataset.dragover&&(n.dataset.dragover=!1);let r=o(e,n.target);r&&(r.dataset.dragover=!0)}),e.addEventListener(`dragover`,e=>{e.preventDefault()}),e.addEventListener(`drop`,i=>{if(!n.onchange){r();return}let s=e.querySelector(`:scope > [data-dragstart="true"]`),c=o(e,i.target);if(r(),!s||!c||c==s)return;let l=e.querySelectorAll(`:scope > [data-sortable-child]`),u=a(l,s),d=a(l,c);if(u==-1||d==-1)return;let f=n.data.slice(),p=f.splice(u,1);f.splice(d,0,p[0]),n.onchange(f,u,d)}),e._documentDragend=function(){r()},document.addEventListener(`dragend`,e._documentDragend)}function a(e,n){for(let r=0;rn.id,hidden:()=>n.hidden,inert:()=>n.inert,className:()=>n.className,onmount:e=>{i(e)},onunmount:e=>{r.forEach(e=>e?.unwatch()),e._documentDragend&&document.removeEventListener(`dragend`,e._documentDragend)}},e=>typeof n.before==`function`?n.before(e):n.before,e=>{let r=[];for(let i=0;itypeof n.after==`function`?n.after(e):n.after)},window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.copyButton=function(e,...n){let r=store({active:!1}),i;function a(){let n=e;typeof n==`function`&&(n=e()),app.utils.copyToClipboard(n),r.active=!0,clearTimeout(i),i=setTimeout(()=>{r.active=!1},500)}return t.button({tabIndex:-1,type:`button`,className:()=>`copy-to-clipboard ${r.active?`active`:``}`,title:`Copy`,ariaDescription:app.attrs.tooltip(()=>r.active?`Copied`:null),onclick:e=>{e.preventDefault(),e.stopPropagation(),a()}},t.i({hidden:n?.length,ariaHidden:!0,className:()=>`copy-icon ${r.active?`ri-check-double-line`:`ri-file-copy-line`}`}),...n)},window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.codeBlock=function(e={}){let n=store({rid:void 0,id:void 0,hidden:void 0,inert:void 0,className:``,language:`js`,value:void 0,footnote:void 0}),r=app.utils.extendStore(n,e);return t.div({rid:n.rid,id:()=>n.id,hidden:()=>n.hidden,inert:()=>n.inert,className:()=>`code-wrapper ${n.className}`,tabIndex:-1,onmount:e=>{e.addEventListener(`keydown`,n=>{(n.ctrlKey||n.metaKey)&&(n.key==`a`||n.key==`A`)&&(n.preventDefault(),window.getSelection().selectAllChildren(e))})},onunmount:()=>{r.forEach(e=>e?.unwatch())}},t.code({className:`block`,innerHTML:()=>rt(n.value,n.language)}),t.div({className:`footnote`},e=>typeof n.footnote==`function`?n.footnote(e):n.footnote))};function rt(e,n){return e=typeof e==`string`?e:``,e=Prism.plugins.NormalizeWhitespace.normalize(e,{"remove-trailing":!0,"remove-indent":!0,"left-trim":!0,"right-trim":!0}),Prism.highlight(e,Prism.languages[n]||Prism.languages.js,n)}window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.codeEditor=function(e={}){let n=store({rid:void 0,id:void 0,hidden:void 0,inert:void 0,name:void 0,className:``,value:``,language:`js`,placeholder:``,disabled:!1,required:!1,singleLine:!1,autocomplete:void 0,oninput:function(e){},onfocus:function(e){},onblur:function(e){}}),r=app.utils.extendStore(n,e,`autocomplete`),i,a,o=!0;function s(e){c(),i=t.div({className:`dropdown autocomplete code-editor-dropdown`,onmount:e=>{e._updatePosition=()=>{o?dt(i):c()},e._closeOnEsc=e=>{e.key==`Escape`&&(e.preventDefault(),c())},window.addEventListener(`scroll`,e._updatePosition,!0),window.addEventListener(`resize`,e._updatePosition),window.addEventListener(`keydown`,e._closeOnEsc),e._updatePosition()},onunmount:e=>{e&&(window.removeEventListener(`scroll`,e._updatePosition,!0),window.removeEventListener(`resize`,e._updatePosition),window.removeEventListener(`keydown`,e._closeOnEsc))}},e),document.body.appendChild(i),p&&(a?.disconnect(),a=new IntersectionObserver(([e])=>{o=e.isIntersecting},{root:null,threshold:.1}),a.observe(p))}function c(){clearTimeout(f),i&&=(i.remove(),null),a&&=(a.disconnect(),null),o=!0}function l(e){n.value=e,n.oninput?.(e),p.dispatchEvent(new CustomEvent(`change`,{detail:e}))}let u=!1,d,f,p=t.div({contentEditable:()=>!n.disabled&&`plaintext-only`,tabIndex:0,spellcheck:!1,autocorrect:!1,autocomplete:`off`,autocapitalize:`off`,role:`textbox`,className:`editor-content`,"html-data-placeholder":()=>n.placeholder,onmount:e=>{d?.unwatch(),d=watch(()=>n.value,e=>{e!=p.textContent&&(p.textContent=e,c())})},onunmount:e=>{d?.unwatch(),c()},onfocus:()=>{n.onfocus?.(n.value)},onblur:e=>{i&&!i.contains(e.relatedTarget)&&c(),n.onblur?.(n.value)},oninput:e=>{if(clearTimeout(f),l(p.textContent),!n.value?.length){p.textContent=``,c();return}f=setTimeout(()=>{if(c(),!p?.isConnected)return;let e=ut(p),r=st(n.value,e);if(!r.word.length||e==r.start)return;let i=[];if(typeof n.autocomplete==`function`)i=n.autocomplete(r.prefix||r.word)||[];else if(!app.utils.isEmpty(n.autocomplete)){let e=(r.prefix||r.word).toLowerCase();i=n.autocomplete.filter(n=>(typeof n==`object`&&(n=n?.value),n=n?.toLowerCase(),n&&n!=e&&n.includes(e)))}!i?.length||i.length==1&&(i[0].value||i[0])==r.word||s(()=>i.map((e,n)=>t.button({type:`button`,className:`dropdown-item ${n==0?`active`:``}`,textContent:e.label||e.value||e,onclick:n=>{n.preventDefault(),p.focus();let i=e.value||e;p.textContent=p.textContent.substring(0,r.start)+i+p.textContent.substring(r.end+1),l(p.textContent);try{window.getSelection().setPosition(p.childNodes[0],r.start+i.length)}catch(e){console.warn(`failed to set caret position`,e)}c()}})))},50)},onkeydown:e=>{if(u=e.ctrlKey||e.metaKey,(e.key==`Enter`||e.key==`Tab`)&&i?.isConnected){e.preventDefault(),i.querySelector(`.dropdown-item.active`)?.click();return}if(e.key==`ArrowUp`&&i?.isConnected){e.preventDefault();let n=i.querySelector(`.dropdown-item.active`);n?.previousElementSibling&&(n.classList.remove(`active`),n.previousElementSibling.classList.add(`active`),n.previousElementSibling.scrollIntoView(!1));return}if(e.key==`ArrowDown`&&i?.isConnected){e.preventDefault();let n=i.querySelector(`.dropdown-item.active`);n?.nextElementSibling&&(n.classList.remove(`active`),n.nextElementSibling.classList.add(`active`),n.nextElementSibling.scrollIntoView(!1));return}if(u&&e.key.toLowerCase()==`l`){e.preventDefault(),ct(p);return}if(u&&e.key.toLowerCase()==`d`){e.preventDefault(),lt(p);return}if(!n.singleLine&&e.key==`Escape`&&!i?.isConnected){p?.blur();return}if(!n.singleLine&&e.key==`Tab`){e.preventDefault();let n=window.getSelection();if(!n)return;if(e.shiftKey){n.modify(`extend`,`backward`,`character`),n.toString()[0]==` `?(n.deleteFromDocument(),l(p.textContent)):(n.modify(`extend`,`forward`,`character`),n.toString()[0]==` `&&(n.deleteFromDocument(),l(p.textContent)));return}let r=n.getRangeAt(0);r&&(r.deleteContents(),r.insertNode(document.createTextNode(` `)),r.collapse(),l(p.textContent));return}if(n.singleLine&&e.key==`Enter`){e.preventDefault(),h.click();return}},onscroll:()=>{c(),m&&(m.scrollLeft=p.scrollLeft,m.scrollTop=p.scrollTop)}}),m=t.div({className:`highlight-overlay`,innerHTML:()=>at(n.value,n.language),onscroll:()=>{p&&(p.scrollLeft=m.scrollLeft,p.scrollTop=m.scrollTop)}}),h=t.button({type:`submit`,className:`hidden`});return t.div({rid:n.rid,id:()=>n.id,inert:()=>n.inert,hidden:()=>n.hidden,"html-name":()=>n.name,"html-required":()=>n.required||void 0,className:()=>`input code-editor ${n.className} ${n.disabled?`disabled`:``} ${n.singleLine?`single-line`:``}`,onclick:()=>{p?.focus()},onunmount:()=>{r?.forEach(e=>e?.unwatch())}},t.div({className:`code-editor-container`},p,m,h))};var it=800;function at(e,n){return e=typeof e==`string`?e:``,e?((!Prism.languages[n]||e.length>it)&&(n=`plain`),Prism.highlight(e,Prism.languages[n],n)):``}var ot=new RegExp(/[\p{Alphabetic}\p{Number}_@:\."'{}]/,`u`);function st(e,n){let r=n;for(let i=n-1;i>=0&&ot.test(e[i]);i--)r=i;let i=r;for(let r=n-1;rdocument.documentElement.clientHeight&&(o=Math.max(n.top-r,0)),a+i>document.documentElement.clientWidth&&(a=Math.max(document.documentElement.clientWidth-i,0)),e.style.left=a+`px`,e.style.top=o+`px`}window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.codeBlockTabs=function(e={}){let n=store({rid:void 0,id:void 0,hidden:void 0,inert:void 0,className:``,activeTabIndex:0,historyKey:``,tabs:[],get activeTab(){return n.tabs[n.activeTabIndex]||n.tabs[0]}}),r=app.utils.extendStore(n,e);return r.push(watch(()=>n.activeTabIndex,(e,r)=>{r!=null&&n.historyKey&&localStorage.setItem(n.historyKey,e)})),t.div({rid:n.rid,id:()=>n.id,hidden:()=>n.hidden||!n.tabs.length,inert:()=>n.inert,className:()=>`code-block-tabs ${n.className}`,onmount:()=>{n.historyKey&&(n.activeTabIndex=localStorage.getItem(n.historyKey)<<0)},onunmount:()=>{r.forEach(e=>e?.unwatch())}},t.header({className:`tabs-header`},()=>n.tabs.map((e,r)=>t.button({type:`button`,className:()=>`tab-item ${n.activeTabIndex==r?`active`:``}`,onclick:()=>n.activeTabIndex=r},n=>typeof e.title==`function`?e.title(n):e.title))),t.div({className:`code-block-tabs-content`},()=>{if(n.activeTab)return app.components.codeBlock(n.activeTab)}))},window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.select=function(e={}){let n=store({rid:void 0,id:void 0,name:void 0,hidden:void 0,inert:void 0,className:``,value:void 0,options:[],before:null,after:null,max:1,searchThreshold:6,required:!1,disabled:!1,placeholder:`- Select -`,noItemsFoundText:`No items found`,onchange:function(e){},ondropdowntoggle:function(e){}}),r=app.utils.extendStore(n,e);n.max<=0&&(n.max=1);let i=store({selected:[],search:``,get hasSearch(){return i.search?.length>0},get allowRemove(){return!n.disabled&&(!n.required||n.max>1)}});function a(){if(n.value===void 0)return;let e=app.utils.toArray(n.value,!0),r=e.slice(0,n.max||1);e.length!=r.length&&(console.warn(`[select] the provided select values (${e.length}) are more than the allowed max selected options (${r.length}):`,e),n.value=n.max>1?r:r[0]),i.selected=e.map(e=>n.options.find(n=>n.value===e)).filter(Boolean)}r.push(watch(()=>n.value,()=>a()));async function o(e){let r=i.selected.findIndex(n=>n.value===e.value);if(r>=0){if(!i.allowRemove){f?.hidePopover();return}i.selected.splice(r,1)}else{let r=i.selected.length-n.max;for(;r>=0;)i.selected.pop(),r--;i.selected.push(e)}n.max<=1&&f?.hidePopover(),n.onchange&&(await n.onchange(i.selected),a()),p?.isConnected&&p.dispatchEvent(new CustomEvent(`change`,{detail:i.selected,bubbles:!0}))}function s(e){return i.selected.findIndex(n=>n.value===e.value)>=0}let c=t.input({type:`text`,placeholder:`Search...`,value:()=>i.search,oninput:e=>i.search=e.target.value});function l(e=!1){i.search=``,e&&c?.focus()}let u=t.div({className:`txt-hint txt-center m-0 p-5`,hidden:!0},e=>typeof n.noItemsFoundText==`function`?n.noItemsFoundText(e):n.noItemsFoundText);async function d(){f&&(await new Promise(e=>setTimeout(e,0)),f.querySelector(`.select-option:not([hidden])`)?u.hidden=!0:u.hidden=!1)}let f=t.div({tabIndex:-1,popover:`auto`,className:`dropdown`,onbeforetoggle:e=>(e.newState==`closed`&&l(),n.ondropdowntoggle?.(e))},t.div({className:`fields dropdown-search`,hidden:()=>n.options.length!i.hasSearch},t.button({type:`button`,title:`Clear`,className:`btn sm secondary transparent circle`,onclick:()=>l(!0)},t.i({className:`ri-close-line`,ariaHidden:!0})))),()=>n.before?.__raw||n.before,()=>n.options.map(e=>t.button({type:`button`,className:()=>`dropdown-item select-option ${s(e)?`active`:``}`,onclick:()=>(o(e),!1)},e.label||e.value)),u,()=>n.after?.__raw||n.after),p=t.button({type:`button`,id:()=>n.id,disabled:()=>n.disabled,className:`selected-container`,popoverTargetElement:f,onclick:e=>{e.stopPropagation()}},()=>i.selected.length?i.selected.map(e=>t.div({className:`selected-item`},e.selected||e.label||e.value,()=>{if(i.allowRemove)return t.i({tabIndex:-1,role:`button`,className:`ri-close-line link-hint btn-option-unset`,ariaLabel:app.attrs.tooltip(`Unset`),onclick:()=>(o(e),!1)})})):t.span({rid:`selected-placeholder`,className:`placeholder`},e=>typeof n.placeholder==`function`?n.placeholder(e):n.placeholder));r.push(watch(()=>n.options,()=>{d()}));let m;return r.push(watch(()=>i.search,()=>{let e=i.search.toLowerCase().replaceAll(` `,``);clearTimeout(m),m=setTimeout(()=>{let n=f.querySelectorAll(`.select-option`);e.length?n.forEach(n=>{n.hidden=!n.textContent.toLowerCase().replaceAll(` `,``).includes(e)}):n.forEach(e=>e.hidden=!1),d()},100)})),t.output({rid:n.rid,name:()=>n.name,hidden:()=>n.hidden,inert:()=>n.inert,onmount:e=>{e.addEventListener(`focusout`,function(n){(!n.relatedTarget||!e.contains(n.relatedTarget))&&f?.hidePopover()})},onunmount:()=>{clearTimeout(m),r.forEach(e=>e.unwatch())},className:()=>[`input`,`select`,n.max>1?`multiple`:`single`,n.disabled?`disabled`:null,n.required?`required`:null,n.className||null].filter(Boolean).join(` `)},p,f)},window.app=window.app||{},window.app.components=window.app.components||{};var ft=Intl.DateTimeFormat().resolvedOptions().timeZone;window.app.components.formattedDate=function(e={}){let n=store({rid:void 0,id:void 0,hidden:void 0,value:``,short:!1}),r=app.utils.extendStore(n,e);return t.div({rid:n.rid,id:()=>n.id,hidden:()=>n.hidden,ariaDescription:app.attrs.tooltip(()=>n.short&&n.value?app.utils.toLocalDatetime(n.value)+` `+ft:null),"html-class":`formatted-date`,className:()=>`formatted-date ${n.short?`short`:`full`}`,onunmount:()=>{r.forEach(e=>e?.unwatch())}},()=>{if(!n.value)return t.span({className:`missing-value`});if(n.short){let e=n.value.split(` `);return[t.span({className:`primary-date`},e[0]),t.span({className:`secondary-date`},e[1])]}return[t.span({className:`primary-date`},app.utils.toLocalDatetime(n.value)),t.span({className:`secondary-date`},n.value)]})},window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.refreshButton=function(e={}){let n=store({rid:void 0,id:void 0,hidden:void 0,inert:void 0,tooltip:`Refresh`,className:`btn transparent secondary circle rotate-btn`,disabled:!1,onclick:function(e){}}),r=app.utils.extendStore(n,e),i,a=t.button({rid:n.rid,id:()=>n.id,hidden:()=>n.hidden,inert:()=>n.inert,type:`button`,ariaLabel:app.attrs.tooltip(()=>n.tooltip),disabled:()=>n.disabled,className:()=>n.className,onunmount:()=>{clearTimeout(i),r.forEach(e=>e?.unwatch())},onclick:e=>{e.preventDefault(),n.onclick&&n.onclick(e),a.dataset.rotate=!0,a.addEventListener(`animationend`,()=>{a.dataset.rotate=!1}),clearTimeout(i),i=setTimeout(()=>{clearTimeout(i),a.dataset.rotate=!1},500)}},t.i({className:`ri-refresh-line`,ariaHidden:!0}));return a},window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.searchHistoryButton=function(e={}){let n=store({rid:void 0,id:void 0,hidden:void 0,inert:void 0,value:void 0,historyKey:`default`,max:15,openInNewTabParam:`filter`,btnClassName:`btn sm pill secondary transparent p-r-5`,onselect:function(e){}}),r=app.utils.extendStore(n,e),i=store({items:app.utils.getLocalHistory(n.historyKey,[])});function a(e){o(e),i.items.unshift(e)}function o(e){app.utils.removeByValue(i.items,e)}let s=`history_dropdown_`+app.utils.randomString();r.push(watch(()=>n.value,e=>{e&&a(e)})),r.push(watch(()=>{i.items.length>n.max&&(i.items=i.items.slice(0,n.max)),app.utils.saveLocalHistory(n.historyKey,i.items)}));let c=t.div({id:s,className:`dropdown sm left nowrap history-searchbar-dropdown`,popover:`hint`,onclick:e=>(e.stopPropagation(),!1)},t.div({className:`block p-5`},t.small({className:`txt-hint`},`Search history`)),()=>i.items?.length?i.items.slice(0,n.max).map(e=>t.button({type:`button`,className:`dropdown-item txt-code`,onclick:()=>{c.hidePopover(),n.onselect?.(e),a(e)},onauxclick:()=>{if(n.openInNewTabParam){a(e),c.hidePopover();let r=app.utils.replaceHashQueryParams({[n.openInNewTabParam]:e},!1);window.open(r,`_blank`)}}},t.span({className:`txt-ellipsis`,title:e,textContent:e}),t.small({role:`button`,className:`remove-btn link-hint m-l-auto p-l-5 p-r-5`,title:`Clear`,onauxclick:e=>(e.stopPropagation(),!1),onclick:n=>(n.stopPropagation(),o(e),!1)},t.i({className:`ri-close-line`,ariaHidden:!0})))):t.div({rid:`no-history`,className:`block p-5`},t.span(null,`Your recent searches will show up here.`)));return t.button({rid:n.rid,id:()=>n.id,hidden:()=>n.hidden,inert:()=>n.inert,type:`button`,title:`Search history`,className:()=>n.btnClassName,"html-popovertarget":s,onunmount:()=>{r?.forEach(e=>e?.unwatch())}},t.i({className:`ri-search-line`,ariaHidden:!0}),t.i({className:`ri-arrow-drop-down-line`,ariaHidden:!0}),c)},window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.s3Test=function(e={}){let n=`s3_test_request`,r=store({rid:void 0,config:null,label:`Use S3 storage`,testFilesystem:`storage`}),i=app.utils.extendStore(r,e),a=store({isTesting:!1,testError:null,get hasError(){return!app.utils.isEmpty(a.testError)}}),o,s;function c(e=150){if(!r.config.enabled){clearTimeout(o);return}a.isTesting=!0,clearTimeout(o),o=setTimeout(()=>{l()},e)}async function l(){if(a.isTesting=!0,!r.config.enabled||!r.testFilesystem){a.testError=null,a.isTesting=!1;return}app.pb.cancelRequest(n),clearTimeout(s),s=setTimeout(()=>{app.pb.cancelRequest(n),a.testError=Error(`S3 test connection timeout.`),a.isTesting=!1},3e4);try{await app.pb.props.testS3(r.testFilesystem,{requestKey:n}),a.testError=null,a.isTesting=!1}catch(e){e?.isAbort||(a.testError=e,a.isTesting=!1,clearTimeout(s))}}return i.push(watch(()=>r.testFilesystem&&r.config,()=>c())),t.div({pbEvent:`s3Test`,rid:r.rid,hidden:()=>!r.testFilesystem,className:()=>`label s3-test-label txt-nowrap ${a.hasError?`warning`:`success`}`,ariaDescription:app.attrs.tooltip(()=>a.testError?.data?.message),onunmount:()=>{clearTimeout(s),clearTimeout(o),i.forEach(e=>e?.unwatch())}},()=>a.isTesting?t.span({className:`loader sm`}):a.hasError?[t.i({className:`ri-error-warning-line txt-warning`,ariaHidden:!0}),t.span({className:`txt`},`Failed to establish S3 connection`)]:[t.i({className:`ri-checkbox-circle-line txt-success`,ariaHidden:!0}),t.span({className:`txt`},`S3 connected successfully`)])},window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.s3ConfigFields=function(e={}){let n=store({rid:void 0,id:void 0,hidden:void 0,inert:void 0,className:``,config:{},configKey:`s3`,toggleLabel:`Use S3 storage`,testFilesystem:`storage`,before:null,after:null}),r=app.utils.extendStore(n,e);n.configKey.endsWith(`.`)&&(n.configKey=n.configKey.substring(0,n.configKey.length-1));let i=store({originalHash:``,originalConfig:null});return r.push(watch(()=>n.config,e=>{i.originalHash=JSON.stringify(e),i.originalConfig=JSON.parse(i.originalHash)})),t.div({pbEvent:`s3ConfigFields`,rid:n.rid,id:()=>n.id,hidden:()=>n.hidden,inert:()=>n.inert,className:()=>`block s3-fields s3-config-${n.configKey} ${n.className}`,onunmount:()=>{r.forEach(e=>e?.unwatch())}},t.div({className:`field`},t.input({id:()=>`${n.configKey}.enabled`,name:()=>`${n.configKey}.enabled`,type:`checkbox`,className:`switch`,checked:()=>n.config.enabled,onchange:e=>n.config.enabled=e.target.checked}),t.label({htmlFor:()=>`${n.configKey}.enabled`},()=>n.toggleLabel)),e=>typeof n.before==`function`?n.before(e):n.before,app.components.slide(()=>n.config.enabled,t.div({className:`grid m-t-base`},t.div({className:`col-lg-6`},t.div({className:`field`},t.label({htmlFor:()=>`${n.configKey}.endpoint`},`Endpoint`),t.input({id:()=>`${n.configKey}.endpoint`,name:()=>`${n.configKey}.endpoint`,type:`text`,required:()=>n.config.enabled,value:()=>n.config.endpoint||``,oninput:e=>n.config.endpoint=e.target.value}))),t.div({className:`col-lg-3`},t.div({className:`field`},t.label({htmlFor:()=>`${n.configKey}.bucket`},`Bucket`),t.input({id:()=>`${n.configKey}.bucket`,name:()=>`${n.configKey}.bucket`,type:`text`,required:()=>n.config.enabled,value:()=>n.config.bucket||``,oninput:e=>n.config.bucket=e.target.value}))),t.div({className:`col-lg-3`},t.div({className:`field`},t.label({htmlFor:()=>`${n.configKey}.region`},`Region`),t.input({id:()=>`${n.configKey}.region`,name:()=>`${n.configKey}.region`,type:`text`,required:()=>n.config.enabled,value:()=>n.config.region||``,oninput:e=>n.config.region=e.target.value}))),t.div({className:`col-lg-6`},t.div({className:`field`},t.label({htmlFor:()=>`${n.configKey}.accessKey`},`Access key`),t.input({id:()=>`${n.configKey}.accessKey`,name:()=>`${n.configKey}.accessKey`,type:`text`,autocomplete:`off`,required:()=>n.config.enabled,value:()=>n.config.accessKey||``,oninput:e=>n.config.accessKey=e.target.value}))),t.div({className:`col-lg-6`},t.div({className:()=>`field ${n.config.enabled?``:`required`}`},t.label({htmlFor:()=>`${n.configKey}.secret`},`Secret`),t.input({id:()=>`${n.configKey}.secret`,name:()=>`${n.configKey}.secret`,type:`password`,autocomplete:`new-password`,value:()=>n.config.secret||``,oninput:e=>n.config.secret=e.target.value,onkeyup:e=>{e.key==`Backspace`&&n.config.secret===void 0&&(n.config.secret=``)},placeholder:()=>n.config.secret===void 0?`* * * * * *`:``}))),t.div({className:`col-lg-6`,style:`min-height: 25px`},t.div({className:`field`},t.input({id:()=>`${n.configKey}.forcePathStyle`,name:()=>`${n.configKey}.forcePathStyle`,type:`checkbox`,checked:()=>n.config.forcePathStyle||!1,onchange:e=>n.config.forcePathStyle=e.target.checked}),t.label({htmlFor:()=>`${n.configKey}.forcePathStyle`},t.span({className:`txt`},`Force path-style addressing`),t.i({className:`ri-information-line link-hint`,ariaDescription:app.attrs.tooltip(`Forces the request to use path-style addressing, eg. "https://s3.amazonaws.com/BUCKET/KEY" instead of the default "https://BUCKET.s3.amazonaws.com/KEY".`)})))),t.div({className:`col-lg-6 txt-right`},()=>{if(!(!n.config?.enabled||i.originalHash!=JSON.stringify(n.config)))return app.components.s3Test({config:()=>n.config,testFilesystem:()=>n.testFilesystem})}))),e=>typeof n.after==`function`?n.after(e):n.after)};var pt=l(s(((e,n)=>{(function(r,i){typeof e==`object`&&n!==void 0?i(e):typeof define==`function`&&define.amd?define([`exports`],i):(r=typeof globalThis<`u`?globalThis:r||self,i(r.leaflet={}))})(e,(function(e){var n=`1.9.4`;function r(e){var n,r,i,a;for(r=1,i=arguments.length;r`u`||!L||!L.Mixin)){e=v(e)?e:[e];for(var n=0;n0?Math.floor(e):Math.ceil(e)};w.prototype={clone:function(){return new w(this.x,this.y)},add:function(e){return this.clone()._add(E(e))},_add:function(e){return this.x+=e.x,this.y+=e.y,this},subtract:function(e){return this.clone()._subtract(E(e))},_subtract:function(e){return this.x-=e.x,this.y-=e.y,this},divideBy:function(e){return this.clone()._divideBy(e)},_divideBy:function(e){return this.x/=e,this.y/=e,this},multiplyBy:function(e){return this.clone()._multiplyBy(e)},_multiplyBy:function(e){return this.x*=e,this.y*=e,this},scaleBy:function(e){return new w(this.x*e.x,this.y*e.y)},unscaleBy:function(e){return new w(this.x/e.x,this.y/e.y)},round:function(){return this.clone()._round()},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},floor:function(){return this.clone()._floor()},_floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},ceil:function(){return this.clone()._ceil()},_ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this},trunc:function(){return this.clone()._trunc()},_trunc:function(){return this.x=T(this.x),this.y=T(this.y),this},distanceTo:function(e){e=E(e);var n=e.x-this.x,r=e.y-this.y;return Math.sqrt(n*n+r*r)},equals:function(e){return e=E(e),e.x===this.x&&e.y===this.y},contains:function(e){return e=E(e),Math.abs(e.x)<=Math.abs(this.x)&&Math.abs(e.y)<=Math.abs(this.y)},toString:function(){return`Point(`+d(this.x)+`, `+d(this.y)+`)`}};function E(e,n,r){return e instanceof w?e:v(e)?new w(e[0],e[1]):e==null?e:typeof e==`object`&&`x`in e&&`y`in e?new w(e.x,e.y):new w(e,n,r)}function D(e,n){if(e)for(var r=n?[e,n]:e,i=0,a=r.length;i=this.min.x&&r.x<=this.max.x&&n.y>=this.min.y&&r.y<=this.max.y},intersects:function(e){e=O(e);var n=this.min,r=this.max,i=e.min,a=e.max,o=a.x>=n.x&&i.x<=r.x,s=a.y>=n.y&&i.y<=r.y;return o&&s},overlaps:function(e){e=O(e);var n=this.min,r=this.max,i=e.min,a=e.max,o=a.x>n.x&&i.xn.y&&i.y=n.lat&&a.lat<=r.lat&&i.lng>=n.lng&&a.lng<=r.lng},intersects:function(e){e=A(e);var n=this._southWest,r=this._northEast,i=e.getSouthWest(),a=e.getNorthEast(),o=a.lat>=n.lat&&i.lat<=r.lat,s=a.lng>=n.lng&&i.lng<=r.lng;return o&&s},overlaps:function(e){e=A(e);var n=this._southWest,r=this._northEast,i=e.getSouthWest(),a=e.getNorthEast(),o=a.lat>n.lat&&i.latn.lng&&i.lng1,Ke=function(){var e=!1;try{var n=Object.defineProperty({},"passive",{get:function(){e=!0}});window.addEventListener(`testPassiveEventSupport`,u,n),window.removeEventListener(`testPassiveEventSupport`,u,n)}catch{}return e}(),qe=function(){return!!document.createElement(`canvas`).getContext}(),Je=!!(document.createElementNS&&ge(`svg`).createSVGRect),Ye=!!Je&&(function(){var e=document.createElement(`div`);return e.innerHTML=``,(e.firstChild&&e.firstChild.namespaceURI)===`http://www.w3.org/2000/svg`})(),Xe=!Je&&function(){try{var e=document.createElement(`div`);e.innerHTML=``;var n=e.firstChild;return n.style.behavior=`url(#default#VML)`,n&&typeof n.adj==`object`}catch{return!1}}(),Ze=navigator.platform.indexOf(`Mac`)===0,Qe=navigator.platform.indexOf(`Linux`)===0;function I(e){return navigator.userAgent.toLowerCase().indexOf(e)>=0}var R={ie:ye,ielt9:be,edge:xe,webkit:Se,android:Ce,android23:we,androidStock:Ee,opera:De,chrome:Oe,gecko:ke,safari:Ae,phantom:je,opera12:Me,win:Ne,ie3d:Pe,webkit3d:Fe,gecko3d:Ie,any3d:Le,mobile:Re,mobileWebkit:ze,mobileWebkit3d:Be,msPointer:P,pointer:Ve,touch:Ue,touchNative:He,mobileOpera:We,mobileGecko:F,retina:Ge,passiveEvents:Ke,canvas:qe,svg:Je,vml:Xe,inlineSvg:Ye,mac:Ze,linux:Qe},$e=R.msPointer?`MSPointerDown`:`pointerdown`,et=R.msPointer?`MSPointerMove`:`pointermove`,tt=R.msPointer?`MSPointerUp`:`pointerup`,nt=R.msPointer?`MSPointerCancel`:`pointercancel`,rt={touchstart:$e,touchmove:et,touchend:tt,touchcancel:nt},it={touchstart:mt,touchmove:pt,touchend:pt,touchcancel:pt},at={},ot=!1;function st(e,n,r){return n===`touchstart`&&ft(),it[n]?(r=it[n].bind(this,r),e.addEventListener(rt[n],r,!1),r):(console.warn(`wrong event specified:`,n),u)}function ct(e,n,r){if(!rt[n]){console.warn(`wrong event specified:`,n);return}e.removeEventListener(rt[n],r,!1)}function lt(e){at[e.pointerId]=e}function ut(e){at[e.pointerId]&&(at[e.pointerId]=e)}function dt(e){delete at[e.pointerId]}function ft(){ot||=(document.addEventListener($e,lt,!0),document.addEventListener(et,ut,!0),document.addEventListener(tt,dt,!0),document.addEventListener(nt,dt,!0),!0)}function pt(e,n){if(n.pointerType!==(n.MSPOINTER_TYPE_MOUSE||`mouse`)){for(var r in n.touches=[],at)n.touches.push(at[r]);n.changedTouches=[n],e(n)}}function mt(e,n){n.MSPOINTER_TYPE_TOUCH&&n.pointerType===n.MSPOINTER_TYPE_TOUCH&&X(n),pt(e,n)}function ht(e){var n={},r,i;for(i in e)r=e[i],n[i]=r&&r.bind?r.bind(e):r;return e=n,n.type=`dblclick`,n.detail=2,n.isTrusted=!1,n._simulated=!0,n}var gt=200;function _t(e,n){e.addEventListener(`dblclick`,n);var r=0,i;function a(e){if(e.detail!==1){i=e.detail;return}if(!(e.pointerType===`mouse`||e.sourceCapabilities&&!e.sourceCapabilities.firesTouchEvents)){var a=$t(e);if(!(a.some(function(e){return e instanceof HTMLLabelElement&&e.attributes.for})&&!a.some(function(e){return e instanceof HTMLInputElement||e instanceof HTMLSelectElement}))){var o=Date.now();o-r<=gt?(i++,i===2&&n(ht(e))):i=1,r=o}}}return e.addEventListener(`click`,a),{dblclick:n,simDblclick:a}}function vt(e,n){e.removeEventListener(`dblclick`,n.dblclick),e.removeEventListener(`click`,n.simDblclick)}var yt=jt([`transform`,`webkitTransform`,`OTransform`,`MozTransform`,`msTransform`]),bt=jt([`webkitTransition`,`transition`,`OTransition`,`MozTransition`,`msTransition`]),xt=bt===`webkitTransition`||bt===`OTransition`?bt+`End`:`transitionend`;function St(e){return typeof e==`string`?document.getElementById(e):e}function Ct(e,n){var r=e.style[n]||e.currentStyle&&e.currentStyle[n];if((!r||r===`auto`)&&document.defaultView){var i=document.defaultView.getComputedStyle(e,null);r=i?i[n]:null}return r===`auto`?null:r}function z(e,n,r){var i=document.createElement(e);return i.className=n||``,r&&r.appendChild(i),i}function B(e){var n=e.parentNode;n&&n.removeChild(e)}function wt(e){for(;e.firstChild;)e.removeChild(e.firstChild)}function Tt(e){var n=e.parentNode;n&&n.lastChild!==e&&n.appendChild(e)}function Et(e){var n=e.parentNode;n&&n.firstChild!==e&&n.insertBefore(e,n.firstChild)}function Dt(e,n){if(e.classList!==void 0)return e.classList.contains(n);var r=kt(e);return r.length>0&&RegExp(`(^|\\s)`+n+`(\\s|$)`).test(r)}function V(e,n){if(e.classList!==void 0)for(var r=p(n),i=0,a=r.length;i0?2*window.devicePixelRatio:1;function nn(e){return R.edge?e.wheelDeltaY/2:e.deltaY&&e.deltaMode===0?-e.deltaY/tn:e.deltaY&&e.deltaMode===1?-e.deltaY*20:e.deltaY&&e.deltaMode===2?-e.deltaY*60:e.deltaX||e.deltaZ?0:e.wheelDelta?(e.wheelDeltaY||e.wheelDelta)/2:e.detail&&Math.abs(e.detail)<32765?-e.detail*20:e.detail?e.detail/-32765*60:0}function rn(e,n){var r=n.relatedTarget;if(!r)return!0;try{for(;r&&r!==e;)r=r.parentNode}catch{return!1}return r!==e}var an={__proto__:null,on:q,off:Y,stopPropagation:Yt,disableScrollPropagation:Xt,disableClickPropagation:Zt,preventDefault:X,stop:Qt,getPropagationPath:$t,getMousePosition:en,getWheelDelta:nn,isExternalTarget:rn,addListener:q,removeListener:Y},on=ce.extend({run:function(e,n,r,i){this.stop(),this._el=e,this._inProgress=!0,this._duration=r||.25,this._easeOutPower=1/Math.max(i||.5,.2),this._startPos=Nt(e),this._offset=n.subtract(this._startPos),this._startTime=+new Date,this.fire(`start`),this._animate()},stop:function(){this._inProgress&&(this._step(!0),this._complete())},_animate:function(){this._animId=b(this._animate,this),this._step()},_step:function(e){var n=+new Date-this._startTime,r=this._duration*1e3;nthis.options.maxZoom)?this.setZoom(e):this},panInsideBounds:function(e,n){this._enforcingBounds=!0;var r=this.getCenter(),i=this._limitCenter(r,this._zoom,A(e));return r.equals(i)||this.panTo(i,n),this._enforcingBounds=!1,this},panInside:function(e,n){n||={};var r=E(n.paddingTopLeft||n.padding||[0,0]),i=E(n.paddingBottomRight||n.padding||[0,0]),a=this.project(this.getCenter()),o=this.project(e),s=this.getPixelBounds(),c=O([s.min.add(r),s.max.subtract(i)]),l=c.getSize();if(!c.contains(o)){this._enforcingBounds=!0;var u=o.subtract(c.getCenter()),d=c.extend(o).getSize().subtract(l);a.x+=u.x<0?-d.x:d.x,a.y+=u.y<0?-d.y:d.y,this.panTo(this.unproject(a),n),this._enforcingBounds=!1}return this},invalidateSize:function(e){if(!this._loaded)return this;e=r({animate:!1,pan:!0},e===!0?{animate:!0}:e);var n=this.getSize();this._sizeChanged=!0,this._lastCenter=null;var i=this.getSize(),o=n.divideBy(2).round(),s=i.divideBy(2).round(),c=o.subtract(s);return!c.x&&!c.y?this:(e.animate&&e.pan?this.panBy(c):(e.pan&&this._rawPanBy(c),this.fire(`move`),e.debounceMoveend?(clearTimeout(this._sizeTimer),this._sizeTimer=setTimeout(a(this.fire,this,`moveend`),200)):this.fire(`moveend`)),this.fire(`resize`,{oldSize:n,newSize:i}))},stop:function(){return this.setZoom(this._limitZoom(this._zoom)),this.options.zoomSnap||this.fire(`viewreset`),this._stop()},locate:function(e){if(e=this._locateOptions=r({timeout:1e4,watch:!1},e),!(`geolocation`in navigator))return this._handleGeolocationError({code:0,message:`Geolocation not supported.`}),this;var n=a(this._handleGeolocationResponse,this),i=a(this._handleGeolocationError,this);return e.watch?this._locationWatchId=navigator.geolocation.watchPosition(n,i,e):navigator.geolocation.getCurrentPosition(n,i,e),this},stopLocate:function(){return navigator.geolocation&&navigator.geolocation.clearWatch&&navigator.geolocation.clearWatch(this._locationWatchId),this._locateOptions&&(this._locateOptions.setView=!1),this},_handleGeolocationError:function(e){if(this._container._leaflet_id){var n=e.code,r=e.message||(n===1?`permission denied`:n===2?`position unavailable`:`timeout`);this._locateOptions.setView&&!this._loaded&&this.fitWorld(),this.fire(`locationerror`,{code:n,message:`Geolocation error: `+r+`.`})}},_handleGeolocationResponse:function(e){if(this._container._leaflet_id){var n=e.coords.latitude,r=e.coords.longitude,i=new j(n,r),a=i.toBounds(e.coords.accuracy*2),o=this._locateOptions;if(o.setView){var s=this.getBoundsZoom(a);this.setView(i,o.maxZoom?Math.min(s,o.maxZoom):s)}var c={latlng:i,bounds:a,timestamp:e.timestamp};for(var l in e.coords)typeof e.coords[l]==`number`&&(c[l]=e.coords[l]);this.fire(`locationfound`,c)}},addHandler:function(e,n){if(!n)return this;var r=this[e]=new n(this);return this._handlers.push(r),this.options[e]&&r.enable(),this},remove:function(){if(this._initEvents(!0),this.options.maxBounds&&this.off(`moveend`,this._panInsideMaxBounds),this._containerId!==this._container._leaflet_id)throw Error(`Map container is being reused by another instance`);try{delete this._container._leaflet_id,delete this._containerId}catch{this._container._leaflet_id=void 0,this._containerId=void 0}for(var e in this._locationWatchId!==void 0&&this.stopLocate(),this._stop(),B(this._mapPane),this._clearControlPos&&this._clearControlPos(),this._resizeRequest&&=(x(this._resizeRequest),null),this._clearHandlers(),this._loaded&&this.fire(`unload`),this._layers)this._layers[e].remove();for(e in this._panes)B(this._panes[e]);return this._layers=[],this._panes=[],delete this._mapPane,delete this._renderer,this},createPane:function(e,n){var r=z(`div`,`leaflet-pane`+(e?` leaflet-`+e.replace(`Pane`,``)+`-pane`:``),n||this._mapPane);return e&&(this._panes[e]=r),r},getCenter:function(){return this._checkIfLoaded(),this._lastCenter&&!this._moved()?this._lastCenter.clone():this.layerPointToLatLng(this._getCenterLayerPoint())},getZoom:function(){return this._zoom},getBounds:function(){var e=this.getPixelBounds();return new k(this.unproject(e.getBottomLeft()),this.unproject(e.getTopRight()))},getMinZoom:function(){return this.options.minZoom===void 0?this._layersMinZoom||0:this.options.minZoom},getMaxZoom:function(){return this.options.maxZoom===void 0?this._layersMaxZoom===void 0?1/0:this._layersMaxZoom:this.options.maxZoom},getBoundsZoom:function(e,n,r){e=A(e),r=E(r||[0,0]);var i=this.getZoom()||0,a=this.getMinZoom(),o=this.getMaxZoom(),s=e.getNorthWest(),c=e.getSouthEast(),l=this.getSize().subtract(r),u=O(this.project(c,i),this.project(s,i)).getSize(),d=R.any3d?this.options.zoomSnap:1,f=l.x/u.x,p=l.y/u.y,m=n?Math.max(f,p):Math.min(f,p);return i=this.getScaleZoom(m,i),d&&(i=Math.round(i/(d/100))*(d/100),i=n?Math.ceil(i/d)*d:Math.floor(i/d)*d),Math.max(a,Math.min(o,i))},getSize:function(){return(!this._size||this._sizeChanged)&&(this._size=new w(this._container.clientWidth||0,this._container.clientHeight||0),this._sizeChanged=!1),this._size.clone()},getPixelBounds:function(e,n){var r=this._getTopLeftPoint(e,n);return new D(r,r.add(this.getSize()))},getPixelOrigin:function(){return this._checkIfLoaded(),this._pixelOrigin},getPixelWorldBounds:function(e){return this.options.crs.getProjectedBounds(e===void 0?this.getZoom():e)},getPane:function(e){return typeof e==`string`?this._panes[e]:e},getPanes:function(){return this._panes},getContainer:function(){return this._container},getZoomScale:function(e,n){var r=this.options.crs;return n=n===void 0?this._zoom:n,r.scale(e)/r.scale(n)},getScaleZoom:function(e,n){var r=this.options.crs;n=n===void 0?this._zoom:n;var i=r.zoom(e*r.scale(n));return isNaN(i)?1/0:i},project:function(e,n){return n=n===void 0?this._zoom:n,this.options.crs.latLngToPoint(M(e),n)},unproject:function(e,n){return n=n===void 0?this._zoom:n,this.options.crs.pointToLatLng(E(e),n)},layerPointToLatLng:function(e){var n=E(e).add(this.getPixelOrigin());return this.unproject(n)},latLngToLayerPoint:function(e){return this.project(M(e))._round()._subtract(this.getPixelOrigin())},wrapLatLng:function(e){return this.options.crs.wrapLatLng(M(e))},wrapLatLngBounds:function(e){return this.options.crs.wrapLatLngBounds(A(e))},distance:function(e,n){return this.options.crs.distance(M(e),M(n))},containerPointToLayerPoint:function(e){return E(e).subtract(this._getMapPanePos())},layerPointToContainerPoint:function(e){return E(e).add(this._getMapPanePos())},containerPointToLatLng:function(e){var n=this.containerPointToLayerPoint(E(e));return this.layerPointToLatLng(n)},latLngToContainerPoint:function(e){return this.layerPointToContainerPoint(this.latLngToLayerPoint(M(e)))},mouseEventToContainerPoint:function(e){return en(e,this._container)},mouseEventToLayerPoint:function(e){return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e))},mouseEventToLatLng:function(e){return this.layerPointToLatLng(this.mouseEventToLayerPoint(e))},_initContainer:function(e){var n=this._container=St(e);if(!n)throw Error(`Map container not found.`);if(n._leaflet_id)throw Error(`Map container is already initialized.`);q(n,`scroll`,this._onScroll,this),this._containerId=s(n)},_initLayout:function(){var e=this._container;this._fadeAnimated=this.options.fadeAnimation&&R.any3d,V(e,`leaflet-container`+(R.touch?` leaflet-touch`:``)+(R.retina?` leaflet-retina`:``)+(R.ielt9?` leaflet-oldie`:``)+(R.safari?` leaflet-safari`:``)+(this._fadeAnimated?` leaflet-fade-anim`:``));var n=Ct(e,`position`);n!==`absolute`&&n!==`relative`&&n!==`fixed`&&n!==`sticky`&&(e.style.position=`relative`),this._initPanes(),this._initControlPos&&this._initControlPos()},_initPanes:function(){var e=this._panes={};this._paneRenderers={},this._mapPane=this.createPane(`mapPane`,this._container),W(this._mapPane,new w(0,0)),this.createPane(`tilePane`),this.createPane(`overlayPane`),this.createPane(`shadowPane`),this.createPane(`markerPane`),this.createPane(`tooltipPane`),this.createPane(`popupPane`),this.options.markerZoomAnimation||(V(e.markerPane,`leaflet-zoom-hide`),V(e.shadowPane,`leaflet-zoom-hide`))},_resetView:function(e,n,r){W(this._mapPane,new w(0,0));var i=!this._loaded;this._loaded=!0,n=this._limitZoom(n),this.fire(`viewprereset`);var a=this._zoom!==n;this._moveStart(a,r)._move(e,n)._moveEnd(a),this.fire(`viewreset`),i&&this.fire(`load`)},_moveStart:function(e,n){return e&&this.fire(`zoomstart`),n||this.fire(`movestart`),this},_move:function(e,n,r,i){n===void 0&&(n=this._zoom);var a=this._zoom!==n;return this._zoom=n,this._lastCenter=e,this._pixelOrigin=this._getNewPixelOrigin(e),i?r&&r.pinch&&this.fire(`zoom`,r):((a||r&&r.pinch)&&this.fire(`zoom`,r),this.fire(`move`,r)),this},_moveEnd:function(e){return e&&this.fire(`zoomend`),this.fire(`moveend`)},_stop:function(){return x(this._flyToFrame),this._panAnim&&this._panAnim.stop(),this},_rawPanBy:function(e){W(this._mapPane,this._getMapPanePos().subtract(e))},_getZoomSpan:function(){return this.getMaxZoom()-this.getMinZoom()},_panInsideMaxBounds:function(){this._enforcingBounds||this.panInsideBounds(this.options.maxBounds)},_checkIfLoaded:function(){if(!this._loaded)throw Error(`Set map center and zoom first.`)},_initEvents:function(e){this._targets={},this._targets[s(this._container)]=this;var n=e?Y:q;n(this._container,`click dblclick mousedown mouseup mouseover mouseout mousemove contextmenu keypress keydown keyup`,this._handleDOMEvent,this),this.options.trackResize&&n(window,`resize`,this._onResize,this),R.any3d&&this.options.transform3DLimit&&(e?this.off:this.on).call(this,`moveend`,this._onMoveEnd)},_onResize:function(){x(this._resizeRequest),this._resizeRequest=b(function(){this.invalidateSize({debounceMoveend:!0})},this)},_onScroll:function(){this._container.scrollTop=0,this._container.scrollLeft=0},_onMoveEnd:function(){var e=this._getMapPanePos();Math.max(Math.abs(e.x),Math.abs(e.y))>=this.options.transform3DLimit&&this._resetView(this.getCenter(),this.getZoom())},_findEventTargets:function(e,n){for(var r=[],i,a=n===`mouseout`||n===`mouseover`,o=e.target||e.srcElement,c=!1;o;){if(i=this._targets[s(o)],i&&(n===`click`||n===`preclick`)&&this._draggableMoved(i)){c=!0;break}if(i&&i.listens(n,!0)&&(a&&!rn(o,e)||(r.push(i),a))||o===this._container)break;o=o.parentNode}return!r.length&&!c&&!a&&this.listens(n,!0)&&(r=[this]),r},_isClickDisabled:function(e){for(;e&&e!==this._container;){if(e._leaflet_disable_click)return!0;e=e.parentNode}},_handleDOMEvent:function(e){var n=e.target||e.srcElement;if(!(!this._loaded||n._leaflet_disable_events||e.type===`click`&&this._isClickDisabled(n))){var r=e.type;r===`mousedown`&&K(n),this._fireDOMEvent(e,r)}},_mouseEvents:[`click`,`dblclick`,`mouseover`,`mouseout`,`contextmenu`],_fireDOMEvent:function(e,n,i){if(e.type===`click`){var a=r({},e);a.type=`preclick`,this._fireDOMEvent(a,a.type,i)}var o=this._findEventTargets(e,n);if(i){for(var s=[],c=0;c0?Math.round(e-n)/2:Math.max(0,Math.ceil(e))-Math.max(0,Math.floor(n))},_limitZoom:function(e){var n=this.getMinZoom(),r=this.getMaxZoom(),i=R.any3d?this.options.zoomSnap:1;return i&&(e=Math.round(e/i)*i),Math.max(n,Math.min(r,e))},_onPanTransitionStep:function(){this.fire(`move`)},_onPanTransitionEnd:function(){H(this._mapPane,`leaflet-pan-anim`),this.fire(`moveend`)},_tryAnimatedPan:function(e,n){var r=this._getCenterOffset(e)._trunc();return(n&&n.animate)!==!0&&!this.getSize().contains(r)?!1:(this.panBy(r,n),!0)},_createAnimProxy:function(){var e=this._proxy=z(`div`,`leaflet-proxy leaflet-zoom-animated`);this._panes.mapPane.appendChild(e),this.on(`zoomanim`,function(e){var n=yt,r=this._proxy.style[n];Mt(this._proxy,this.project(e.center,e.zoom),this.getZoomScale(e.zoom,1)),r===this._proxy.style[n]&&this._animatingZoom&&this._onZoomTransitionEnd()},this),this.on(`load moveend`,this._animMoveEnd,this),this._on(`unload`,this._destroyAnimProxy,this)},_destroyAnimProxy:function(){B(this._proxy),this.off(`load moveend`,this._animMoveEnd,this),delete this._proxy},_animMoveEnd:function(){var e=this.getCenter(),n=this.getZoom();Mt(this._proxy,this.project(e,n),this.getZoomScale(n,1))},_catchTransitionEnd:function(e){this._animatingZoom&&e.propertyName.indexOf(`transform`)>=0&&this._onZoomTransitionEnd()},_nothingToAnimate:function(){return!this._container.getElementsByClassName(`leaflet-zoom-animated`).length},_tryAnimatedZoom:function(e,n,r){if(this._animatingZoom)return!0;if(r||={},!this._zoomAnimated||r.animate===!1||this._nothingToAnimate()||Math.abs(n-this._zoom)>this.options.zoomAnimationThreshold)return!1;var i=this.getZoomScale(n),a=this._getCenterOffset(e)._divideBy(1-1/i);return r.animate!==!0&&!this.getSize().contains(a)?!1:(b(function(){this._moveStart(!0,r.noMoveStart||!1)._animateZoom(e,n,!0)},this),!0)},_animateZoom:function(e,n,r,i){this._mapPane&&(r&&(this._animatingZoom=!0,this._animateToCenter=e,this._animateToZoom=n,V(this._mapPane,`leaflet-zoom-anim`)),this.fire(`zoomanim`,{center:e,zoom:n,noUpdate:i}),this._tempFireZoomEvent||=this._zoom!==this._animateToZoom,this._move(this._animateToCenter,this._animateToZoom,void 0,!0),setTimeout(a(this._onZoomTransitionEnd,this),250))},_onZoomTransitionEnd:function(){this._animatingZoom&&(this._mapPane&&H(this._mapPane,`leaflet-zoom-anim`),this._animatingZoom=!1,this._move(this._animateToCenter,this._animateToZoom,void 0,!0),this._tempFireZoomEvent&&this.fire(`zoom`),delete this._tempFireZoomEvent,this.fire(`move`),this._moveEnd(!0))}});function sn(e,n){return new Z(e,n)}var Q=S.extend({options:{position:`topright`},initialize:function(e){m(this,e)},getPosition:function(){return this.options.position},setPosition:function(e){var n=this._map;return n&&n.removeControl(this),this.options.position=e,n&&n.addControl(this),this},getContainer:function(){return this._container},addTo:function(e){this.remove(),this._map=e;var n=this._container=this.onAdd(e),r=this.getPosition(),i=e._controlCorners[r];return V(n,`leaflet-control`),r.indexOf(`bottom`)===-1?i.appendChild(n):i.insertBefore(n,i.firstChild),this._map.on(`unload`,this.remove,this),this},remove:function(){return this._map?(B(this._container),this.onRemove&&this.onRemove(this._map),this._map.off(`unload`,this.remove,this),this._map=null,this):this},_refocusOnMap:function(e){this._map&&e&&e.screenX>0&&e.screenY>0&&this._map.getContainer().focus()}}),cn=function(e){return new Q(e)};Z.include({addControl:function(e){return e.addTo(this),this},removeControl:function(e){return e.remove(),this},_initControlPos:function(){var e=this._controlCorners={},n=`leaflet-`,r=this._controlContainer=z(`div`,n+`control-container`,this._container);function i(i,a){var o=n+i+` `+n+a;e[i+a]=z(`div`,o,r)}i(`top`,`left`),i(`top`,`right`),i(`bottom`,`left`),i(`bottom`,`right`)},_clearControlPos:function(){for(var e in this._controlCorners)B(this._controlCorners[e]);B(this._controlContainer),delete this._controlCorners,delete this._controlContainer}});var ln=Q.extend({options:{collapsed:!0,position:`topright`,autoZIndex:!0,hideSingleBase:!1,sortLayers:!1,sortFunction:function(e,n,r,i){return r1,this._baseLayersList.style.display=e?``:`none`),this._separator.style.display=n&&e?``:`none`,this},_onLayerChange:function(e){this._handlingClick||this._update();var n=this._getLayer(s(e.target)),r=n.overlay?e.type===`add`?`overlayadd`:`overlayremove`:e.type===`add`?`baselayerchange`:null;r&&this._map.fire(r,n)},_createRadioElement:function(e,n){var r=``,i=document.createElement(`div`);return i.innerHTML=r,i.firstChild},_addItem:function(e){var n=document.createElement(`label`),r=this._map.hasLayer(e.layer),i;e.overlay?(i=document.createElement(`input`),i.type=`checkbox`,i.className=`leaflet-control-layers-selector`,i.defaultChecked=r):i=this._createRadioElement(`leaflet-base-layers_`+s(this),r),this._layerControlInputs.push(i),i.layerId=s(e.layer),q(i,`click`,this._onInputClick,this);var a=document.createElement(`span`);a.innerHTML=` `+e.name;var o=document.createElement(`span`);return n.appendChild(o),o.appendChild(i),o.appendChild(a),(e.overlay?this._overlaysList:this._baseLayersList).appendChild(n),this._checkDisabledLayers(),n},_onInputClick:function(){if(!this._preventClick){var e=this._layerControlInputs,n,r,i=[],a=[];this._handlingClick=!0;for(var o=e.length-1;o>=0;o--)n=e[o],r=this._getLayer(n.layerId).layer,n.checked?i.push(r):n.checked||a.push(r);for(o=0;o=0;a--)n=e[a],r=this._getLayer(n.layerId).layer,n.disabled=r.options.minZoom!==void 0&&ir.options.maxZoom},_expandIfNotCollapsed:function(){return this._map&&!this.options.collapsed&&this.expand(),this},_expandSafely:function(){var e=this._section;this._preventClick=!0,q(e,`click`,X),this.expand();var n=this;setTimeout(function(){Y(e,`click`,X),n._preventClick=!1})}}),un=function(e,n,r){return new ln(e,n,r)},dn=Q.extend({options:{position:`topleft`,zoomInText:``,zoomInTitle:`Zoom in`,zoomOutText:``,zoomOutTitle:`Zoom out`},onAdd:function(e){var n=`leaflet-control-zoom`,r=z(`div`,n+` leaflet-bar`),i=this.options;return this._zoomInButton=this._createButton(i.zoomInText,i.zoomInTitle,n+`-in`,r,this._zoomIn),this._zoomOutButton=this._createButton(i.zoomOutText,i.zoomOutTitle,n+`-out`,r,this._zoomOut),this._updateDisabled(),e.on(`zoomend zoomlevelschange`,this._updateDisabled,this),r},onRemove:function(e){e.off(`zoomend zoomlevelschange`,this._updateDisabled,this)},disable:function(){return this._disabled=!0,this._updateDisabled(),this},enable:function(){return this._disabled=!1,this._updateDisabled(),this},_zoomIn:function(e){!this._disabled&&this._map._zoomthis._map.getMinZoom()&&this._map.zoomOut(this._map.options.zoomDelta*(e.shiftKey?3:1))},_createButton:function(e,n,r,i,a){var o=z(`a`,r,i);return o.innerHTML=e,o.href=`#`,o.title=n,o.setAttribute(`role`,`button`),o.setAttribute(`aria-label`,n),Zt(o),q(o,`click`,Qt),q(o,`click`,a,this),q(o,`click`,this._refocusOnMap,this),o},_updateDisabled:function(){var e=this._map,n=`leaflet-disabled`;H(this._zoomInButton,n),H(this._zoomOutButton,n),this._zoomInButton.setAttribute(`aria-disabled`,`false`),this._zoomOutButton.setAttribute(`aria-disabled`,`false`),(this._disabled||e._zoom===e.getMinZoom())&&(V(this._zoomOutButton,n),this._zoomOutButton.setAttribute(`aria-disabled`,`true`)),(this._disabled||e._zoom===e.getMaxZoom())&&(V(this._zoomInButton,n),this._zoomInButton.setAttribute(`aria-disabled`,`true`))}});Z.mergeOptions({zoomControl:!0}),Z.addInitHook(function(){this.options.zoomControl&&(this.zoomControl=new dn,this.addControl(this.zoomControl))});var fn=function(e){return new dn(e)},pn=Q.extend({options:{position:`bottomleft`,maxWidth:100,metric:!0,imperial:!0},onAdd:function(e){var n=`leaflet-control-scale`,r=z(`div`,n),i=this.options;return this._addScales(i,n+`-line`,r),e.on(i.updateWhenIdle?`moveend`:`move`,this._update,this),e.whenReady(this._update,this),r},onRemove:function(e){e.off(this.options.updateWhenIdle?`moveend`:`move`,this._update,this)},_addScales:function(e,n,r){e.metric&&(this._mScale=z(`div`,n,r)),e.imperial&&(this._iScale=z(`div`,n,r))},_update:function(){var e=this._map,n=e.getSize().y/2,r=e.distance(e.containerPointToLatLng([0,n]),e.containerPointToLatLng([this.options.maxWidth,n]));this._updateScales(r)},_updateScales:function(e){this.options.metric&&e&&this._updateMetric(e),this.options.imperial&&e&&this._updateImperial(e)},_updateMetric:function(e){var n=this._getRoundNum(e),r=n<1e3?n+` m`:n/1e3+` km`;this._updateScale(this._mScale,r,n/e)},_updateImperial:function(e){var n=e*3.2808399,r,i,a;n>5280?(r=n/5280,i=this._getRoundNum(r),this._updateScale(this._iScale,i+` mi`,i/r)):(a=this._getRoundNum(n),this._updateScale(this._iScale,a+` ft`,a/n))},_updateScale:function(e,n,r){e.style.width=Math.round(this.options.maxWidth*r)+`px`,e.innerHTML=n},_getRoundNum:function(e){var n=10**((Math.floor(e)+``).length-1),r=e/n;return r=r>=10?10:r>=5?5:r>=3?3:r>=2?2:1,n*r}}),mn=function(e){return new pn(e)},hn=Q.extend({options:{position:`bottomright`,prefix:``+(R.inlineSvg?` `:``)+`Leaflet`},initialize:function(e){m(this,e),this._attributions={}},onAdd:function(e){for(var n in e.attributionControl=this,this._container=z(`div`,`leaflet-control-attribution`),Zt(this._container),e._layers)e._layers[n].getAttribution&&this.addAttribution(e._layers[n].getAttribution());return this._update(),e.on(`layeradd`,this._addAttribution,this),this._container},onRemove:function(e){e.off(`layeradd`,this._addAttribution,this)},_addAttribution:function(e){e.layer.getAttribution&&(this.addAttribution(e.layer.getAttribution()),e.layer.once(`remove`,function(){this.removeAttribution(e.layer.getAttribution())},this))},setPrefix:function(e){return this.options.prefix=e,this._update(),this},addAttribution:function(e){return e?(this._attributions[e]||(this._attributions[e]=0),this._attributions[e]++,this._update(),this):this},removeAttribution:function(e){return e&&this._attributions[e]&&(this._attributions[e]--,this._update()),this},_update:function(){if(this._map){var e=[];for(var n in this._attributions)this._attributions[n]&&e.push(n);var r=[];this.options.prefix&&r.push(this.options.prefix),e.length&&r.push(e.join(`, `)),this._container.innerHTML=r.join(` `)}}});Z.mergeOptions({attributionControl:!0}),Z.addInitHook(function(){this.options.attributionControl&&new hn().addTo(this)}),Q.Layers=ln,Q.Zoom=dn,Q.Scale=pn,Q.Attribution=hn,cn.layers=un,cn.zoom=fn,cn.scale=mn,cn.attribution=function(e){return new hn(e)};var gn=S.extend({initialize:function(e){this._map=e},enable:function(){return this._enabled?this:(this._enabled=!0,this.addHooks(),this)},disable:function(){return this._enabled?(this._enabled=!1,this.removeHooks(),this):this},enabled:function(){return!!this._enabled}});gn.addTo=function(e,n){return e.addHandler(n,this),this};var _n={Events:C},vn=R.touch?`touchstart mousedown`:`mousedown`,yn=ce.extend({options:{clickTolerance:3},initialize:function(e,n,r,i){m(this,i),this._element=e,this._dragStartTarget=n||e,this._preventOutline=r},enable:function(){this._enabled||=(q(this._dragStartTarget,vn,this._onDown,this),!0)},disable:function(){this._enabled&&(yn._dragging===this&&this.finishDrag(!0),Y(this._dragStartTarget,vn,this._onDown,this),this._enabled=!1,this._moved=!1)},_onDown:function(e){if(this._enabled&&(this._moved=!1,!Dt(this._element,`leaflet-zoom-anim`))){if(e.touches&&e.touches.length!==1){yn._dragging===this&&this.finishDrag();return}if(!(yn._dragging||e.shiftKey||e.which!==1&&e.button!==1&&!e.touches)&&(yn._dragging=this,this._preventOutline&&K(this._element),Lt(),G(),!this._moving)){this.fire(`down`);var n=e.touches?e.touches[0]:e,r=Ht(this._element);this._startPoint=new w(n.clientX,n.clientY),this._startPos=Nt(this._element),this._parentScale=Ut(r);var i=e.type===`mousedown`;q(document,i?`mousemove`:`touchmove`,this._onMove,this),q(document,i?`mouseup`:`touchend touchcancel`,this._onUp,this)}}},_onMove:function(e){if(this._enabled){if(e.touches&&e.touches.length>1){this._moved=!0;return}var n=e.touches&&e.touches.length===1?e.touches[0]:e,r=new w(n.clientX,n.clientY)._subtract(this._startPoint);!r.x&&!r.y||Math.abs(r.x)+Math.abs(r.y)o&&(s=c,o=l);o>r&&(n[s]=1,On(e,n,r,i,s),On(e,n,r,s,a))}function kn(e,n){for(var r=[e[0]],i=1,a=0,o=e.length;in&&(r.push(e[i]),a=i);return an.max.x&&(r|=2),e.yn.max.y&&(r|=8),r}function Pn(e,n){var r=n.x-e.x,i=n.y-e.y;return r*r+i*i}function Fn(e,n,r,i){var a=n.x,o=n.y,s=r.x-a,c=r.y-o,l=s*s+c*c,u;return l>0&&(u=((e.x-a)*s+(e.y-o)*c)/l,u>1?(a=r.x,o=r.y):u>0&&(a+=s*u,o+=c*u)),s=e.x-a,c=e.y-o,i?s*s+c*c:new w(a,o)}function $(e){return!v(e[0])||typeof e[0][0]!=`object`&&e[0][0]!==void 0}function In(e){return console.warn(`Deprecated use of _flat, please use L.LineUtil.isFlat instead.`),$(e)}function Ln(e,n){var r,i,a,o,s,c,l,u;if(!e||e.length===0)throw Error(`latlngs not passed`);$(e)||(console.warn(`latlngs are not flat! Only the first ring will be used`),e=e[0]);var d=M([0,0]),f=A(e);f.getNorthWest().distanceTo(f.getSouthWest())*f.getNorthEast().distanceTo(f.getNorthWest())<1700&&(d=Sn(e));var p=e.length,m=[];for(r=0;ri){l=(o-i)/a,u=[c.x-l*(c.x-s.x),c.y-l*(c.y-s.y)];break}var g=n.unproject(E(u));return M([g.lat+d.lat,g.lng+d.lng])}var Rn={__proto__:null,simplify:wn,pointToSegmentDistance:Tn,closestPointOnSegment:En,clipSegment:jn,_getEdgeIntersection:Mn,_getBitCode:Nn,_sqClosestPointOnSegment:Fn,isFlat:$,_flat:In,polylineCenter:Ln},zn={project:function(e){return new w(e.lng,e.lat)},unproject:function(e){return new j(e.y,e.x)},bounds:new D([-180,-90],[180,90])},Bn={R:6378137,R_MINOR:6356752.314245179,bounds:new D([-20037508.34279,-15496570.73972],[20037508.34279,18764656.23138]),project:function(e){var n=Math.PI/180,r=this.R,i=e.lat*n,a=this.R_MINOR/r,o=Math.sqrt(1-a*a),s=o*Math.sin(i),c=Math.tan(Math.PI/4-i/2)/((1-s)/(1+s))**(o/2);return i=-r*Math.log(Math.max(c,1e-10)),new w(e.lng*n*r,i)},unproject:function(e){for(var n=180/Math.PI,r=this.R,i=this.R_MINOR/r,a=Math.sqrt(1-i*i),o=Math.exp(-e.y/r),s=Math.PI/2-2*Math.atan(o),c=0,l=.1,u;c<15&&Math.abs(l)>1e-7;c++)u=a*Math.sin(s),u=((1-u)/(1+u))**(a/2),l=Math.PI/2-2*Math.atan(o*u)-s,s+=l;return new j(s*n,e.x*n/r)}},Vn={__proto__:null,LonLat:zn,Mercator:Bn,SphericalMercator:de},Hn=r({},le,{code:`EPSG:3395`,projection:Bn,transformation:function(){var e=.5/(Math.PI*Bn.R);return pe(e,.5,-e,.5)}()}),Un=r({},le,{code:`EPSG:4326`,projection:zn,transformation:pe(1/180,1,-1/180,.5)}),Wn=r({},N,{projection:zn,transformation:pe(1,0,-1,0),scale:function(e){return 2**e},zoom:function(e){return Math.log(e)/Math.LN2},distance:function(e,n){var r=n.lng-e.lng,i=n.lat-e.lat;return Math.sqrt(r*r+i*i)},infinite:!0});N.Earth=le,N.EPSG3395=Hn,N.EPSG3857=me,N.EPSG900913=he,N.EPSG4326=Un,N.Simple=Wn;var Gn=ce.extend({options:{pane:`overlayPane`,attribution:null,bubblingMouseEvents:!0},addTo:function(e){return e.addLayer(this),this},remove:function(){return this.removeFrom(this._map||this._mapToAdd)},removeFrom:function(e){return e&&e.removeLayer(this),this},getPane:function(e){return this._map.getPane(e?this.options[e]||e:this.options.pane)},addInteractiveTarget:function(e){return this._map._targets[s(e)]=this,this},removeInteractiveTarget:function(e){return delete this._map._targets[s(e)],this},getAttribution:function(){return this.options.attribution},_layerAdd:function(e){var n=e.target;if(n.hasLayer(this)){if(this._map=n,this._zoomAnimated=n._zoomAnimated,this.getEvents){var r=this.getEvents();n.on(r,this),this.once(`remove`,function(){n.off(r,this)},this)}this.onAdd(n),this.fire(`add`),n.fire(`layeradd`,{layer:this})}}});Z.include({addLayer:function(e){if(!e._layerAdd)throw Error(`The provided object is not a Layer.`);var n=s(e);return this._layers[n]?this:(this._layers[n]=e,e._mapToAdd=this,e.beforeAdd&&e.beforeAdd(this),this.whenReady(e._layerAdd,e),this)},removeLayer:function(e){var n=s(e);return this._layers[n]?(this._loaded&&e.onRemove(this),delete this._layers[n],this._loaded&&(this.fire(`layerremove`,{layer:e}),e.fire(`remove`)),e._map=e._mapToAdd=null,this):this},hasLayer:function(e){return s(e)in this._layers},eachLayer:function(e,n){for(var r in this._layers)e.call(n,this._layers[r]);return this},_addLayers:function(e){e=e?v(e)?e:[e]:[];for(var n=0,r=e.length;nthis._layersMaxZoom&&this.setZoom(this._layersMaxZoom),this.options.minZoom===void 0&&this._layersMinZoom&&this.getZoom()=2&&n[0]instanceof j&&n[0].equals(n[r-1])&&n.pop(),n},_setLatLngs:function(e){sr.prototype._setLatLngs.call(this,e),$(this._latlngs)&&(this._latlngs=[this._latlngs])},_defaultShape:function(){return $(this._latlngs[0])?this._latlngs[0]:this._latlngs[0][0]},_clipPoints:function(){var e=this._renderer._bounds,n=this.options.weight,r=new w(n,n);if(e=new D(e.min.subtract(r),e.max.add(r)),this._parts=[],!(!this._pxBounds||!this._pxBounds.intersects(e))){if(this.options.noClip){this._parts=this._rings;return}for(var i=0,a=this._rings.length,o;ie.y!=a.y>e.y&&e.x<(a.x-i.x)*(e.y-i.y)/(a.y-i.y)+i.x&&(n=!n);return n||sr.prototype._containsPoint.call(this,e,!0)}});function ur(e,n){return new lr(e,n)}var dr=Jn.extend({initialize:function(e,n){m(this,n),this._layers={},e&&this.addData(e)},addData:function(e){var n=v(e)?e:e.features,r,i,a;if(n){for(r=0,i=n.length;r0&&a.push(a[0].slice()),a}function vr(e,n){return e.feature?r({},e.feature,{geometry:n}):yr(n)}function yr(e){return e.type===`Feature`||e.type===`FeatureCollection`?e:{type:`Feature`,properties:{},geometry:e}}var br={toGeoJSON:function(e){return vr(this,{type:`Point`,coordinates:gr(this.getLatLng(),e)})}};er.include(br),ar.include(br),rr.include(br),sr.include({toGeoJSON:function(e){var n=!$(this._latlngs),r=_r(this._latlngs,+!!n,!1,e);return vr(this,{type:(n?`Multi`:``)+`LineString`,coordinates:r})}}),lr.include({toGeoJSON:function(e){var n=!$(this._latlngs),r=n&&!$(this._latlngs[0]),i=_r(this._latlngs,r?2:+!!n,!0,e);return n||(i=[i]),vr(this,{type:(r?`Multi`:``)+`Polygon`,coordinates:i})}}),Kn.include({toMultiPoint:function(e){var n=[];return this.eachLayer(function(r){n.push(r.toGeoJSON(e).geometry.coordinates)}),vr(this,{type:`MultiPoint`,coordinates:n})},toGeoJSON:function(e){var n=this.feature&&this.feature.geometry&&this.feature.geometry.type;if(n===`MultiPoint`)return this.toMultiPoint(e);var r=n===`GeometryCollection`,i=[];return this.eachLayer(function(n){if(n.toGeoJSON){var a=n.toGeoJSON(e);if(r)i.push(a.geometry);else{var o=yr(a);o.type===`FeatureCollection`?i.push.apply(i,o.features):i.push(o)}}}),r?vr(this,{geometries:i,type:`GeometryCollection`}):{type:`FeatureCollection`,features:i}}});function xr(e,n){return new dr(e,n)}var Sr=xr,Cr=Gn.extend({options:{opacity:1,alt:``,interactive:!1,crossOrigin:!1,errorOverlayUrl:``,zIndex:1,className:``},initialize:function(e,n,r){this._url=e,this._bounds=A(n),m(this,r)},onAdd:function(){this._image||(this._initImage(),this.options.opacity<1&&this._updateOpacity()),this.options.interactive&&(V(this._image,`leaflet-interactive`),this.addInteractiveTarget(this._image)),this.getPane().appendChild(this._image),this._reset()},onRemove:function(){B(this._image),this.options.interactive&&this.removeInteractiveTarget(this._image)},setOpacity:function(e){return this.options.opacity=e,this._image&&this._updateOpacity(),this},setStyle:function(e){return e.opacity&&this.setOpacity(e.opacity),this},bringToFront:function(){return this._map&&Tt(this._image),this},bringToBack:function(){return this._map&&Et(this._image),this},setUrl:function(e){return this._url=e,this._image&&(this._image.src=e),this},setBounds:function(e){return this._bounds=A(e),this._map&&this._reset(),this},getEvents:function(){var e={zoom:this._reset,viewreset:this._reset};return this._zoomAnimated&&(e.zoomanim=this._animateZoom),e},setZIndex:function(e){return this.options.zIndex=e,this._updateZIndex(),this},getBounds:function(){return this._bounds},getElement:function(){return this._image},_initImage:function(){var e=this._url.tagName===`IMG`,n=this._image=e?this._url:z(`img`);if(V(n,`leaflet-image-layer`),this._zoomAnimated&&V(n,`leaflet-zoom-animated`),this.options.className&&V(n,this.options.className),n.onselectstart=u,n.onmousemove=u,n.onload=a(this.fire,this,`load`),n.onerror=a(this._overlayOnError,this,`error`),(this.options.crossOrigin||this.options.crossOrigin===``)&&(n.crossOrigin=this.options.crossOrigin===!0?``:this.options.crossOrigin),this.options.zIndex&&this._updateZIndex(),e){this._url=n.src;return}n.src=this._url,n.alt=this.options.alt},_animateZoom:function(e){var n=this._map.getZoomScale(e.zoom),r=this._map._latLngBoundsToNewLayerBounds(this._bounds,e.zoom,e.center).min;Mt(this._image,r,n)},_reset:function(){var e=this._image,n=new D(this._map.latLngToLayerPoint(this._bounds.getNorthWest()),this._map.latLngToLayerPoint(this._bounds.getSouthEast())),r=n.getSize();W(e,n.min),e.style.width=r.x+`px`,e.style.height=r.y+`px`},_updateOpacity:function(){U(this._image,this.options.opacity)},_updateZIndex:function(){this._image&&this.options.zIndex!==void 0&&this.options.zIndex!==null&&(this._image.style.zIndex=this.options.zIndex)},_overlayOnError:function(){this.fire(`error`);var e=this.options.errorOverlayUrl;e&&this._url!==e&&(this._url=e,this._image.src=e)},getCenter:function(){return this._bounds.getCenter()}}),wr=function(e,n,r){return new Cr(e,n,r)},Tr=Cr.extend({options:{autoplay:!0,loop:!0,keepAspectRatio:!0,muted:!1,playsInline:!0},_initImage:function(){var e=this._url.tagName===`VIDEO`,n=this._image=e?this._url:z(`video`);if(V(n,`leaflet-image-layer`),this._zoomAnimated&&V(n,`leaflet-zoom-animated`),this.options.className&&V(n,this.options.className),n.onselectstart=u,n.onmousemove=u,n.onloadeddata=a(this.fire,this,`load`),e){for(var r=n.getElementsByTagName(`source`),i=[],o=0;o0?i:[n.src];return}v(this._url)||(this._url=[this._url]),!this.options.keepAspectRatio&&Object.prototype.hasOwnProperty.call(n.style,`objectFit`)&&(n.style.objectFit=`fill`),n.autoplay=!!this.options.autoplay,n.loop=!!this.options.loop,n.muted=!!this.options.muted,n.playsInline=!!this.options.playsInline;for(var s=0;s