From 98c8c986030bd7495629110c7dfc009b4cc8a681 Mon Sep 17 00:00:00 2001 From: Gani Georgiev Date: Sun, 10 Dec 2023 12:50:56 +0200 Subject: [PATCH] updated jsvm types --- .../jsvm/internal/types/generated/types.d.ts | 7016 ++++++++--------- 1 file changed, 3508 insertions(+), 3508 deletions(-) diff --git a/plugins/jsvm/internal/types/generated/types.d.ts b/plugins/jsvm/internal/types/generated/types.d.ts index 9a9f98bdf..b8ddab172 100644 --- a/plugins/jsvm/internal/types/generated/types.d.ts +++ b/plugins/jsvm/internal/types/generated/types.d.ts @@ -1627,8 +1627,8 @@ namespace os { * than ReadFrom. This is used to permit ReadFrom to call io.Copy * without leading to a recursive call to ReadFrom. */ - type _subbsHpU = File - interface fileWithoutReadFrom extends _subbsHpU { + type _subSGceb = File + interface fileWithoutReadFrom extends _subSGceb { } interface fileWithoutReadFrom { /** @@ -2285,8 +2285,8 @@ namespace os { /** * File represents an open file descriptor. */ - type _subXHWce = file - interface File extends _subXHWce { + type _subzrZng = file + interface File extends _subzrZng { } /** * A FileInfo describes a file and is returned by Stat and Lstat. @@ -2687,24 +2687,6 @@ namespace filepath { } } -/** - * 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 - } -} - /** * Package dbx provides a set of DB-agnostic and easy-to-use query building methods for relational databases. */ @@ -3041,14 +3023,14 @@ namespace dbx { /** * MssqlBuilder is the builder for SQL Server databases. */ - type _subnVnYG = BaseBuilder - interface MssqlBuilder extends _subnVnYG { + type _subKqIKr = BaseBuilder + interface MssqlBuilder extends _subKqIKr { } /** * MssqlQueryBuilder is the query builder for SQL Server databases. */ - type _subAPCfU = BaseQueryBuilder - interface MssqlQueryBuilder extends _subAPCfU { + type _subPIWQx = BaseQueryBuilder + interface MssqlQueryBuilder extends _subPIWQx { } interface newMssqlBuilder { /** @@ -3119,8 +3101,8 @@ namespace dbx { /** * MysqlBuilder is the builder for MySQL databases. */ - type _subRNnzR = BaseBuilder - interface MysqlBuilder extends _subRNnzR { + type _subtNrxE = BaseBuilder + interface MysqlBuilder extends _subtNrxE { } interface newMysqlBuilder { /** @@ -3195,14 +3177,14 @@ namespace dbx { /** * OciBuilder is the builder for Oracle databases. */ - type _subYViQV = BaseBuilder - interface OciBuilder extends _subYViQV { + type _subQvUWw = BaseBuilder + interface OciBuilder extends _subQvUWw { } /** * OciQueryBuilder is the query builder for Oracle databases. */ - type _subyHNQk = BaseQueryBuilder - interface OciQueryBuilder extends _subyHNQk { + type _subwnsWb = BaseQueryBuilder + interface OciQueryBuilder extends _subwnsWb { } interface newOciBuilder { /** @@ -3265,8 +3247,8 @@ namespace dbx { /** * PgsqlBuilder is the builder for PostgreSQL databases. */ - type _subXpWnL = BaseBuilder - interface PgsqlBuilder extends _subXpWnL { + type _subGugrU = BaseBuilder + interface PgsqlBuilder extends _subGugrU { } interface newPgsqlBuilder { /** @@ -3333,8 +3315,8 @@ namespace dbx { /** * SqliteBuilder is the builder for SQLite databases. */ - type _subFvQQP = BaseBuilder - interface SqliteBuilder extends _subFvQQP { + type _subJBzSP = BaseBuilder + interface SqliteBuilder extends _subJBzSP { } interface newSqliteBuilder { /** @@ -3433,8 +3415,8 @@ namespace dbx { /** * StandardBuilder is the builder that is used by DB for an unknown driver. */ - type _subkQLQn = BaseBuilder - interface StandardBuilder extends _subkQLQn { + type _subFGyOQ = BaseBuilder + interface StandardBuilder extends _subFGyOQ { } interface newStandardBuilder { /** @@ -3500,8 +3482,8 @@ namespace dbx { * 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 _subLSYiF = Builder - interface DB extends _subLSYiF { + type _subtJfhr = Builder + interface DB extends _subtJfhr { /** * FieldMapper maps struct fields to DB columns. Defaults to DefaultFieldMapFunc. */ @@ -4303,8 +4285,8 @@ namespace dbx { * 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 _subzIvQz = sql.Rows - interface Rows extends _subzIvQz { + type _subWpZWm = sql.Rows + interface Rows extends _subWpZWm { } interface Rows { /** @@ -4661,8 +4643,8 @@ namespace dbx { }): string } interface structInfo { } - type _subxIELb = structInfo - interface structValue extends _subxIELb { + type _subrffRJ = structInfo + interface structValue extends _subrffRJ { } interface fieldInfo { } @@ -4701,8 +4683,8 @@ namespace dbx { /** * Tx enhances sql.Tx with additional querying methods. */ - type _subOCHpi = Builder - interface Tx extends _subOCHpi { + type _subiGQlH = Builder + interface Tx extends _subiGQlH { } interface Tx { /** @@ -4718,6 +4700,24 @@ namespace dbx { } } +/** + * 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 + } +} + /** * Package exec runs external commands. It wraps os.StartProcess to make it * easier to remap stdin and stdout, connect I/O with pipes, and do other @@ -5065,8 +5065,8 @@ namespace filesystem { */ open(): io.ReadSeekCloser } - type _subdkRRW = bytes.Reader - interface bytesReadSeekCloser extends _subdkRRW { + type _subDLaUX = bytes.Reader + interface bytesReadSeekCloser extends _subDLaUX { } interface bytesReadSeekCloser { /** @@ -6196,8 +6196,8 @@ namespace forms { /** * SettingsUpsert is a [settings.Settings] upsert (create/update) form. */ - type _subljCDC = settings.Settings - interface SettingsUpsert extends _subljCDC { + type _subtmFEQ = settings.Settings + interface SettingsUpsert extends _subtmFEQ { } interface newSettingsUpsert { /** @@ -6623,8 +6623,8 @@ namespace pocketbase { /** * appWrapper serves as a private CoreApp instance wrapper. */ - type _subctqaa = CoreApp - interface appWrapper extends _subctqaa { + type _suboAkdh = CoreApp + interface appWrapper extends _suboAkdh { } /** * PocketBase defines a PocketBase app launcher. @@ -6632,8 +6632,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 _subWBxOH = appWrapper - interface PocketBase extends _subWBxOH { + type _subkOzHL = appWrapper + interface PocketBase extends _subkOzHL { /** * RootCmd is the main console command */ @@ -6820,148 +6820,6 @@ namespace template { } } -/** - * Package io provides basic interfaces to I/O primitives. - * Its primary job is to wrap existing implementations of such primitives, - * such as those in package os, into shared public interfaces that - * abstract the functionality, plus some other related primitives. - * - * Because these interfaces and primitives wrap lower-level operations with - * various implementations, unless otherwise informed clients should not - * assume they are safe for parallel execution. - */ -namespace io { - /** - * Reader is the interface that wraps the basic Read method. - * - * Read reads up to len(p) bytes into p. It returns the number of bytes - * read (0 <= n <= len(p)) and any error encountered. Even if Read - * returns n < len(p), it may use all of p as scratch space during the call. - * If some data is available but not len(p) bytes, Read conventionally - * returns what is available instead of waiting for more. - * - * When Read encounters an error or end-of-file condition after - * successfully reading n > 0 bytes, it returns the number of - * bytes read. It may return the (non-nil) error from the same call - * or return the error (and n == 0) from a subsequent call. - * An instance of this general case is that a Reader returning - * a non-zero number of bytes at the end of the input stream may - * return either err == EOF or err == nil. The next Read should - * return 0, EOF. - * - * Callers should always process the n > 0 bytes returned before - * considering the error err. Doing so correctly handles I/O errors - * that happen after reading some bytes and also both of the - * allowed EOF behaviors. - * - * If len(p) == 0, Read should always return n == 0. It may return a - * non-nil error if some error condition is known, such as EOF. - * - * Implementations of Read are discouraged from returning a - * zero byte count with a nil error, except when len(p) == 0. - * Callers should treat a return of 0 and nil as indicating that - * nothing happened; in particular it does not indicate EOF. - * - * Implementations must not retain p. - */ - interface Reader { - [key:string]: any; - read(p: string|Array): number - } - /** - * ReadSeekCloser is the interface that groups the basic Read, Seek and Close - * methods. - */ - interface ReadSeekCloser { - [key:string]: any; - } -} - -/** - * 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 ReadAt. - * The result is unaffected by any method calls except 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 ReadByte in implementing the io.ByteScanner interface. - */ - unreadByte(): void - } - interface Reader { - /** - * ReadRune implements the io.RuneReader interface. - */ - readRune(): [number, number] - } - interface Reader { - /** - * UnreadRune complements 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 @@ -7831,6 +7689,63 @@ namespace context { } } +/** + * Package io provides basic interfaces to I/O primitives. + * Its primary job is to wrap existing implementations of such primitives, + * such as those in package os, into shared public interfaces that + * abstract the functionality, plus some other related primitives. + * + * Because these interfaces and primitives wrap lower-level operations with + * various implementations, unless otherwise informed clients should not + * assume they are safe for parallel execution. + */ +namespace io { + /** + * Reader is the interface that wraps the basic Read method. + * + * Read reads up to len(p) bytes into p. It returns the number of bytes + * read (0 <= n <= len(p)) and any error encountered. Even if Read + * returns n < len(p), it may use all of p as scratch space during the call. + * If some data is available but not len(p) bytes, Read conventionally + * returns what is available instead of waiting for more. + * + * When Read encounters an error or end-of-file condition after + * successfully reading n > 0 bytes, it returns the number of + * bytes read. It may return the (non-nil) error from the same call + * or return the error (and n == 0) from a subsequent call. + * An instance of this general case is that a Reader returning + * a non-zero number of bytes at the end of the input stream may + * return either err == EOF or err == nil. The next Read should + * return 0, EOF. + * + * Callers should always process the n > 0 bytes returned before + * considering the error err. Doing so correctly handles I/O errors + * that happen after reading some bytes and also both of the + * allowed EOF behaviors. + * + * If len(p) == 0, Read should always return n == 0. It may return a + * non-nil error if some error condition is known, such as EOF. + * + * Implementations of Read are discouraged from returning a + * zero byte count with a nil error, except when len(p) == 0. + * Callers should treat a return of 0 and nil as indicating that + * nothing happened; in particular it does not indicate EOF. + * + * Implementations must not retain p. + */ + interface Reader { + [key:string]: any; + read(p: string|Array): number + } + /** + * ReadSeekCloser is the interface that groups the basic Read, Seek and Close + * methods. + */ + interface ReadSeekCloser { + [key:string]: any; + } +} + /** * Package fs defines basic interfaces to a file system. * A file system can be provided by the host operating system @@ -8026,2440 +7941,2525 @@ namespace fs { } /** - * 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. + * Package bytes implements functions for the manipulation of byte slices. + * It is analogous to the facilities of the [strings] package. */ -namespace sql { +namespace bytes { /** - * TxOptions holds the transaction options to be used in DB.BeginTx. + * 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 TxOptions { - /** - * Isolation is the transaction isolation level. - * If zero, the driver or database's default level is used. - */ - isolation: IsolationLevel - readOnly: boolean - } - /** - * 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 Commit or - * 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 SetMaxIdleConns. - */ - interface DB { - } - interface DB { - /** - * PingContext verifies a connection to the database is still alive, - * establishing a connection if necessary. - */ - pingContext(ctx: context.Context): void - } - interface DB { - /** - * 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 - * PingContext. - */ - ping(): void - } - interface DB { - /** - * 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. - */ - close(): void - } - interface DB { - /** - * SetMaxIdleConns sets the maximum number of connections in the idle - * connection pool. - * - * If MaxOpenConns is greater than 0 but less than the new MaxIdleConns, - * then the new MaxIdleConns will be reduced to match the MaxOpenConns limit. - * - * If n <= 0, no idle connections are retained. - * - * 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. - * - * 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. - * - * If n <= 0, then there is no limit on the number of open connections. - * The default is 0 (unlimited). - */ - setMaxOpenConns(n: number): void + interface Reader { } - interface DB { + interface Reader { /** - * 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. + * Len returns the number of bytes of the unread portion of the + * slice. */ - setConnMaxLifetime(d: time.Duration): void + len(): number } - interface DB { + interface Reader { /** - * 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. + * Size returns the original length of the underlying byte slice. + * Size is the number of bytes available for reading via ReadAt. + * The result is unaffected by any method calls except Reset. */ - setConnMaxIdleTime(d: time.Duration): void + size(): number } - interface DB { + interface Reader { /** - * Stats returns database statistics. + * Read implements the io.Reader interface. */ - stats(): DBStats + read(b: string|Array): number } - interface DB { + interface Reader { /** - * 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 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. + * ReadAt implements the io.ReaderAt interface. */ - prepareContext(ctx: context.Context, query: string): (Stmt) + readAt(b: string|Array, off: number): number } - interface DB { + interface Reader { /** - * 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 Close method - * when the statement is no longer needed. - * - * Prepare uses context.Background internally; to specify the context, use - * PrepareContext. + * ReadByte implements the io.ByteReader interface. */ - prepare(query: string): (Stmt) + readByte(): number } - interface DB { + interface Reader { /** - * ExecContext executes a query without returning any rows. - * The args are for any placeholder parameters in the query. + * UnreadByte complements ReadByte in implementing the io.ByteScanner interface. */ - execContext(ctx: context.Context, query: string, ...args: any[]): Result + unreadByte(): void } - interface DB { + 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 - * ExecContext. + * ReadRune implements the io.RuneReader interface. */ - exec(query: string, ...args: any[]): Result + readRune(): [number, 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. + * UnreadRune complements ReadRune in implementing the io.RuneScanner interface. */ - queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows) + unreadRune(): void } - 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 - * QueryContext. + * Seek implements the io.Seeker interface. */ - query(query: string, ...args: any[]): (Rows) + seek(offset: number, whence: number): number } - 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's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards - * the rest. + * WriteTo implements the io.WriterTo interface. */ - queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row) + writeTo(w: io.Writer): number } - 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's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards - * the rest. - * - * QueryRow uses context.Background internally; to specify the context, use - * QueryRowContext. + * Reset resets the Reader to be reading from b. */ - queryRow(query: string, ...args: any[]): (Row) + reset(b: string|Array): void } - interface DB { - /** - * 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. - * - * 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. - */ - beginTx(ctx: context.Context, opts: TxOptions): (Tx) +} + +/** + * 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. + */ +/** + * Copyright 2023 The Go Authors. All rights reserved. + * Use of this source code is governed by a BSD-style + * license that can be found in the LICENSE file. + */ +namespace multipart { + /** + * A FileHeader describes a file part of a multipart request. + */ + interface FileHeader { + filename: string + header: textproto.MIMEHeader + size: number } - interface DB { + interface FileHeader { /** - * Begin starts a transaction. The default isolation level is dependent on - * the driver. - * - * Begin uses context.Background internally; to specify the context, use - * BeginTx. + * Open opens and returns the FileHeader's associated File. */ - begin(): (Tx) - } - interface DB { - /** - * Driver returns the database's underlying driver. - */ - driver(): any - } - interface DB { - /** - * 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. - */ - conn(ctx: context.Context): (Conn) + 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 + * + * Starting with Go 1.6, the http package has transparent support for the + * HTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2 + * can do so by setting Transport.TLSNextProto (for clients) or + * Server.TLSNextProto (for servers) to a non-nil, empty + * map. 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 + * ``` + * + * Please report any issues before disabling HTTP/2 support: https://golang.org/s/http2bug + * + * The http package's Transport and Server both automatically enable + * HTTP/2 support for simple configurations. To enable HTTP/2 for more + * complex configurations, to use lower-level HTTP/2 features, or to use + * a newer version of Go's http2 package, import "golang.org/x/net/http2" + * directly and use its ConfigureTransport and/or ConfigureServer + * functions. Manually configuring HTTP/2 via the golang.org/x/net/http2 + * package takes precedence over the net/http package's built-in HTTP/2 + * support. + */ +namespace http { + // @ts-ignore + import mathrand = rand + // @ts-ignore + import urlpkg = url /** - * Tx is an in-progress database transaction. - * - * A transaction must end with a call to Commit or Rollback. - * - * After a call to Commit or Rollback, all operations on the - * transaction fail with ErrTxDone. + * A Request represents an HTTP request received by a server + * or to be sent by a client. * - * The statements prepared for a transaction by calling - * the transaction's Prepare or Stmt methods are closed - * by the call to Commit or Rollback. + * 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 Tx { - } - interface Tx { - /** - * Commit commits the transaction. - */ - commit(): void - } - interface Tx { + interface Request { /** - * Rollback aborts the transaction. + * Method specifies the HTTP method (GET, POST, PUT, etc.). + * For client requests, an empty string means GET. + * + * Go's HTTP client does not support sending a request with + * the CONNECT method. See the documentation on Transport for + * details. */ - rollback(): void - } - interface Tx { + method: string /** - * 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. + * URL specifies either the URI being requested (for server + * requests) or the URL to access (for client requests). * - * To use an existing prepared statement on this transaction, see Tx.Stmt. + * 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) * - * 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. + * 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. */ - prepareContext(ctx: context.Context, query: string): (Stmt) - } - interface Tx { + url?: url.URL /** - * 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. + * The protocol version for incoming server requests. * - * Prepare uses context.Background internally; to specify the context, use - * PrepareContext. + * 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. */ - prepare(query: string): (Stmt) - } - interface Tx { + proto: string // "HTTP/1.0" + protoMajor: number // 1 + protoMinor: number // 0 /** - * StmtContext returns a transaction-specific prepared statement from - * an existing statement. + * Header contains the request header fields either received + * by the server or to be sent by the client. * - * Example: + * If a server received a request with header lines, * * ``` - * 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) + * Host: example.com + * accept-encoding: gzip, deflate + * Accept-Language: en-us + * fOO: Bar + * foo: two * ``` * - * The provided context is used for the preparation of the statement, not for the - * execution of the statement. + * then * - * The returned statement operates within the transaction and will be closed - * when the transaction has been committed or rolled back. - */ - stmtContext(ctx: context.Context, stmt: Stmt): (Stmt) - } - interface Tx { - /** - * Stmt returns a transaction-specific prepared statement from - * an existing statement. + * ``` + * Header = map[string][]string{ + * "Accept-Encoding": {"gzip, deflate"}, + * "Accept-Language": {"en-us"}, + * "Foo": {"Bar", "two"}, + * } + * ``` * - * Example: + * For incoming requests, the Host header is promoted to the + * Request.Host field and removed from the Header map. * - * ``` - * 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. + * 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. * - * Stmt uses context.Background internally; to specify the context, use - * StmtContext. - */ - stmt(stmt: Stmt): (Stmt) - } - interface Tx { - /** - * ExecContext executes a query that doesn't return rows. - * For example: an INSERT and UPDATE. + * 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. */ - execContext(ctx: context.Context, query: string, ...args: any[]): Result - } - interface Tx { + header: Header /** - * Exec executes a query that doesn't return rows. - * For example: an INSERT and UPDATE. + * Body is the request's body. * - * Exec uses context.Background internally; to specify the context, use - * ExecContext. + * 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. + * + * 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. */ - exec(query: string, ...args: any[]): Result - } - interface Tx { + body: io.ReadCloser /** - * QueryContext executes a query that returns rows, typically a SELECT. + * 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. */ - queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows) - } - interface Tx { + getBody: () => io.ReadCloser /** - * Query executes a query that returns rows, typically a SELECT. + * 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. * - * Query uses context.Background internally; to specify the context, use - * QueryContext. + * For client requests, a value of 0 with a non-nil Body is + * also treated as unknown. */ - query(query: string, ...args: any[]): (Rows) - } - interface Tx { + contentLength: 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 - * Row's Scan method is called. - * If the query selects no rows, the *Row's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards - * the rest. + * 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. */ - queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row) - } - interface Tx { + transferEncoding: Array /** - * 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's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards - * the rest. + * 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). * - * QueryRow uses context.Background internally; to specify the context, use - * QueryRowContext. - */ - 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 { - /** - * ExecContext executes a prepared statement with the given arguments and - * returns a Result summarizing the effect of the statement. + * For server requests, the HTTP server handles this automatically + * and this field is not needed by Handlers. + * + * For client requests, setting this field prevents re-use of + * TCP connections between requests to the same hosts, as if + * Transport.DisableKeepAlives were set. */ - execContext(ctx: context.Context, ...args: any[]): Result - } - interface Stmt { + close: boolean /** - * Exec executes a prepared statement with the given arguments and - * returns a Result summarizing the effect of the statement. + * 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. * - * Exec uses context.Background internally; to specify the context, use - * ExecContext. + * 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. */ - exec(...args: any[]): Result - } - interface Stmt { + host: string /** - * QueryContext executes a prepared query statement with the given arguments - * and returns the query results as a *Rows. + * 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. */ - queryContext(ctx: context.Context, ...args: any[]): (Rows) - } - interface Stmt { + form: url.Values /** - * Query executes a prepared query statement with the given arguments - * and returns the query results as a *Rows. + * PostForm contains the parsed form data from PATCH, POST + * or PUT body parameters. * - * Query uses context.Background internally; to specify the context, use - * QueryContext. + * This field is only available after ParseForm is called. + * The HTTP client ignores PostForm and uses Body instead. */ - query(...args: any[]): (Rows) - } - interface Stmt { + postForm: url.Values /** - * 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's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards - * the rest. + * 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. */ - queryRowContext(ctx: context.Context, ...args: any[]): (Row) - } - interface Stmt { + multipartForm?: multipart.Form /** - * 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's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards - * the rest. + * Trailer specifies additional headers that are sent after the request + * body. * - * Example usage: + * 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. * - * ``` - * var name string - * err := nameByUseridStmt.QueryRow(id).Scan(&name) - * ``` + * 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. * - * QueryRow uses context.Background internally; to specify the context, use - * QueryRowContext. + * Few HTTP clients, servers, or proxies support HTTP trailers. */ - queryRow(...args: any[]): (Row) - } - interface Stmt { + trailer: Header /** - * Close closes the statement. + * 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. */ - close(): void - } - /** - * Rows is the result of a query. Its cursor starts before the first row - * of the result set. Use Next to advance from row to row. - */ - interface Rows { - } - interface Rows { + remoteAddr: string /** - * Next prepares the next result row for reading with the Scan method. It - * returns true on success, or false if there is no next result row or an error - * happened while preparing it. Err should be consulted to distinguish between - * the two cases. - * - * Every call to Scan, even the first one, must be preceded by a call to Next. + * 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. */ - next(): boolean - } - interface Rows { - /** - * 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 Err method should be consulted - * to distinguish between the two cases. - * - * After calling NextResultSet, the Next method should always be called before - * scanning. If there are further result sets they may not have rows in the result - * set. - */ - nextResultSet(): boolean - } - interface Rows { + requestURI: string /** - * Err returns the error, if any, that was encountered during iteration. - * Err may be called after an explicit or implicit Close. + * 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. */ - err(): void - } - interface Rows { + tls?: any /** - * Columns returns the column names. - * Columns returns an error if the rows are closed. + * 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. */ - columns(): Array - } - interface Rows { + cancel: undefined /** - * ColumnTypes returns column information such as column type, length, - * and nullable. Some information may not be available from some drivers. + * Response is the redirect response which caused this request + * to be created. This field is only populated during client + * redirects. */ - columnTypes(): Array<(ColumnType | undefined)> + response?: Response } - interface Rows { + interface Request { /** - * 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. - * - * Scan converts columns read from the database into the following - * common Go types and special types provided by the sql package: - * - * ``` - * *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) - * ``` - * - * 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. - * - * 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. + * Context returns the request's context. To change the context, use + * Clone or WithContext. * - * 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. + * The returned context is always non-nil; it defaults to the + * background context. * - * 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. + * For outgoing client requests, the context controls cancellation. * - * Source values of type bool may be scanned into types *bool, - * *interface{}, *string, *[]byte, or *RawBytes. + * 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. + */ + context(): context.Context + } + interface Request { + /** + * WithContext returns a shallow copy of r with its context changed + * to ctx. The provided ctx must be non-nil. * - * For scanning into *bool, the source may be true, false, 1, 0, or - * string inputs parseable by strconv.ParseBool. + * 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. * - * 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. + * 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. + */ + withContext(ctx: context.Context): (Request) + } + interface Request { + /** + * Clone returns a deep copy of r with its context changed to ctx. + * The provided ctx must be non-nil. * - * If any of the first arguments implementing Scanner returns an error, - * that error will be wrapped in the returned error. + * 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. */ - scan(...dest: any[]): void + clone(ctx: context.Context): (Request) } - interface Rows { + interface Request { /** - * Close closes the Rows, preventing further enumeration. If 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 Err. Close is idempotent and does not affect the result of Err. + * ProtoAtLeast reports whether the HTTP protocol used + * in the request is at least major.minor. */ - close(): void + protoAtLeast(major: number): boolean } - /** - * A Result summarizes an executed SQL command. - */ - interface Result { - [key:string]: any; + interface Request { /** - * 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. + * UserAgent returns the client's User-Agent, if sent in the request. */ - lastInsertId(): number + userAgent(): string + } + interface Request { /** - * RowsAffected returns the number of rows affected by an - * update, insert, or delete. Not every database or database - * driver may support this. + * Cookies parses and returns the HTTP cookies sent with the request. */ - rowsAffected(): number + cookies(): Array<(Cookie | undefined)> } -} - -/** - * 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. - */ -/** - * Copyright 2023 The Go Authors. All rights reserved. - * Use of this source code is governed by a BSD-style - * license that can be found in the LICENSE file. - */ -namespace multipart { - /** - * A FileHeader describes a file part of a multipart request. - */ - interface FileHeader { - filename: string - header: textproto.MIMEHeader - size: number + interface Request { + /** + * 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. + */ + cookie(name: string): (Cookie) } - interface FileHeader { + interface Request { /** - * Open opens and returns the FileHeader's associated File. + * 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. */ - open(): File + addCookie(c: Cookie): void + } + interface Request { + /** + * 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"]. + */ + referer(): string + } + interface Request { + /** + * 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 ParseMultipartForm to + * process the request body as a stream. + */ + multipartReader(): (multipart.Reader) + } + interface Request { + /** + * 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 TransferEncoding + * hasn't been set to "identity", Write adds "Transfer-Encoding: + * chunked" to the header. Body is closed after it is sent. + */ + write(w: io.Writer): void + } + interface Request { + /** + * WriteProxy is like Write but writes the request in the form + * expected by an HTTP proxy. In particular, 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 } -} - -/** - * 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 - * - * Starting with Go 1.6, the http package has transparent support for the - * HTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2 - * can do so by setting Transport.TLSNextProto (for clients) or - * Server.TLSNextProto (for servers) to a non-nil, empty - * map. 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 - * ``` - * - * Please report any issues before disabling HTTP/2 support: https://golang.org/s/http2bug - * - * The http package's Transport and Server both automatically enable - * HTTP/2 support for simple configurations. To enable HTTP/2 for more - * complex configurations, to use lower-level HTTP/2 features, or to use - * a newer version of Go's http2 package, import "golang.org/x/net/http2" - * directly and use its ConfigureTransport and/or ConfigureServer - * functions. Manually configuring HTTP/2 via the golang.org/x/net/http2 - * package takes precedence over the net/http package's built-in HTTP/2 - * support. - */ -namespace http { - // @ts-ignore - import mathrand = rand - // @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 { /** - * Method specifies the HTTP method (GET, POST, PUT, etc.). - * For client requests, an empty string means GET. - * - * Go's HTTP client does not support sending a request with - * the CONNECT method. See the documentation on Transport for - * details. + * 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. */ - method: string + basicAuth(): [string, boolean] + } + interface Request { /** - * URL specifies either the URI being requested (for server - * requests) or the URL to access (for client requests). - * - * 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) + * SetBasicAuth sets the request's Authorization header to use HTTP + * Basic Authentication with the provided username and password. * - * 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 + * With HTTP Basic Authentication the provided username and password + * are not encrypted. It should generally only be used in an HTTPS * request. - */ - url?: url.URL - /** - * 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. + * 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. */ - proto: string // "HTTP/1.0" - protoMajor: number // 1 - protoMinor: number // 0 + setBasicAuth(username: string): void + } + interface Request { /** - * 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 - * ``` + * ParseForm populates r.Form and r.PostForm. * - * then + * For all requests, ParseForm parses the raw query from the URL and updates + * r.Form. * - * ``` - * Header = map[string][]string{ - * "Accept-Encoding": {"gzip, deflate"}, - * "Accept-Language": {"en-us"}, - * "Foo": {"Bar", "two"}, - * } - * ``` + * 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. * - * For incoming requests, the Host header is promoted to the - * Request.Host field and removed from the Header map. + * If the request Body's size has not already been limited by MaxBytesReader, + * the size is capped at 10MB. * - * 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. + * 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. * - * 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. + * ParseMultipartForm calls ParseForm automatically. + * ParseForm is idempotent. */ - header: Header + parseForm(): void + } + interface Request { /** - * 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. - * - * 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. + * 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 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. */ - body: io.ReadCloser + parseMultipartForm(maxMemory: number): void + } + interface Request { /** - * 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. + * FormValue returns the first value for the named component of the query. + * POST and PUT body parameters take precedence over URL query string values. + * FormValue calls ParseMultipartForm and 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. */ - getBody: () => io.ReadCloser + formValue(key: string): string + } + interface Request { /** - * 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. + * PostFormValue returns the first value for the named component of the POST, + * PATCH, or PUT request body. URL query parameters are ignored. + * PostFormValue calls ParseMultipartForm and ParseForm if necessary and ignores + * any errors returned by these functions. + * If key is not present, PostFormValue returns the empty string. */ - contentLength: number + postFormValue(key: string): string + } + interface Request { /** - * 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. + * FormFile returns the first file for the provided form key. + * FormFile calls ParseMultipartForm and ParseForm if necessary. */ - transferEncoding: Array + formFile(key: string): [multipart.File, (multipart.FileHeader)] + } + /** + * A ResponseWriter interface is used by an HTTP handler to + * construct an HTTP response. + * + * A ResponseWriter may not be used after the Handler.ServeHTTP method + * has returned. + */ + interface ResponseWriter { + [key:string]: any; /** - * 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). + * Header returns the header map that will be sent by + * WriteHeader. The Header map also is the mechanism with which + * Handlers can set HTTP trailers. * - * For server requests, the HTTP server handles this automatically - * and this field is not needed by Handlers. + * Changing the header map after a call to WriteHeader (or + * Write) has no effect unless the HTTP status code was of the + * 1xx class or the modified headers are trailers. * - * For client requests, setting this field prevents re-use of - * TCP connections between requests to the same hosts, as if - * Transport.DisableKeepAlives were set. - */ - close: boolean - /** - * 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. + * 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 Write, + * is to prefix the Header map keys with the TrailerPrefix + * constant value. See TrailerPrefix. * - * 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. - */ - host: string - /** - * 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. + * To suppress automatic response headers (such as "Date"), set + * their value to nil. */ - form: url.Values + header(): Header /** - * PostForm contains the parsed form data from PATCH, POST - * or PUT body parameters. + * Write writes the data to the connection as part of an HTTP reply. * - * This field is only available after ParseForm is called. - * The HTTP client ignores PostForm and uses Body instead. - */ - postForm: url.Values - /** - * 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. + * If 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. */ - multipartForm?: multipart.Form + write(_arg0: string|Array): number /** - * Trailer specifies additional headers that are sent after the request - * body. + * WriteHeader sends an HTTP response header with the provided + * status code. * - * 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. + * 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. * - * 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. + * 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. * - * Few HTTP clients, servers, or proxies support HTTP trailers. + * 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. */ - trailer: Header + writeHeader(statusCode: number): void + } + /** + * A Server defines parameters for running an HTTP server. + * The zero value for Server is a valid configuration. + */ + interface Server { /** - * 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. + * 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. */ - remoteAddr: string + addr: string + handler: Handler // handler to invoke, http.DefaultServeMux if nil /** - * 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. + * DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler, + * otherwise responds with 200 OK and Content-Length: 0. */ - requestURI: string + disableGeneralOptionsHandler: boolean /** - * 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. + * 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. */ - tls?: any + tlsConfig?: any /** - * 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. + * ReadTimeout is the maximum duration for reading the entire + * request, including the body. A zero or negative value means + * there will be no timeout. * - * 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. + * 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. */ - cancel: undefined + readTimeout: time.Duration /** - * Response is the redirect response which caused this request - * to be created. This field is only populated during client - * redirects. + * 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 ReadHeaderTimeout + * is zero, the value of ReadTimeout is used. If both are + * zero, there is no timeout. */ - response?: Response - } - interface Request { + readHeaderTimeout: time.Duration /** - * Context returns the request's context. To change the context, use - * Clone or 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. + * 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. */ - context(): context.Context - } - interface Request { + writeTimeout: time.Duration /** - * 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. - * - * 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. + * IdleTimeout is the maximum amount of time to wait for the + * next request when keep-alives are enabled. If IdleTimeout + * is zero, the value of ReadTimeout is used. If both are + * zero, there is no timeout. */ - withContext(ctx: context.Context): (Request) - } - interface Request { + idleTimeout: time.Duration /** - * Clone returns a deep copy of r with its context changed to ctx. - * The provided ctx must be non-nil. - * - * 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. + * 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. */ - clone(ctx: context.Context): (Request) - } - interface Request { + maxHeaderBytes: number /** - * ProtoAtLeast reports whether the HTTP protocol used - * in the request is at least major.minor. + * 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. */ - protoAtLeast(major: number): boolean - } - interface Request { + tlsNextProto: _TygojaDict /** - * UserAgent returns the client's User-Agent, if sent in the request. + * ConnState specifies an optional callback function that is + * called when a client connection changes state. See the + * ConnState type and associated constants for details. */ - userAgent(): string - } - interface Request { + connState: (_arg0: net.Conn, _arg1: ConnState) => void /** - * Cookies parses and returns the HTTP cookies sent with the request. + * 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. */ - cookies(): Array<(Cookie | undefined)> - } - interface Request { + errorLog?: any /** - * 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. + * 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. */ - cookie(name: string): (Cookie) + 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. + */ + connContext: (ctx: context.Context, c: net.Conn) => context.Context } - interface Request { + interface Server { /** - * 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. + * Close immediately closes all active net.Listeners and any + * connections in state StateNew, StateActive, or StateIdle. For a + * graceful shutdown, use 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). */ - addCookie(c: Cookie): void + close(): void } - interface Request { + interface Server { /** - * Referer returns the referring URL, if sent in the request. + * 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). * - * 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"]. + * When Shutdown is called, Serve, 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 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. */ - referer(): string + shutdown(ctx: context.Context): void } - interface Request { + interface Server { /** - * 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 ParseMultipartForm to - * process the request body as a stream. + * RegisterOnShutdown registers a function to call on 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. */ - multipartReader(): (multipart.Reader) + registerOnShutdown(f: () => void): void } - interface Request { + interface Server { /** - * 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: + * ListenAndServe listens on the TCP network address srv.Addr and then + * calls Serve to handle requests on incoming connections. + * Accepted connections are configured to enable TCP keep-alives. * - * ``` - * Host - * URL - * Method (defaults to "GET") - * Header - * ContentLength - * TransferEncoding - * Body - * ``` + * If srv.Addr is blank, ":http" is used. * - * If Body is present, Content-Length is <= 0 and TransferEncoding - * hasn't been set to "identity", Write adds "Transfer-Encoding: - * chunked" to the header. Body is closed after it is sent. + * ListenAndServe always returns a non-nil error. After Shutdown or Close, + * the returned error is ErrServerClosed. */ - write(w: io.Writer): void + listenAndServe(): void } - interface Request { + interface Server { /** - * WriteProxy is like Write but writes the request in the form - * expected by an HTTP proxy. In particular, 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. + * Serve accepts incoming connections on the Listener l, creating a + * new service goroutine for each. The service goroutines read requests and + * then call srv.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 Shutdown or Close, the returned error is ErrServerClosed. */ - writeProxy(w: io.Writer): void + serve(l: net.Listener): void } - interface Request { + interface Server { /** - * 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. + * 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 srv.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 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. + * + * ServeTLS always returns a non-nil error. After Shutdown or Close, the + * returned error is ErrServerClosed. */ - basicAuth(): [string, boolean] + serveTLS(l: net.Listener, certFile: string): void } - interface Request { + interface Server { /** - * 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. - * - * 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. + * 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. */ - setBasicAuth(username: string): void + setKeepAlivesEnabled(v: boolean): void } - interface Request { + interface Server { /** - * 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. + * ListenAndServeTLS listens on the TCP network address srv.Addr and + * then calls ServeTLS to handle requests on incoming TLS connections. + * Accepted connections are configured to enable TCP keep-alives. * - * If the request Body's size has not already been limited by MaxBytesReader, - * the size is capped at 10MB. + * 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. * - * 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. + * If srv.Addr is blank, ":https" is used. * - * ParseMultipartForm calls ParseForm automatically. - * ParseForm is idempotent. + * ListenAndServeTLS always returns a non-nil error. After Shutdown or + * Close, the returned error is ErrServerClosed. */ - parseForm(): void + listenAndServeTLS(certFile: string): void } - interface Request { +} + +/** + * Package exec runs external commands. It wraps os.StartProcess to make it + * easier to remap stdin and stdout, connect I/O with pipes, and do other + * adjustments. + * + * Unlike the "system" library call from C and other languages, the + * os/exec package intentionally does not invoke the system shell and + * does not expand any glob patterns or handle other expansions, + * pipelines, or redirections typically done by shells. The package + * behaves more like C's "exec" family of functions. To expand glob + * patterns, either call the shell directly, taking care to escape any + * dangerous input, or use the path/filepath package's Glob function. + * To expand environment variables, use package os's ExpandEnv. + * + * Note that the examples in this package assume a Unix system. + * They may not run on Windows, and they do not run in the Go Playground + * used by golang.org and godoc.org. + * + * # Executables in the current directory + * + * The functions Command and LookPath look for a program + * in the directories listed in the current path, following the + * conventions of the host operating system. + * Operating systems have for decades included the current + * directory in this search, sometimes implicitly and sometimes + * configured explicitly that way by default. + * Modern practice is that including the current directory + * is usually unexpected and often leads to security problems. + * + * To avoid those security problems, as of Go 1.19, this package will not resolve a program + * using an implicit or explicit path entry relative to the current directory. + * That is, if you run exec.LookPath("go"), it will not successfully return + * ./go on Unix nor .\go.exe on Windows, no matter how the path is configured. + * Instead, if the usual path algorithms would result in that answer, + * these functions return an error err satisfying errors.Is(err, ErrDot). + * + * For example, consider these two program snippets: + * + * ``` + * path, err := exec.LookPath("prog") + * if err != nil { + * log.Fatal(err) + * } + * use(path) + * ``` + * + * and + * + * ``` + * cmd := exec.Command("prog") + * if err := cmd.Run(); err != nil { + * log.Fatal(err) + * } + * ``` + * + * These will not find and run ./prog or .\prog.exe, + * no matter how the current path is configured. + * + * Code that always wants to run a program from the current directory + * can be rewritten to say "./prog" instead of "prog". + * + * Code that insists on including results from relative path entries + * can instead override the error using an errors.Is check: + * + * ``` + * path, err := exec.LookPath("prog") + * if errors.Is(err, exec.ErrDot) { + * err = nil + * } + * if err != nil { + * log.Fatal(err) + * } + * use(path) + * ``` + * + * and + * + * ``` + * cmd := exec.Command("prog") + * if errors.Is(cmd.Err, exec.ErrDot) { + * cmd.Err = nil + * } + * if err := cmd.Run(); err != nil { + * log.Fatal(err) + * } + * ``` + * + * Setting the environment variable GODEBUG=execerrdot=0 + * disables generation of ErrDot entirely, temporarily restoring the pre-Go 1.19 + * behavior for programs that are unable to apply more targeted fixes. + * A future version of Go may remove support for this variable. + * + * Before adding such overrides, make sure you understand the + * security implications of doing so. + * See https://go.dev/blog/path-security for more information. + */ +namespace exec { + /** + * Cmd represents an external command being prepared or run. + * + * A Cmd cannot be reused after calling its Run, Output or CombinedOutput + * methods. + */ + interface Cmd { /** - * 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 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. + * 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. */ - parseMultipartForm(maxMemory: number): void - } - interface Request { + path: string /** - * FormValue returns the first value for the named component of the query. - * POST and PUT body parameters take precedence over URL query string values. - * FormValue calls ParseMultipartForm and 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. + * 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. */ - formValue(key: string): string - } - interface Request { + args: Array /** - * PostFormValue returns the first value for the named component of the POST, - * PATCH, or PUT request body. URL query parameters are ignored. - * PostFormValue calls ParseMultipartForm and ParseForm if necessary and ignores - * any errors returned by these functions. - * If key is not present, PostFormValue returns the empty string. + * 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. */ - postFormValue(key: string): string - } - interface Request { + env: Array /** - * FormFile returns the first file for the provided form key. - * FormFile calls ParseMultipartForm and ParseForm if necessary. + * 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. */ - formFile(key: string): [multipart.File, (multipart.FileHeader)] - } - /** - * A ResponseWriter interface is used by an HTTP handler to - * construct an HTTP response. - * - * A ResponseWriter may not be used after the Handler.ServeHTTP method - * has returned. - */ - interface ResponseWriter { - [key:string]: any; + dir: string /** - * Header returns the header map that will be sent by - * WriteHeader. The Header map also is the mechanism with which - * Handlers can set HTTP trailers. + * Stdin specifies the process's standard input. * - * Changing the header map after a call to WriteHeader (or - * Write) has no effect unless the HTTP status code was of the - * 1xx class or the modified headers are trailers. + * If Stdin is nil, the process reads from the null device (os.DevNull). * - * 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 Write, - * is to prefix the Header map keys with the TrailerPrefix - * constant value. See TrailerPrefix. + * If Stdin is an *os.File, the process's standard input is connected + * directly to that file. * - * To suppress automatic response headers (such as "Date"), set - * their value to nil. + * 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. */ - header(): Header + stdin: io.Reader /** - * Write writes the data to the connection as part of an HTTP reply. - * - * If 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. + * Stdout and Stderr specify the process's standard output and error. * - * 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. - */ - write(_arg0: string|Array): number - /** - * WriteHeader sends an HTTP response header with the provided - * status code. + * If either is nil, Run connects the corresponding file descriptor + * to the null device (os.DevNull). * - * 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. + * If either is an *os.File, the corresponding output from the process + * is connected directly to that file. * - * 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. + * 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. * - * 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. + * 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. */ - writeHeader(statusCode: number): void - } - /** - * A Server defines parameters for running an HTTP server. - * The zero value for Server is a valid configuration. - */ - interface Server { + stdout: io.Writer + stderr: io.Writer /** - * 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. + * 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. */ - addr: string - handler: Handler // handler to invoke, http.DefaultServeMux if nil + extraFiles: Array<(os.File | undefined)> /** - * DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler, - * otherwise responds with 200 OK and Content-Length: 0. + * SysProcAttr holds optional, operating system-specific attributes. + * Run passes it to os.StartProcess as the os.ProcAttr's Sys field. */ - disableGeneralOptionsHandler: boolean + sysProcAttr?: syscall.SysProcAttr /** - * 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. + * Process is the underlying process, once started. */ - tlsConfig?: any + process?: os.Process /** - * 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. + * ProcessState contains information about an exited process. + * If the process was started successfully, Wait or Run will + * populate its ProcessState when the command completes. */ - readTimeout: time.Duration + processState?: os.ProcessState + err: Error // LookPath error, if any. /** - * 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 ReadHeaderTimeout - * is zero, the value of ReadTimeout is used. If both are - * zero, there is no timeout. + * 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. */ - readHeaderTimeout: time.Duration + cancel: () => void /** - * 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. + * 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. */ - writeTimeout: time.Duration + waitDelay: time.Duration + } + interface Cmd { /** - * IdleTimeout is the maximum amount of time to wait for the - * next request when keep-alives are enabled. If IdleTimeout - * is zero, the value of ReadTimeout is used. If both are - * zero, there is no timeout. + * 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. */ - idleTimeout: time.Duration + string(): string + } + interface Cmd { /** - * 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. + * 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. */ - maxHeaderBytes: number + run(): void + } + interface Cmd { /** - * 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. + * 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 Wait method must be called in + * order to release associated system resources. */ - tlsNextProto: _TygojaDict + start(): void + } + interface Cmd { /** - * ConnState specifies an optional callback function that is - * called when a client connection changes state. See the - * ConnState type and associated constants for details. + * 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 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 releases any resources associated with the Cmd. */ - connState: (_arg0: net.Conn, _arg1: ConnState) => void + wait(): void + } + interface Cmd { /** - * 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. + * Output runs the command and returns its standard output. + * Any returned error will usually be of type *ExitError. + * If c.Stderr was nil, Output populates ExitError.Stderr. */ - errorLog?: any + output(): string|Array + } + interface Cmd { /** - * 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. + * CombinedOutput runs the command and returns its combined standard + * output and standard error. */ - baseContext: (_arg0: net.Listener) => context.Context + combinedOutput(): string|Array + } + interface Cmd { /** - * 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. + * 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 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. */ - connContext: (ctx: context.Context, c: net.Conn) => context.Context + stdinPipe(): io.WriteCloser } - interface Server { + interface Cmd { /** - * Close immediately closes all active net.Listeners and any - * connections in state StateNew, StateActive, or StateIdle. For a - * graceful shutdown, use Shutdown. - * - * Close does not attempt to close (and does not even know about) - * any hijacked connections, such as WebSockets. + * StdoutPipe returns a pipe that will be connected to the command's + * standard output when the command starts. * - * Close returns any error returned from closing the Server's - * underlying Listener(s). + * 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 Run when using StdoutPipe. + * See the example for idiomatic usage. */ - close(): void + stdoutPipe(): io.ReadCloser } - interface Server { + interface Cmd { /** - * 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). - * - * When Shutdown is called, Serve, 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 RegisterOnShutdown for a way to - * register shutdown notification functions. + * StderrPipe returns a pipe that will be connected to the command's + * standard error when the command starts. * - * Once Shutdown has been called on a server, it may not be reused; - * future calls to methods such as Serve will return ErrServerClosed. + * 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 Run when using StderrPipe. + * See the StdoutPipe example for idiomatic usage. */ - shutdown(ctx: context.Context): void + stderrPipe(): io.ReadCloser } - interface Server { + interface Cmd { /** - * RegisterOnShutdown registers a function to call on 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. + * Environ returns a copy of the environment in which the command would be run + * as it is currently configured. */ - registerOnShutdown(f: () => void): void + environ(): Array } - interface Server { +} + +/** + * 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]interface{} for JSON decoding. + * This is the default claims type if you don't supply one + */ + interface MapClaims extends _TygojaDict{} + interface MapClaims { /** - * ListenAndServe listens on the TCP network address srv.Addr and then - * calls Serve to handle requests on incoming connections. - * Accepted connections are configured to enable TCP keep-alives. - * - * If srv.Addr is blank, ":http" is used. - * - * ListenAndServe always returns a non-nil error. After Shutdown or Close, - * the returned error is ErrServerClosed. + * VerifyAudience Compares the aud claim against cmp. + * If required is false, this method will return true if the value matches or is unset */ - listenAndServe(): void + verifyAudience(cmp: string, req: boolean): boolean } - interface Server { + interface MapClaims { /** - * Serve accepts incoming connections on the Listener l, creating a - * new service goroutine for each. The service goroutines read requests and - * then call srv.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 Shutdown or Close, the returned error is ErrServerClosed. + * VerifyExpiresAt compares the exp claim against cmp (cmp <= exp). + * If req is false, it will return true, if exp is unset. */ - serve(l: net.Listener): void + verifyExpiresAt(cmp: number, req: boolean): boolean } - interface Server { + interface MapClaims { /** - * 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 srv.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 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. - * - * ServeTLS always returns a non-nil error. After Shutdown or Close, the - * returned error is ErrServerClosed. + * VerifyIssuedAt compares the exp claim against cmp (cmp >= iat). + * If req is false, it will return true, if iat is unset. */ - serveTLS(l: net.Listener, certFile: string): void + verifyIssuedAt(cmp: number, req: boolean): boolean } - interface Server { + interface MapClaims { /** - * 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. + * VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). + * If req is false, it will return true, if nbf is unset. */ - setKeepAlivesEnabled(v: boolean): void + verifyNotBefore(cmp: number, req: boolean): boolean } - interface Server { - /** - * ListenAndServeTLS listens on the TCP network address srv.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 srv.Addr is blank, ":https" is used. - * - * ListenAndServeTLS always returns a non-nil error. After Shutdown or - * Close, the returned error is ErrServerClosed. + interface MapClaims { + /** + * VerifyIssuer compares the iss claim against cmp. + * If required is false, this method will return true if the value matches or is unset */ - listenAndServeTLS(certFile: string): void + verifyIssuer(cmp: string, req: boolean): boolean + } + interface MapClaims { + /** + * Valid validates time based claims "exp, iat, nbf". + * There is no accounting for clock skew. + * As well, if any of the above claims are not in the token, it will still + * be considered a valid claim. + */ + valid(): void } } /** - * Package exec runs external commands. It wraps os.StartProcess to make it - * easier to remap stdin and stdout, connect I/O with pipes, and do other - * adjustments. - * - * Unlike the "system" library call from C and other languages, the - * os/exec package intentionally does not invoke the system shell and - * does not expand any glob patterns or handle other expansions, - * pipelines, or redirections typically done by shells. The package - * behaves more like C's "exec" family of functions. To expand glob - * patterns, either call the shell directly, taking care to escape any - * dangerous input, or use the path/filepath package's Glob function. - * To expand environment variables, use package os's ExpandEnv. - * - * Note that the examples in this package assume a Unix system. - * They may not run on Windows, and they do not run in the Go Playground - * used by golang.org and godoc.org. - * - * # Executables in the current directory - * - * The functions Command and LookPath look for a program - * in the directories listed in the current path, following the - * conventions of the host operating system. - * Operating systems have for decades included the current - * directory in this search, sometimes implicitly and sometimes - * configured explicitly that way by default. - * Modern practice is that including the current directory - * is usually unexpected and often leads to security problems. + * Package blob provides an easy and portable way to interact with blobs + * within a storage location. Subpackages contain driver implementations of + * blob for supported services. * - * To avoid those security problems, as of Go 1.19, this package will not resolve a program - * using an implicit or explicit path entry relative to the current directory. - * That is, if you run exec.LookPath("go"), it will not successfully return - * ./go on Unix nor .\go.exe on Windows, no matter how the path is configured. - * Instead, if the usual path algorithms would result in that answer, - * these functions return an error err satisfying errors.Is(err, ErrDot). + * See https://gocloud.dev/howto/blob/ for a detailed how-to guide. * - * For example, consider these two program snippets: + * *blob.Bucket implements io/fs.FS and io/fs.SubFS, so it can be used with + * functions in that package. * - * ``` - * path, err := exec.LookPath("prog") - * if err != nil { - * log.Fatal(err) - * } - * use(path) - * ``` + * # Errors * - * and + * The errors returned from this package can be inspected in several ways: * - * ``` - * cmd := exec.Command("prog") - * if err := cmd.Run(); err != nil { - * log.Fatal(err) - * } - * ``` + * The Code function from gocloud.dev/gcerrors will return an error code, also + * defined in that package, when invoked on an error. * - * These will not find and run ./prog or .\prog.exe, - * no matter how the current path is configured. + * The Bucket.ErrorAs method can retrieve the driver error underlying the returned + * error. * - * Code that always wants to run a program from the current directory - * can be rewritten to say "./prog" instead of "prog". + * # OpenCensus Integration * - * Code that insists on including results from relative path entries - * can instead override the error using an errors.Is check: + * OpenCensus supports tracing and metric collection for multiple languages and + * backend providers. See https://opencensus.io. * + * This API collects OpenCensus traces and metrics for the following methods: * ``` - * path, err := exec.LookPath("prog") - * if errors.Is(err, exec.ErrDot) { - * err = nil - * } - * if err != nil { - * log.Fatal(err) - * } - * use(path) + * - Attributes + * - Copy + * - Delete + * - ListPage + * - NewRangeReader, from creation until the call to Close. (NewReader and ReadAll + * are included because they call NewRangeReader.) + * - NewWriter, from creation until the call to Close. * ``` * - * and + * All trace and metric names begin with the package import path. + * The traces add the method name. + * For example, "gocloud.dev/blob/Attributes". + * The metrics are "completed_calls", a count of completed method calls by driver, + * method and status (error code); and "latency", a distribution of method latency + * by driver and method. + * For example, "gocloud.dev/blob/latency". * + * It also collects the following metrics: * ``` - * cmd := exec.Command("prog") - * if errors.Is(cmd.Err, exec.ErrDot) { - * cmd.Err = nil - * } - * if err := cmd.Run(); err != nil { - * log.Fatal(err) - * } + * - gocloud.dev/blob/bytes_read: the total number of bytes read, by driver. + * - gocloud.dev/blob/bytes_written: the total number of bytes written, by driver. * ``` * - * Setting the environment variable GODEBUG=execerrdot=0 - * disables generation of ErrDot entirely, temporarily restoring the pre-Go 1.19 - * behavior for programs that are unable to apply more targeted fixes. - * A future version of Go may remove support for this variable. - * - * Before adding such overrides, make sure you understand the - * security implications of doing so. - * See https://go.dev/blog/path-security for more information. + * To enable trace collection in your application, see "Configure Exporter" at + * https://opencensus.io/quickstart/go/tracing. + * To enable metric collection in your application, see "Exporting stats" at + * https://opencensus.io/quickstart/go/metrics. */ -namespace exec { +namespace blob { /** - * Cmd represents an external command being prepared or run. - * - * A Cmd cannot be reused after calling its Run, Output or CombinedOutput - * methods. + * Reader reads bytes from a blob. + * It implements io.ReadSeekCloser, and must be closed after + * reads are finished. */ - interface Cmd { + interface Reader { + } + interface Reader { /** - * Path is the path of the command to run. + * Read implements io.Reader (https://golang.org/pkg/io/#Reader). + */ + read(p: string|Array): number + } + interface Reader { + /** + * Seek implements io.Seeker (https://golang.org/pkg/io/#Seeker). + */ + seek(offset: number, whence: number): number + } + interface Reader { + /** + * Close implements io.Closer (https://golang.org/pkg/io/#Closer). + */ + close(): void + } + interface Reader { + /** + * ContentType returns the MIME type of the blob. + */ + contentType(): string + } + interface Reader { + /** + * ModTime returns the time the blob was last modified. + */ + modTime(): time.Time + } + interface Reader { + /** + * Size returns the size of the blob content in bytes. + */ + size(): number + } + interface Reader { + /** + * As converts i to driver-specific types. + * See https://gocloud.dev/concepts/as/ for background information, the "As" + * examples in this package for examples, and the driver package + * documentation for the specific types supported for that driver. + */ + as(i: { + }): boolean + } + 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. * - * This is the only field that must be set to a non-zero - * value. If Path is relative, it is evaluated relative - * to Dir. + * It implements the io.WriterTo interface. */ - path: string + writeTo(w: io.Writer): number + } + /** + * 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 + */ + contentType: string + /** + * 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. + */ + 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 /** - * 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. + * ETag for the blob; see https://en.wikipedia.org/wiki/HTTP_ETag. */ - args: Array + eTag: string + } + interface Attributes { /** - * 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. + * As converts i to driver-specific types. + * See https://gocloud.dev/concepts/as/ for background information, the "As" + * examples in this package for examples, and the driver package + * documentation for the specific types supported for that driver. */ - env: Array + as(i: { + }): boolean + } + /** + * ListObject represents a single blob returned from List. + */ + interface ListObject { /** - * 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. + * Key is the key for this blob. */ - dir: string + key: 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. + * ModTime is the time the blob was last modified. */ - stdin: io.Reader + modTime: time.Time /** - * 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. - * - * 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. + * Size is the size of the blob's content in bytes. */ - stdout: io.Writer - stderr: io.Writer + size: number /** - * 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. + * MD5 is an MD5 hash of the blob contents or nil if not available. */ - extraFiles: Array<(os.File | undefined)> + md5: string|Array /** - * SysProcAttr holds optional, operating system-specific attributes. - * Run passes it to os.StartProcess as the os.ProcAttr's Sys field. + * 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. */ - sysProcAttr?: syscall.SysProcAttr + isDir: boolean + } + interface ListObject { /** - * Process is the underlying process, once started. + * As converts i to driver-specific types. + * See https://gocloud.dev/concepts/as/ for background information, the "As" + * examples in this package for examples, and the driver package + * documentation for the specific types supported for that driver. */ - process?: os.Process + as(i: { + }): boolean + } +} + +/** + * Package types implements some commonly used db serializable types + * like datetime, json, etc. + */ +namespace types { + /** + * JsonArray defines a slice that is safe for json and db read/write. + */ + interface JsonArray extends Array{} + interface JsonArray { /** - * ProcessState contains information about an exited process. - * If the process was started successfully, Wait or Run will - * populate its ProcessState when the command completes. + * MarshalJSON implements the [json.Marshaler] interface. */ - processState?: os.ProcessState - err: Error // LookPath error, if any. + marshalJSON(): string|Array + } + interface JsonArray { /** - * 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. + * Value implements the [driver.Valuer] interface. */ - cancel: () => void + value(): any + } + interface JsonArray { /** - * 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. + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current JsonArray[T] instance. */ - waitDelay: time.Duration + scan(value: any): void } - interface Cmd { + /** + * JsonMap defines a map that is safe for json and db read/write. + */ + interface JsonMap extends _TygojaDict{} + interface JsonMap { /** - * 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. + * MarshalJSON implements the [json.Marshaler] interface. */ - string(): string + marshalJSON(): string|Array } - interface Cmd { + interface JsonMap { /** - * 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. + * Get retrieves a single value from the current JsonMap. * - * 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. + * 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). */ - run(): void + get(key: string): any } - interface Cmd { + interface JsonMap { /** - * Start starts the specified command but does not wait for it to complete. - * - * If Start returns successfully, the c.Process field will be set. + * Set sets a single value in the current JsonMap. * - * After a successful call to Start the Wait method must be called in - * order to release associated system resources. + * 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). */ - start(): void + set(key: string, value: any): void } - interface Cmd { + interface JsonMap { /** - * 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 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 releases any resources associated with the Cmd. + * Value implements the [driver.Valuer] interface. + */ + value(): any + } + interface JsonMap { + /** + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current `JsonMap` instance. + */ + scan(value: any): void + } +} + +/** + * Package schema implements custom Schema and SchemaField datatypes + * for handling the Collection schema definitions. + */ +namespace schema { + // @ts-ignore + import validation = ozzo_validation + /** + * Schema defines a dynamic db schema as a slice of `SchemaField`s. + */ + interface Schema { + } + interface Schema { + /** + * Fields returns the registered schema fields. */ - wait(): void + fields(): Array<(SchemaField | undefined)> } - interface Cmd { + interface Schema { /** - * Output runs the command and returns its standard output. - * Any returned error will usually be of type *ExitError. - * If c.Stderr was nil, Output populates ExitError.Stderr. + * InitFieldsOptions calls `InitOptions()` for all schema fields. */ - output(): string|Array + initFieldsOptions(): void } - interface Cmd { + interface Schema { /** - * CombinedOutput runs the command and returns its combined standard - * output and standard error. + * Clone creates a deep clone of the current schema. */ - combinedOutput(): string|Array + clone(): (Schema) } - interface Cmd { + interface Schema { /** - * 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 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. + * AsMap returns a map with all registered schema field. + * The returned map is indexed with each field name. */ - stdinPipe(): io.WriteCloser + asMap(): _TygojaDict } - interface Cmd { + interface Schema { /** - * StdoutPipe returns a pipe that will be connected to the command's - * standard output when the command starts. - * - * 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 Run when using StdoutPipe. - * See the example for idiomatic usage. + * GetFieldById returns a single field by its id. */ - stdoutPipe(): io.ReadCloser + getFieldById(id: string): (SchemaField) } - interface Cmd { + interface Schema { /** - * StderrPipe returns a pipe that will be connected to the command's - * standard error when the command starts. - * - * 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 Run when using StderrPipe. - * See the StdoutPipe example for idiomatic usage. + * GetFieldByName returns a single field by its name. */ - stderrPipe(): io.ReadCloser + getFieldByName(name: string): (SchemaField) } - interface Cmd { + interface Schema { /** - * Environ returns a copy of the environment in which the command would be run - * as it is currently configured. + * RemoveField removes a single schema field by its id. + * + * This method does nothing if field with `id` doesn't exist. */ - environ(): Array + removeField(id: string): 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]interface{} for JSON decoding. - * This is the default claims type if you don't supply one - */ - interface MapClaims extends _TygojaDict{} - interface MapClaims { + interface Schema { /** - * VerifyAudience Compares the aud claim against cmp. - * If required is false, this method will return true if the value matches or is unset + * AddField registers the provided newField to the current schema. + * + * If field with `newField.Id` already exist, the existing field is + * replaced with the new one. + * + * Otherwise the new field is appended to the other schema fields. */ - verifyAudience(cmp: string, req: boolean): boolean + addField(newField: SchemaField): void } - interface MapClaims { + interface Schema { /** - * VerifyExpiresAt compares the exp claim against cmp (cmp <= exp). - * If req is false, it will return true, if exp is unset. + * Validate makes Schema validatable by implementing [validation.Validatable] interface. + * + * Internally calls each individual field's validator and additionally + * checks for invalid renamed fields and field name duplications. */ - verifyExpiresAt(cmp: number, req: boolean): boolean + validate(): void } - interface MapClaims { + interface Schema { /** - * VerifyIssuedAt compares the exp claim against cmp (cmp >= iat). - * If req is false, it will return true, if iat is unset. + * MarshalJSON implements the [json.Marshaler] interface. */ - verifyIssuedAt(cmp: number, req: boolean): boolean + marshalJSON(): string|Array } - interface MapClaims { + interface Schema { /** - * VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). - * If req is false, it will return true, if nbf is unset. + * UnmarshalJSON implements the [json.Unmarshaler] interface. + * + * On success, all schema field options are auto initialized. */ - verifyNotBefore(cmp: number, req: boolean): boolean + unmarshalJSON(data: string|Array): void } - interface MapClaims { + interface Schema { /** - * VerifyIssuer compares the iss claim against cmp. - * If required is false, this method will return true if the value matches or is unset + * Value implements the [driver.Valuer] interface. */ - verifyIssuer(cmp: string, req: boolean): boolean + value(): any } - interface MapClaims { + interface Schema { /** - * Valid validates time based claims "exp, iat, nbf". - * There is no accounting for clock skew. - * As well, if any of the above claims are not in the token, it will still - * be considered a valid claim. + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current Schema instance. */ - valid(): void + scan(value: any): void } } /** - * Package blob provides an easy and portable way to interact with blobs - * within a storage location. Subpackages contain driver implementations of - * blob for supported services. - * - * See https://gocloud.dev/howto/blob/ for a detailed how-to guide. - * - * *blob.Bucket implements io/fs.FS and io/fs.SubFS, so it can be used with - * functions in that package. - * - * # Errors - * - * The errors returned from this package can be inspected in several ways: - * - * The Code function from gocloud.dev/gcerrors will return an error code, also - * defined in that package, when invoked on an error. - * - * The Bucket.ErrorAs method can retrieve the driver error underlying the returned - * error. - * - * # OpenCensus Integration - * - * OpenCensus supports tracing and metric collection for multiple languages and - * backend providers. See https://opencensus.io. - * - * This API collects OpenCensus traces and metrics for the following methods: - * ``` - * - Attributes - * - Copy - * - Delete - * - ListPage - * - NewRangeReader, from creation until the call to Close. (NewReader and ReadAll - * are included because they call NewRangeReader.) - * - NewWriter, from creation until the call to Close. - * ``` + * Package sql provides a generic interface around SQL (or SQL-like) + * databases. * - * All trace and metric names begin with the package import path. - * The traces add the method name. - * For example, "gocloud.dev/blob/Attributes". - * The metrics are "completed_calls", a count of completed method calls by driver, - * method and status (error code); and "latency", a distribution of method latency - * by driver and method. - * For example, "gocloud.dev/blob/latency". + * The sql package must be used in conjunction with a database driver. + * See https://golang.org/s/sqldrivers for a list of drivers. * - * It also collects the following metrics: - * ``` - * - gocloud.dev/blob/bytes_read: the total number of bytes read, by driver. - * - gocloud.dev/blob/bytes_written: the total number of bytes written, by driver. - * ``` + * Drivers that do not support context cancellation will not return until + * after the query is completed. * - * To enable trace collection in your application, see "Configure Exporter" at - * https://opencensus.io/quickstart/go/tracing. - * To enable metric collection in your application, see "Exporting stats" at - * https://opencensus.io/quickstart/go/metrics. + * For usage examples, see the wiki page at + * https://golang.org/s/sqlwiki. */ -namespace blob { +namespace sql { /** - * Reader reads bytes from a blob. - * It implements io.ReadSeekCloser, and must be closed after - * reads are finished. + * TxOptions holds the transaction options to be used in DB.BeginTx. */ - interface Reader { + interface TxOptions { + /** + * Isolation is the transaction isolation level. + * If zero, the driver or database's default level is used. + */ + isolation: IsolationLevel + readOnly: boolean + } + /** + * 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 Commit or + * 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 SetMaxIdleConns. + */ + interface DB { + } + interface DB { + /** + * PingContext verifies a connection to the database is still alive, + * establishing a connection if necessary. + */ + pingContext(ctx: context.Context): void + } + interface DB { + /** + * 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 + * PingContext. + */ + ping(): void + } + interface DB { + /** + * 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. + */ + close(): void } - interface Reader { + interface DB { /** - * Read implements io.Reader (https://golang.org/pkg/io/#Reader). + * SetMaxIdleConns sets the maximum number of connections in the idle + * connection pool. + * + * If MaxOpenConns is greater than 0 but less than the new MaxIdleConns, + * then the new MaxIdleConns will be reduced to match the MaxOpenConns limit. + * + * If n <= 0, no idle connections are retained. + * + * The default max idle connections is currently 2. This may change in + * a future release. */ - read(p: string|Array): number + setMaxIdleConns(n: number): void } - interface Reader { + interface DB { /** - * Seek implements io.Seeker (https://golang.org/pkg/io/#Seeker). + * SetMaxOpenConns sets the maximum number of open connections to the database. + * + * 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. + * + * If n <= 0, then there is no limit on the number of open connections. + * The default is 0 (unlimited). */ - seek(offset: number, whence: number): number + setMaxOpenConns(n: number): void } - interface Reader { + interface DB { /** - * Close implements io.Closer (https://golang.org/pkg/io/#Closer). + * 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. */ - close(): void + setConnMaxLifetime(d: time.Duration): void } - interface Reader { + interface DB { /** - * ContentType returns the MIME type of the blob. + * 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. */ - contentType(): string + setConnMaxIdleTime(d: time.Duration): void } - interface Reader { + interface DB { /** - * ModTime returns the time the blob was last modified. + * Stats returns database statistics. */ - modTime(): time.Time + stats(): DBStats } - interface Reader { + interface DB { /** - * Size returns the size of the blob content in bytes. + * 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 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. */ - size(): number + prepareContext(ctx: context.Context, query: string): (Stmt) } - interface Reader { + interface DB { /** - * As converts i to driver-specific types. - * See https://gocloud.dev/concepts/as/ for background information, the "As" - * examples in this package for examples, and the driver package - * documentation for the specific types supported for that driver. + * 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 Close method + * when the statement is no longer needed. + * + * Prepare uses context.Background internally; to specify the context, use + * PrepareContext. */ - as(i: { - }): boolean + prepare(query: string): (Stmt) } - interface Reader { + interface DB { /** - * 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. - * - * It implements the io.WriterTo interface. + * ExecContext executes a query without returning any rows. + * The args are for any placeholder parameters in the query. */ - writeTo(w: io.Writer): number + execContext(ctx: context.Context, query: string, ...args: any[]): Result } - /** - * Attributes contains attributes about a blob. - */ - interface Attributes { + interface DB { /** - * CacheControl specifies caching attributes that services may use - * when serving the blob. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control + * 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 + * ExecContext. */ - cacheControl: string + exec(query: string, ...args: any[]): Result + } + interface DB { /** - * 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 + * QueryContext executes a query that returns rows, typically a SELECT. + * The args are for any placeholder parameters in the query. */ - contentDisposition: string + queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows) + } + interface DB { /** - * ContentEncoding specifies the encoding used for the blob's content, if any. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding + * 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 + * QueryContext. */ - contentEncoding: string + query(query: string, ...args: any[]): (Rows) + } + interface DB { /** - * ContentLanguage specifies the language used in the blob's content, if any. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language + * 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's Scan will return ErrNoRows. + * Otherwise, the *Row's Scan scans the first selected row and discards + * the rest. */ - contentLanguage: string + queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row) + } + interface DB { /** - * 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 + * 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's Scan will return ErrNoRows. + * Otherwise, the *Row's Scan scans the first selected row and discards + * the rest. + * + * QueryRow uses context.Background internally; to specify the context, use + * QueryRowContext. */ - contentType: string + queryRow(query: string, ...args: any[]): (Row) + } + interface DB { /** - * 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. + * 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. + * + * 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. */ - metadata: _TygojaDict + beginTx(ctx: context.Context, opts: TxOptions): (Tx) + } + interface DB { /** - * CreateTime is the time the blob was created, if available. If not available, - * CreateTime will be the zero time. + * Begin starts a transaction. The default isolation level is dependent on + * the driver. + * + * Begin uses context.Background internally; to specify the context, use + * BeginTx. */ - createTime: time.Time + begin(): (Tx) + } + interface DB { /** - * ModTime is the time the blob was last modified. + * Driver returns the database's underlying driver. */ - modTime: time.Time + driver(): any + } + interface DB { /** - * Size is the size of the blob's content in bytes. + * 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. */ - size: number + conn(ctx: context.Context): (Conn) + } + /** + * Tx is an in-progress database transaction. + * + * A transaction must end with a call to Commit or Rollback. + * + * After a call to Commit or Rollback, all operations on the + * transaction fail with ErrTxDone. + * + * The statements prepared for a transaction by calling + * the transaction's Prepare or Stmt methods are closed + * by the call to Commit or Rollback. + */ + interface Tx { + } + interface Tx { /** - * MD5 is an MD5 hash of the blob contents or nil if not available. + * Commit commits the transaction. */ - md5: string|Array + commit(): void + } + interface Tx { /** - * ETag for the blob; see https://en.wikipedia.org/wiki/HTTP_ETag. + * Rollback aborts the transaction. */ - eTag: string + rollback(): void } - interface Attributes { + interface Tx { /** - * As converts i to driver-specific types. - * See https://gocloud.dev/concepts/as/ for background information, the "As" - * examples in this package for examples, and the driver package - * documentation for the specific types supported for that driver. + * 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. */ - as(i: { - }): boolean + prepareContext(ctx: context.Context, query: string): (Stmt) } - /** - * ListObject represents a single blob returned from List. - */ - interface ListObject { + interface Tx { /** - * Key is the key for this blob. + * 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. + * + * Prepare uses context.Background internally; to specify the context, use + * PrepareContext. */ - key: string + prepare(query: string): (Stmt) + } + interface Tx { /** - * ModTime is the time the blob was last modified. + * 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. */ - modTime: time.Time + stmtContext(ctx: context.Context, stmt: Stmt): (Stmt) + } + interface Tx { /** - * Size is the size of the blob's content in bytes. + * 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. + * + * Stmt uses context.Background internally; to specify the context, use + * StmtContext. */ - size: number + stmt(stmt: Stmt): (Stmt) + } + interface Tx { /** - * MD5 is an MD5 hash of the blob contents or nil if not available. + * ExecContext executes a query that doesn't return rows. + * For example: an INSERT and UPDATE. */ - md5: string|Array + execContext(ctx: context.Context, query: string, ...args: any[]): Result + } + interface Tx { /** - * 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. + * 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 + * ExecContext. */ - isDir: boolean + exec(query: string, ...args: any[]): Result } - interface ListObject { + interface Tx { /** - * As converts i to driver-specific types. - * See https://gocloud.dev/concepts/as/ for background information, the "As" - * examples in this package for examples, and the driver package - * documentation for the specific types supported for that driver. + * QueryContext executes a query that returns rows, typically a SELECT. */ - as(i: { - }): boolean + queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows) } -} - -/** - * Package types implements some commonly used db serializable types - * like datetime, json, etc. - */ -namespace types { - /** - * JsonArray defines a slice that is safe for json and db read/write. - */ - interface JsonArray extends Array{} - interface JsonArray { + interface Tx { /** - * MarshalJSON implements the [json.Marshaler] interface. + * Query executes a query that returns rows, typically a SELECT. + * + * Query uses context.Background internally; to specify the context, use + * QueryContext. */ - marshalJSON(): string|Array + query(query: string, ...args: any[]): (Rows) } - interface JsonArray { + interface Tx { /** - * Value implements the [driver.Valuer] interface. + * 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's Scan will return ErrNoRows. + * Otherwise, the *Row's Scan scans the first selected row and discards + * the rest. */ - value(): any + queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row) } - interface JsonArray { + interface Tx { /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current JsonArray[T] instance. + * 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's Scan will return ErrNoRows. + * Otherwise, the *Row's Scan scans the first selected row and discards + * the rest. + * + * QueryRow uses context.Background internally; to specify the context, use + * QueryRowContext. */ - scan(value: any): void + queryRow(query: string, ...args: any[]): (Row) } /** - * JsonMap defines a map that is safe for json and db read/write. + * 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 JsonMap extends _TygojaDict{} - interface JsonMap { + interface Stmt { + } + interface Stmt { /** - * MarshalJSON implements the [json.Marshaler] interface. + * ExecContext executes a prepared statement with the given arguments and + * returns a Result summarizing the effect of the statement. */ - marshalJSON(): string|Array + execContext(ctx: context.Context, ...args: any[]): Result } - interface JsonMap { + interface Stmt { /** - * Get retrieves a single value from the current JsonMap. + * Exec executes a prepared statement with the given arguments and + * returns a Result summarizing the effect of the statement. * - * 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). + * Exec uses context.Background internally; to specify the context, use + * ExecContext. */ - get(key: string): any + exec(...args: any[]): Result } - interface JsonMap { + interface Stmt { /** - * Set sets a single value in the current JsonMap. - * - * 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). + * QueryContext executes a prepared query statement with the given arguments + * and returns the query results as a *Rows. */ - set(key: string, value: any): void + queryContext(ctx: context.Context, ...args: any[]): (Rows) } - interface JsonMap { + interface Stmt { /** - * Value implements the [driver.Valuer] interface. + * Query executes a prepared query statement with the given arguments + * and returns the query results as a *Rows. + * + * Query uses context.Background internally; to specify the context, use + * QueryContext. */ - value(): any + query(...args: any[]): (Rows) } - interface JsonMap { + interface Stmt { /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current `JsonMap` instance. + * 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's Scan will return ErrNoRows. + * Otherwise, the *Row's Scan scans the first selected row and discards + * the rest. */ - scan(value: any): void - } -} - -/** - * Package schema implements custom Schema and SchemaField datatypes - * for handling the Collection schema definitions. - */ -namespace schema { - // @ts-ignore - import validation = ozzo_validation - /** - * Schema defines a dynamic db schema as a slice of `SchemaField`s. - */ - interface Schema { + queryRowContext(ctx: context.Context, ...args: any[]): (Row) } - interface Schema { + interface Stmt { /** - * Fields returns the registered schema fields. + * 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's Scan will return ErrNoRows. + * Otherwise, the *Row's Scan scans the first selected row and discards + * the rest. + * + * Example usage: + * + * ``` + * var name string + * err := nameByUseridStmt.QueryRow(id).Scan(&name) + * ``` + * + * QueryRow uses context.Background internally; to specify the context, use + * QueryRowContext. */ - fields(): Array<(SchemaField | undefined)> + queryRow(...args: any[]): (Row) } - interface Schema { + interface Stmt { /** - * InitFieldsOptions calls `InitOptions()` for all schema fields. + * Close closes the statement. */ - initFieldsOptions(): void + close(): void } - interface Schema { + /** + * Rows is the result of a query. Its cursor starts before the first row + * of the result set. Use Next to advance from row to row. + */ + interface Rows { + } + interface Rows { /** - * Clone creates a deep clone of the current schema. + * Next prepares the next result row for reading with the Scan method. It + * returns true on success, or false if there is no next result row or an error + * happened while preparing it. Err should be consulted to distinguish between + * the two cases. + * + * Every call to Scan, even the first one, must be preceded by a call to Next. */ - clone(): (Schema) + next(): boolean } - interface Schema { + interface Rows { /** - * AsMap returns a map with all registered schema field. - * The returned map is indexed with each field name. + * 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 Err method should be consulted + * to distinguish between the two cases. + * + * After calling NextResultSet, the Next method should always be called before + * scanning. If there are further result sets they may not have rows in the result + * set. */ - asMap(): _TygojaDict + nextResultSet(): boolean } - interface Schema { + interface Rows { /** - * GetFieldById returns a single field by its id. + * Err returns the error, if any, that was encountered during iteration. + * Err may be called after an explicit or implicit Close. */ - getFieldById(id: string): (SchemaField) + err(): void } - interface Schema { + interface Rows { /** - * GetFieldByName returns a single field by its name. + * Columns returns the column names. + * Columns returns an error if the rows are closed. */ - getFieldByName(name: string): (SchemaField) + columns(): Array } - interface Schema { + interface Rows { /** - * RemoveField removes a single schema field by its id. - * - * This method does nothing if field with `id` doesn't exist. + * ColumnTypes returns column information such as column type, length, + * and nullable. Some information may not be available from some drivers. */ - removeField(id: string): void + columnTypes(): Array<(ColumnType | undefined)> } - interface Schema { + interface Rows { /** - * AddField registers the provided newField to the current schema. + * 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 field with `newField.Id` already exist, the existing field is - * replaced with the new one. + * Scan converts columns read from the database into the following + * common Go types and special types provided by the sql package: * - * Otherwise the new field is appended to the other schema fields. - */ - addField(newField: SchemaField): void - } - interface Schema { - /** - * Validate makes Schema validatable by implementing [validation.Validatable] interface. + * ``` + * *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) + * ``` * - * Internally calls each individual field's validator and additionally - * checks for invalid renamed fields and field name duplications. - */ - validate(): void - } - interface Schema { - /** - * MarshalJSON implements the [json.Marshaler] interface. + * 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. + * + * 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. + * + * 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. */ - marshalJSON(): string|Array + scan(...dest: any[]): void } - interface Schema { + interface Rows { /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. - * - * On success, all schema field options are auto initialized. + * Close closes the Rows, preventing further enumeration. If 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 Err. Close is idempotent and does not affect the result of Err. */ - unmarshalJSON(data: string|Array): void + close(): void } - interface Schema { + /** + * A Result summarizes an executed SQL command. + */ + interface Result { + [key:string]: any; /** - * Value implements the [driver.Valuer] interface. + * 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. */ - value(): any - } - interface Schema { + lastInsertId(): number /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current Schema instance. + * RowsAffected returns the number of rows affected by an + * update, insert, or delete. Not every database or database + * driver may support this. */ - scan(value: any): void + rowsAffected(): number } } @@ -10467,8 +10467,8 @@ namespace schema { * Package models implements all PocketBase DB models and DTOs. */ namespace models { - type _subQBatR = BaseModel - interface Admin extends _subQBatR { + type _subYlRNg = BaseModel + interface Admin extends _subYlRNg { avatar: number email: string tokenKey: string @@ -10503,8 +10503,8 @@ namespace models { } // @ts-ignore import validation = ozzo_validation - type _subbIeYl = BaseModel - interface Collection extends _subbIeYl { + type _subeQlzp = BaseModel + interface Collection extends _subeQlzp { name: string type: string system: boolean @@ -10597,8 +10597,8 @@ namespace models { */ setOptions(typedOptions: any): void } - type _subkPein = BaseModel - interface ExternalAuth extends _subkPein { + type _subbYlmv = BaseModel + interface ExternalAuth extends _subbYlmv { collectionId: string recordId: string provider: string @@ -10607,8 +10607,8 @@ namespace models { interface ExternalAuth { tableName(): string } - type _subDBryk = BaseModel - interface Record extends _subDBryk { + type _subgEvDY = BaseModel + interface Record extends _subgEvDY { } interface Record { /** @@ -11792,6 +11792,36 @@ namespace settings { } } +namespace migrate { + /** + * MigrationsList defines a list with migration definitions + */ + interface MigrationsList { + } + interface MigrationsList { + /** + * Item returns a single migration from the list by its index. + */ + item(index: number): (Migration) + } + interface MigrationsList { + /** + * Items returns the internal migrations list slice. + */ + items(): Array<(Migration | undefined)> + } + interface MigrationsList { + /** + * Register adds new migration definition to the list. + * + * If `optFilename` is not provided, it will try to get the name from its .go file. + * + * The list will be sorted automatically based on the migrations file name. + */ + register(up: (db: dbx.Builder) => void, down: (db: dbx.Builder) => void, ...optFilename: string[]): void + } +} + /** * Package daos handles common PocketBase DB model manipulations. * @@ -12442,36 +12472,6 @@ namespace daos { } } -namespace migrate { - /** - * MigrationsList defines a list with migration definitions - */ - interface MigrationsList { - } - interface MigrationsList { - /** - * Item returns a single migration from the list by its index. - */ - item(index: number): (Migration) - } - interface MigrationsList { - /** - * Items returns the internal migrations list slice. - */ - items(): Array<(Migration | undefined)> - } - interface MigrationsList { - /** - * Register adds new migration definition to the list. - * - * If `optFilename` is not provided, it will try to get the name from its .go file. - * - * The list will be sorted automatically based on the migrations file name. - */ - register(up: (db: dbx.Builder) => void, down: (db: dbx.Builder) => void, ...optFilename: string[]): void - } -} - /** * Package core is the backbone of PocketBase. * @@ -14399,17 +14399,57 @@ namespace cobra { */ 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 + 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 + } +} + +/** + * Package io provides basic interfaces to I/O primitives. + * Its primary job is to wrap existing implementations of such primitives, + * such as those in package os, into shared public interfaces that + * abstract the functionality, plus some other related primitives. + * + * Because these interfaces and primitives wrap lower-level operations with + * various implementations, unless otherwise informed clients should not + * assume they are safe for parallel execution. + */ +namespace io { + /** + * Writer is the interface that wraps the basic Write method. + * + * Write writes len(p) bytes from p to the underlying data stream. + * It returns the number of bytes written from p (0 <= n <= len(p)) + * and any error encountered that caused the write to stop early. + * Write must return a non-nil error if it returns n < len(p). + * Write must not modify the slice data, even temporarily. + * + * Implementations must not retain p. + */ + interface Writer { + [key:string]: any; + write(p: string|Array): number + } + /** + * ReadCloser is the interface that groups the basic Read and Close methods. + */ + interface ReadCloser { + [key:string]: any; + } + /** + * WriteCloser is the interface that groups the basic Write and Close methods. + */ + interface WriteCloser { + [key:string]: any; } } @@ -14643,46 +14683,6 @@ namespace time { namespace context { } -/** - * Package io provides basic interfaces to I/O primitives. - * Its primary job is to wrap existing implementations of such primitives, - * such as those in package os, into shared public interfaces that - * abstract the functionality, plus some other related primitives. - * - * Because these interfaces and primitives wrap lower-level operations with - * various implementations, unless otherwise informed clients should not - * assume they are safe for parallel execution. - */ -namespace io { - /** - * Writer is the interface that wraps the basic Write method. - * - * Write writes len(p) bytes from p to the underlying data stream. - * It returns the number of bytes written from p (0 <= n <= len(p)) - * and any error encountered that caused the write to stop early. - * Write must return a non-nil error if it returns n < len(p). - * Write must not modify the slice data, even temporarily. - * - * Implementations must not retain p. - */ - interface Writer { - [key:string]: any; - write(p: string|Array): number - } - /** - * ReadCloser is the interface that groups the basic Read and Close methods. - */ - interface ReadCloser { - [key:string]: any; - } - /** - * WriteCloser is the interface that groups the basic Write and Close methods. - */ - interface WriteCloser { - [key:string]: any; - } -} - /** * Package fs defines basic interfaces to a file system. * A file system can be provided by the host operating system @@ -14853,236 +14853,57 @@ namespace sql { * DecimalSize returns the scale and precision of a decimal type. * If not applicable or if not supported ok is false. */ - decimalSize(): [number, boolean] - } - interface ColumnType { - /** - * 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. - */ - scanType(): any - } - interface ColumnType { - /** - * Nullable reports whether the column may be null. - * If a driver does not support this property ok will be false. - */ - nullable(): boolean - } - interface ColumnType { - /** - * 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. Length specifiers - * are not included. - * Common type names include "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL", - * "INT", and "BIGINT". - */ - databaseTypeName(): string - } - /** - * Row is the result of calling QueryRow to select a single row. - */ - 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 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 Scan. - */ - err(): void - } -} - -/** - * Package net provides a portable interface for network I/O, including - * TCP/IP, UDP, domain name resolution, and Unix domain sockets. - * - * Although the package provides access to low-level networking - * primitives, most clients will need only the basic interface provided - * by the Dial, Listen, and Accept functions and the associated - * Conn and Listener interfaces. The crypto/tls package uses - * the same interfaces and similar Dial and Listen functions. - * - * The Dial function connects to a server: - * - * ``` - * conn, err := net.Dial("tcp", "golang.org:80") - * if err != nil { - * // handle error - * } - * fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n") - * status, err := bufio.NewReader(conn).ReadString('\n') - * // ... - * ``` - * - * The Listen function creates servers: - * - * ``` - * ln, err := net.Listen("tcp", ":8080") - * if err != nil { - * // handle error - * } - * for { - * conn, err := ln.Accept() - * if err != nil { - * // handle error - * } - * go handleConnection(conn) - * } - * ``` - * - * # Name Resolution - * - * The method for resolving domain names, whether indirectly with functions like Dial - * or directly with functions like LookupHost and LookupAddr, varies by operating system. - * - * On Unix systems, the resolver has two options for resolving names. - * It can use a pure Go resolver that sends DNS requests directly to the servers - * listed in /etc/resolv.conf, or it can use a cgo-based resolver that calls C - * library routines such as getaddrinfo and getnameinfo. - * - * By default the pure Go resolver is used, because a blocked DNS request consumes - * only a goroutine, while a blocked C call consumes an operating system thread. - * When cgo is available, the cgo-based resolver is used instead under a variety of - * conditions: on systems that do not let programs make direct DNS requests (OS X), - * when the LOCALDOMAIN environment variable is present (even if empty), - * when the RES_OPTIONS or HOSTALIASES environment variable is non-empty, - * when the ASR_CONFIG environment variable is non-empty (OpenBSD only), - * when /etc/resolv.conf or /etc/nsswitch.conf specify the use of features that the - * Go resolver does not implement, and when the name being looked up ends in .local - * or is an mDNS name. - * - * The resolver decision can be overridden by setting the netdns value of the - * GODEBUG environment variable (see package runtime) to go or cgo, as in: - * - * ``` - * export GODEBUG=netdns=go # force pure Go resolver - * export GODEBUG=netdns=cgo # force native resolver (cgo, win32) - * ``` - * - * The decision can also be forced while building the Go source tree - * by setting the netgo or netcgo build tag. - * - * A numeric netdns setting, as in GODEBUG=netdns=1, causes the resolver - * to print debugging information about its decisions. - * To force a particular resolver while also printing debugging information, - * join the two settings by a plus sign, as in GODEBUG=netdns=go+1. - * - * On macOS, if Go code that uses the net package is built with - * -buildmode=c-archive, linking the resulting archive into a C program - * requires passing -lresolv when linking the C code. - * - * On Plan 9, the resolver always accesses /net/cs and /net/dns. - * - * On Windows, in Go 1.18.x and earlier, the resolver always used C - * library functions, such as GetAddrInfo and DnsQuery. - */ -namespace net { - /** - * Conn is a generic stream-oriented network connection. - * - * Multiple goroutines may invoke methods on a Conn simultaneously. - */ - interface Conn { - [key:string]: any; - /** - * Read reads data from the connection. - * Read can be made to time out and return an error after a fixed - * time limit; see SetDeadline and SetReadDeadline. - */ - read(b: string|Array): number - /** - * Write writes data to the connection. - * Write can be made to time out and return an error after a fixed - * time limit; see SetDeadline and SetWriteDeadline. - */ - write(b: string|Array): number - /** - * Close closes the connection. - * Any blocked Read or Write operations will be unblocked and return errors. - */ - close(): void - /** - * LocalAddr returns the local network address, if known. - */ - localAddr(): Addr - /** - * RemoteAddr returns the remote network address, if known. - */ - remoteAddr(): Addr - /** - * SetDeadline sets the read and write deadlines associated - * with the connection. It is equivalent to calling both - * SetReadDeadline and SetWriteDeadline. - * - * A deadline is an absolute time after which I/O operations - * fail instead of blocking. The deadline applies to all future - * and pending I/O, not just the immediately following call to - * Read or Write. After a deadline has been exceeded, the - * connection can be refreshed by setting a deadline in the future. - * - * If the deadline is exceeded a call to Read or Write or to other - * I/O methods will return an error that wraps os.ErrDeadlineExceeded. - * This can be tested using errors.Is(err, os.ErrDeadlineExceeded). - * The error's Timeout method will return true, but note that there - * are other possible errors for which the Timeout method will - * return true even if the deadline has not been exceeded. - * - * An idle timeout can be implemented by repeatedly extending - * the deadline after successful Read or Write calls. - * - * A zero value for t means I/O operations will not time out. - */ - setDeadline(t: time.Time): void + decimalSize(): [number, boolean] + } + interface ColumnType { /** - * SetReadDeadline sets the deadline for future Read calls - * and any currently-blocked Read call. - * A zero value for t means Read will not time out. + * 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. */ - setReadDeadline(t: time.Time): void + scanType(): any + } + interface ColumnType { /** - * SetWriteDeadline sets the deadline for future Write calls - * and any currently-blocked Write call. - * Even if write times out, it may return n > 0, indicating that - * some of the data was successfully written. - * A zero value for t means Write will not time out. + * Nullable reports whether the column may be null. + * If a driver does not support this property ok will be false. */ - setWriteDeadline(t: time.Time): void + nullable(): boolean } - /** - * A Listener is a generic network listener for stream-oriented protocols. - * - * Multiple goroutines may invoke methods on a Listener simultaneously. - */ - interface Listener { - [key:string]: any; + interface ColumnType { /** - * Accept waits for and returns the next connection to the listener. + * 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. Length specifiers + * are not included. + * Common type names include "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL", + * "INT", and "BIGINT". */ - accept(): Conn + databaseTypeName(): string + } + /** + * Row is the result of calling QueryRow to select a single row. + */ + interface Row { + } + interface Row { /** - * Close closes the listener. - * Any blocked Accept operations will be unblocked and return errors. + * 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. */ - close(): void + scan(...dest: any[]): void + } + interface Row { /** - * Addr returns the listener's network address. + * Err provides a way for wrapping packages to check for + * query errors without calling 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 Scan. */ - addr(): Addr + err(): void } } @@ -15286,34 +15107,213 @@ namespace url { } 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. + * 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. + */ + hostname(): string + } + interface URL { + /** + * 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. + */ + port(): string + } + interface URL { + marshalBinary(): string|Array + } + interface URL { + unmarshalBinary(text: string|Array): void + } + interface URL { + /** + * 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 /. + */ + joinPath(...elem: string[]): (URL) + } +} + +/** + * Package net provides a portable interface for network I/O, including + * TCP/IP, UDP, domain name resolution, and Unix domain sockets. + * + * Although the package provides access to low-level networking + * primitives, most clients will need only the basic interface provided + * by the Dial, Listen, and Accept functions and the associated + * Conn and Listener interfaces. The crypto/tls package uses + * the same interfaces and similar Dial and Listen functions. + * + * The Dial function connects to a server: + * + * ``` + * conn, err := net.Dial("tcp", "golang.org:80") + * if err != nil { + * // handle error + * } + * fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n") + * status, err := bufio.NewReader(conn).ReadString('\n') + * // ... + * ``` + * + * The Listen function creates servers: + * + * ``` + * ln, err := net.Listen("tcp", ":8080") + * if err != nil { + * // handle error + * } + * for { + * conn, err := ln.Accept() + * if err != nil { + * // handle error + * } + * go handleConnection(conn) + * } + * ``` + * + * # Name Resolution + * + * The method for resolving domain names, whether indirectly with functions like Dial + * or directly with functions like LookupHost and LookupAddr, varies by operating system. + * + * On Unix systems, the resolver has two options for resolving names. + * It can use a pure Go resolver that sends DNS requests directly to the servers + * listed in /etc/resolv.conf, or it can use a cgo-based resolver that calls C + * library routines such as getaddrinfo and getnameinfo. + * + * By default the pure Go resolver is used, because a blocked DNS request consumes + * only a goroutine, while a blocked C call consumes an operating system thread. + * When cgo is available, the cgo-based resolver is used instead under a variety of + * conditions: on systems that do not let programs make direct DNS requests (OS X), + * when the LOCALDOMAIN environment variable is present (even if empty), + * when the RES_OPTIONS or HOSTALIASES environment variable is non-empty, + * when the ASR_CONFIG environment variable is non-empty (OpenBSD only), + * when /etc/resolv.conf or /etc/nsswitch.conf specify the use of features that the + * Go resolver does not implement, and when the name being looked up ends in .local + * or is an mDNS name. + * + * The resolver decision can be overridden by setting the netdns value of the + * GODEBUG environment variable (see package runtime) to go or cgo, as in: + * + * ``` + * export GODEBUG=netdns=go # force pure Go resolver + * export GODEBUG=netdns=cgo # force native resolver (cgo, win32) + * ``` + * + * The decision can also be forced while building the Go source tree + * by setting the netgo or netcgo build tag. + * + * A numeric netdns setting, as in GODEBUG=netdns=1, causes the resolver + * to print debugging information about its decisions. + * To force a particular resolver while also printing debugging information, + * join the two settings by a plus sign, as in GODEBUG=netdns=go+1. + * + * On macOS, if Go code that uses the net package is built with + * -buildmode=c-archive, linking the resulting archive into a C program + * requires passing -lresolv when linking the C code. + * + * On Plan 9, the resolver always accesses /net/cs and /net/dns. + * + * On Windows, in Go 1.18.x and earlier, the resolver always used C + * library functions, such as GetAddrInfo and DnsQuery. + */ +namespace net { + /** + * Conn is a generic stream-oriented network connection. + * + * Multiple goroutines may invoke methods on a Conn simultaneously. + */ + interface Conn { + [key:string]: any; + /** + * Read reads data from the connection. + * Read can be made to time out and return an error after a fixed + * time limit; see SetDeadline and SetReadDeadline. + */ + read(b: string|Array): number + /** + * Write writes data to the connection. + * Write can be made to time out and return an error after a fixed + * time limit; see SetDeadline and SetWriteDeadline. + */ + write(b: string|Array): number + /** + * Close closes the connection. + * Any blocked Read or Write operations will be unblocked and return errors. + */ + close(): void + /** + * LocalAddr returns the local network address, if known. + */ + localAddr(): Addr + /** + * RemoteAddr returns the remote network address, if known. + */ + remoteAddr(): Addr + /** + * SetDeadline sets the read and write deadlines associated + * with the connection. It is equivalent to calling both + * SetReadDeadline and SetWriteDeadline. + * + * A deadline is an absolute time after which I/O operations + * fail instead of blocking. The deadline applies to all future + * and pending I/O, not just the immediately following call to + * Read or Write. After a deadline has been exceeded, the + * connection can be refreshed by setting a deadline in the future. + * + * If the deadline is exceeded a call to Read or Write or to other + * I/O methods will return an error that wraps os.ErrDeadlineExceeded. + * This can be tested using errors.Is(err, os.ErrDeadlineExceeded). + * The error's Timeout method will return true, but note that there + * are other possible errors for which the Timeout method will + * return true even if the deadline has not been exceeded. + * + * An idle timeout can be implemented by repeatedly extending + * the deadline after successful Read or Write calls. + * + * A zero value for t means I/O operations will not time out. + */ + setDeadline(t: time.Time): void + /** + * SetReadDeadline sets the deadline for future Read calls + * and any currently-blocked Read call. + * A zero value for t means Read will not time out. + */ + setReadDeadline(t: time.Time): void + /** + * SetWriteDeadline sets the deadline for future Write calls + * and any currently-blocked Write call. + * Even if write times out, it may return n > 0, indicating that + * some of the data was successfully written. + * A zero value for t means Write will not time out. + */ + setWriteDeadline(t: time.Time): void + } + /** + * A Listener is a generic network listener for stream-oriented protocols. + * + * Multiple goroutines may invoke methods on a Listener simultaneously. + */ + interface Listener { + [key:string]: any; + /** + * Accept waits for and returns the next connection to the listener. */ - hostname(): string - } - interface URL { + accept(): Conn /** - * 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. + * Close closes the listener. + * Any blocked Accept operations will be unblocked and return errors. */ - port(): string - } - interface URL { - marshalBinary(): string|Array - } - interface URL { - unmarshalBinary(text: string|Array): void - } - interface URL { + close(): void /** - * 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 /. + * Addr returns the listener's network address. */ - joinPath(...elem: string[]): (URL) + addr(): Addr } } @@ -15911,963 +15911,963 @@ namespace http { } } -/** - * Package echo implements high performance, minimalist Go web framework. - * - * Example: - * - * ``` - * package main - * - * import ( - * "github.com/labstack/echo/v5" - * "github.com/labstack/echo/v5/middleware" - * "log" - * "net/http" - * ) - * - * // Handler - * func hello(c echo.Context) error { - * return c.String(http.StatusOK, "Hello, World!") - * } - * - * func main() { - * // Echo instance - * e := echo.New() - * - * // Middleware - * e.Use(middleware.Logger()) - * e.Use(middleware.Recover()) - * - * // Routes - * e.GET("/", hello) - * - * // Start server - * if err := e.Start(":8080"); err != http.ErrServerClosed { - * log.Fatal(err) - * } - * } - * ``` - * - * Learn more at https://echo.labstack.com - */ -namespace echo { - /** - * Binder is the interface that wraps the Bind method. - */ - interface Binder { - [key:string]: any; - bind(c: Context, i: { - }): void - } - /** - * ServableContext is interface that Echo context implementation must implement to be usable in middleware/handlers and - * be able to be routed by Router. - */ - interface ServableContext { - [key:string]: any; - /** - * Reset resets the context after request completes. It must be called along - * with `Echo#AcquireContext()` and `Echo#ReleaseContext()`. - * See `Echo#ServeHTTP()` - */ - reset(r: http.Request, w: http.ResponseWriter): void - } - // @ts-ignore - import stdContext = context - /** - * JSONSerializer is the interface that encodes and decodes JSON to and from interfaces. - */ - interface JSONSerializer { - [key:string]: any; - serialize(c: Context, i: { - }, indent: string): void - deserialize(c: Context, i: { - }): void - } - /** - * HTTPErrorHandler is a centralized HTTP error handler. - */ - interface HTTPErrorHandler {(c: Context, err: Error): void } - /** - * Validator is the interface that wraps the Validate function. - */ - interface Validator { - [key:string]: any; - validate(i: { - }): void - } - /** - * Renderer is the interface that wraps the Render function. - */ - interface Renderer { - [key:string]: any; - render(_arg0: io.Writer, _arg1: string, _arg2: { - }, _arg3: Context): void - } +namespace store { /** - * Group is a set of sub-routes for a specified route. It can be used for inner - * routes that share a common middleware or functionality that should be separate - * from the parent echo instance while still inheriting from it. + * Store defines a concurrent safe in memory key-value data store. */ - interface Group { - } - interface Group { - /** - * Use implements `Echo#Use()` for sub-routes within the Group. - * Group middlewares are not executed on request when there is no matching route found. - */ - use(...middleware: MiddlewareFunc[]): void - } - interface Group { - /** - * CONNECT implements `Echo#CONNECT()` for sub-routes within the Group. Panics on error. - */ - connect(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Group { - /** - * DELETE implements `Echo#DELETE()` for sub-routes within the Group. Panics on error. - */ - delete(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + interface Store { } - interface Group { + interface Store { /** - * GET implements `Echo#GET()` for sub-routes within the Group. Panics on error. + * Reset clears the store and replaces the store data with a + * shallow copy of the provided newData. */ - get(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + reset(newData: _TygojaDict): void } - interface Group { + interface Store { /** - * HEAD implements `Echo#HEAD()` for sub-routes within the Group. Panics on error. + * Length returns the current number of elements in the store. */ - head(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + length(): number } - interface Group { + interface Store { /** - * OPTIONS implements `Echo#OPTIONS()` for sub-routes within the Group. Panics on error. + * RemoveAll removes all the existing store entries. */ - options(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + removeAll(): void } - interface Group { + interface Store { /** - * PATCH implements `Echo#PATCH()` for sub-routes within the Group. Panics on error. + * Remove removes a single entry from the store. + * + * Remove does nothing if key doesn't exist in the store. */ - patch(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + remove(key: string): void } - interface Group { + interface Store { /** - * POST implements `Echo#POST()` for sub-routes within the Group. Panics on error. + * Has checks if element with the specified key exist or not. */ - post(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + has(key: string): boolean } - interface Group { + interface Store { /** - * PUT implements `Echo#PUT()` for sub-routes within the Group. Panics on error. + * Get returns a single element value from the store. + * + * If key is not set, the zero T value is returned. */ - put(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + get(key: string): T } - interface Group { + interface Store { /** - * TRACE implements `Echo#TRACE()` for sub-routes within the Group. Panics on error. + * GetAll returns a shallow copy of the current store data. */ - trace(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + getAll(): _TygojaDict } - interface Group { + interface Store { /** - * Any implements `Echo#Any()` for sub-routes within the Group. Panics on error. + * Set sets (or overwrite if already exist) a new value for key. */ - any(path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes + set(key: string, value: T): void } - interface Group { + interface Store { /** - * Match implements `Echo#Match()` for sub-routes within the Group. Panics on error. + * 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. */ - match(methods: Array, path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes + setIfLessThanLimit(key: string, value: T, maxAllowedElements: number): boolean } - interface Group { - /** - * Group creates a new sub-group with prefix and optional sub-group-level middleware. - * Important! Group middlewares are only executed in case there was exact route match and not - * for 404 (not found) or 405 (method not allowed) cases. If this kind of behaviour is needed then add - * a catch-all route `/*` for the group which handler returns always 404 - */ - group(prefix: string, ...middleware: MiddlewareFunc[]): (Group) +} + +/** + * 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 Group { + interface DateTime { /** - * Static implements `Echo#Static()` for sub-routes within the Group. + * Time returns the internal [time.Time] instance. */ - static(pathPrefix: string): RouteInfo + time(): time.Time } - interface Group { + interface DateTime { /** - * StaticFS implements `Echo#StaticFS()` for sub-routes within the Group. - * - * When dealing with `embed.FS` use `fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary - * prefix for directory path. This is necessary as `//go:embed assets/images` embeds files with paths - * including `assets/images` as their prefix. + * IsZero checks whether the current DateTime instance has zero time value. */ - staticFS(pathPrefix: string, filesystem: fs.FS): RouteInfo + isZero(): boolean } - interface Group { + interface DateTime { /** - * FileFS implements `Echo#FileFS()` for sub-routes within the Group. + * String serializes the current DateTime instance into a formatted + * UTC date string. + * + * The zero value is serialized to an empty string. */ - fileFS(path: string, filesystem: fs.FS, ...m: MiddlewareFunc[]): RouteInfo + string(): string } - interface Group { + interface DateTime { /** - * File implements `Echo#File()` for sub-routes within the Group. Panics on error. + * MarshalJSON implements the [json.Marshaler] interface. */ - file(path: string, ...middleware: MiddlewareFunc[]): RouteInfo + marshalJSON(): string|Array } - interface Group { + interface DateTime { /** - * RouteNotFound implements `Echo#RouteNotFound()` for sub-routes within the Group. - * - * Example: `g.RouteNotFound("/*", func(c echo.Context) error { return c.NoContent(http.StatusNotFound) })` + * UnmarshalJSON implements the [json.Unmarshaler] interface. */ - routeNotFound(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + unmarshalJSON(b: string|Array): void } - interface Group { + interface DateTime { /** - * Add implements `Echo#Add()` for sub-routes within the Group. Panics on error. + * Value implements the [driver.Valuer] interface. */ - add(method: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): RouteInfo + value(): any } - interface Group { + interface DateTime { /** - * AddRoute registers a new Routable with Router + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current DateTime instance. */ - addRoute(route: Routable): RouteInfo + scan(value: any): void } +} + +/** + * Package schema implements custom Schema and SchemaField datatypes + * for handling the Collection schema definitions. + */ +namespace schema { + // @ts-ignore + import validation = ozzo_validation /** - * IPExtractor is a function to extract IP addr from http.Request. - * Set appropriate one to Echo#IPExtractor. - * See https://echo.labstack.com/guide/ip-address for more details. - */ - interface IPExtractor {(_arg0: http.Request): string } - /** - * Logger defines the logging interface that Echo uses internally in few places. - * For logging in handlers use your own logger instance (dependency injected or package/public variable) from logging framework of your choice. + * SchemaField defines a single schema field structure. */ - interface Logger { - [key:string]: any; + interface SchemaField { + system: boolean + id: string + name: string + type: string + required: boolean /** - * Write provides writer interface for http.Server `ErrorLog` and for logging startup messages. - * `http.Server.ErrorLog` logs errors from accepting connections, unexpected behavior from handlers, - * and underlying FileSystem errors. - * `logger` middleware will use this method to write its JSON payload. + * Presentable indicates whether the field is suitable for + * visualization purposes (eg. in the Admin UI relation views). */ - write(p: string|Array): number + presentable: boolean /** - * Error logs the error + * Deprecated: This field is no-op and will be removed in future versions. + * Please use the collection.Indexes field to define a unique constraint. */ - error(err: Error): void - } - /** - * Response wraps an http.ResponseWriter and implements its interface to be used - * by an HTTP handler to construct an HTTP response. - * See: https://golang.org/pkg/net/http/#ResponseWriter - */ - interface Response { - writer: http.ResponseWriter - status: number - size: number - committed: boolean + unique: boolean + options: any } - interface Response { + interface SchemaField { /** - * Header returns the header map for the writer that will be sent by - * WriteHeader. Changing the header after a call to WriteHeader (or Write) has - * no effect unless the modified headers were declared as trailers by setting - * the "Trailer" header before the call to WriteHeader (see example) - * To suppress implicit response headers, set their value to nil. - * Example: https://golang.org/pkg/net/http/#example_ResponseWriter_trailers + * ColDefinition returns the field db column type definition as string. */ - header(): http.Header + colDefinition(): string } - interface Response { + interface SchemaField { /** - * Before registers a function which is called just before the response is written. + * String serializes and returns the current field as string. */ - before(fn: () => void): void + string(): string } - interface Response { + interface SchemaField { /** - * After registers a function which is called just after the response is written. - * If the `Content-Length` is unknown, none of the after function is executed. + * MarshalJSON implements the [json.Marshaler] interface. */ - after(fn: () => void): void + marshalJSON(): string|Array } - interface Response { + interface SchemaField { /** - * WriteHeader sends an HTTP response header with 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. + * UnmarshalJSON implements the [json.Unmarshaler] interface. + * + * The schema field options are auto initialized on success. */ - writeHeader(code: number): void + unmarshalJSON(data: string|Array): void } - interface Response { + interface SchemaField { /** - * Write writes the data to the connection as part of an HTTP reply. + * Validate makes `SchemaField` validatable by implementing [validation.Validatable] interface. */ - write(b: string|Array): number + validate(): void } - interface Response { + interface SchemaField { /** - * Flush implements the http.Flusher interface to allow an HTTP handler to flush - * buffered data to the client. - * See [http.Flusher](https://golang.org/pkg/net/http/#Flusher) + * InitOptions initializes the current field options based on its type. + * + * Returns error on unknown field type. */ - flush(): void + initOptions(): void } - interface Response { + interface SchemaField { /** - * Hijack implements the http.Hijacker interface to allow an HTTP handler to - * take over the connection. - * See [http.Hijacker](https://golang.org/pkg/net/http/#Hijacker) + * PrepareValue returns normalized and properly formatted field value. */ - hijack(): [net.Conn, (bufio.ReadWriter)] + prepareValue(value: any): any } - interface Response { + interface SchemaField { /** - * Unwrap returns the original http.ResponseWriter. - * ResponseController can be used to access the original http.ResponseWriter. - * See [https://go.dev/blog/go1.20] + * PrepareValueWithModifier returns normalized and properly formatted field value + * by "merging" baseValue with the modifierValue based on the specified modifier (+ or -). */ - unwrap(): http.ResponseWriter + prepareValueWithModifier(baseValue: any, modifier: string, modifierValue: any): any } - interface Routes { +} + +/** + * Package models implements all PocketBase DB models and DTOs. + */ +namespace models { + /** + * Model defines an interface with common methods that all db models should have. + */ + interface Model { + [key:string]: any; + tableName(): string + isNew(): boolean + markAsNew(): void + markAsNotNew(): void + hasId(): boolean + getId(): string + setId(id: string): void + getCreated(): types.DateTime + getUpdated(): types.DateTime + refreshId(): void + refreshCreated(): void + refreshUpdated(): void + } + /** + * BaseModel defines common fields and methods used by all other models. + */ + interface BaseModel { + id: string + created: types.DateTime + updated: types.DateTime + } + interface BaseModel { /** - * Reverse reverses route to URL string by replacing path parameters with given params values. + * HasId returns whether the model has a nonzero id. */ - reverse(name: string, ...params: { - }[]): string + hasId(): boolean } - interface Routes { + interface BaseModel { /** - * FindByMethodPath searched for matching route info by method and path + * GetId returns the model id. */ - findByMethodPath(method: string, path: string): RouteInfo + getId(): string } - interface Routes { + interface BaseModel { /** - * FilterByMethod searched for matching route info by method + * SetId sets the model id to the provided string value. */ - filterByMethod(method: string): Routes + setId(id: string): void } - interface Routes { + interface BaseModel { /** - * FilterByPath searched for matching route info by path + * MarkAsNew marks the model as "new" (aka. enforces m.IsNew() to be true). */ - filterByPath(path: string): Routes + markAsNew(): void } - interface Routes { + interface BaseModel { /** - * FilterByName searched for matching route info by name + * MarkAsNotNew marks the model as "not new" (aka. enforces m.IsNew() to be false) */ - filterByName(name: string): Routes + markAsNotNew(): void } - /** - * Router is interface for routing request contexts to registered routes. - * - * Contract between Echo/Context instance and the router: - * ``` - * - all routes must be added through methods on echo.Echo instance. - * Reason: Echo instance uses RouteInfo.Params() length to allocate slice for paths parameters (see `Echo.contextPathParamAllocSize`). - * - Router must populate Context during Router.Route call with: - * - RoutableContext.SetPath - * - RoutableContext.SetRawPathParams (IMPORTANT! with same slice pointer that c.RawPathParams() returns) - * - RoutableContext.SetRouteInfo - * And optionally can set additional information to Context with RoutableContext.Set - * ``` - */ - interface Router { - [key:string]: any; + interface BaseModel { /** - * Add registers Routable with the Router and returns registered RouteInfo + * IsNew indicates what type of db query (insert or update) + * should be used with the model instance. */ - add(routable: Routable): RouteInfo + isNew(): boolean + } + interface BaseModel { /** - * Remove removes route from the Router + * GetCreated returns the model Created datetime. */ - remove(method: string, path: string): void + getCreated(): types.DateTime + } + interface BaseModel { /** - * Routes returns information about all registered routes + * GetUpdated returns the model Updated datetime. */ - routes(): Routes + getUpdated(): types.DateTime + } + interface BaseModel { /** - * Route searches Router for matching route and applies it to the given context. In case when no matching method - * was not found (405) or no matching route exists for path (404), router will return its implementation of 405/404 - * handler function. + * RefreshId generates and sets a new model id. + * + * The generated id is a cryptographically random 15 characters length string. */ - route(c: RoutableContext): HandlerFunc + refreshId(): void } - /** - * Routable is interface for registering Route with Router. During route registration process the Router will - * convert Routable to RouteInfo with ToRouteInfo method. By creating custom implementation of Routable additional - * information about registered route can be stored in Routes (i.e. privileges used with route etc.) - */ - interface Routable { - [key:string]: any; + interface BaseModel { /** - * ToRouteInfo converts Routable to RouteInfo - * - * This method is meant to be used by Router after it parses url for path parameters, to store information about - * route just added. + * RefreshCreated updates the model Created field with the current datetime. */ - toRouteInfo(params: Array): RouteInfo + refreshCreated(): void + } + interface BaseModel { /** - * ToRoute converts Routable to Route which Router uses to register the method handler for path. - * - * This method is meant to be used by Router to get fields (including handler and middleware functions) needed to - * add Route to Router. + * RefreshUpdated updates the model Updated field with the current datetime. */ - toRoute(): Route + refreshUpdated(): void + } + interface BaseModel { /** - * ForGroup recreates routable with added group prefix and group middlewares it is grouped to. + * PostScan implements the [dbx.PostScanner] interface. * - * Is necessary for Echo.Group to be able to add/register Routable with Router and having group prefix and group - * middlewares included in actually registered Route. + * It is executed right after the model was populated with the db row values. */ - forGroup(pathPrefix: string, middlewares: Array): Routable + postScan(): void } + // @ts-ignore + import validation = ozzo_validation /** - * Routes is collection of RouteInfo instances with various helper methods. + * CollectionBaseOptions defines the "base" Collection.Options fields. */ - interface Routes extends Array{} + interface CollectionBaseOptions { + } + interface CollectionBaseOptions { + /** + * Validate implements [validation.Validatable] interface. + */ + validate(): void + } /** - * RouteInfo describes registered route base fields. - * Method+Path pair uniquely identifies the Route. Name can have duplicates. + * CollectionAuthOptions defines the "auth" Collection.Options fields. */ - interface RouteInfo { - [key:string]: any; - method(): string - path(): string - name(): string - params(): Array + interface CollectionAuthOptions { + manageRule?: string + allowOAuth2Auth: boolean + allowUsernameAuth: boolean + allowEmailAuth: boolean + requireEmail: boolean + exceptEmailDomains: Array + onlyVerified: boolean + onlyEmailDomains: Array + minPasswordLength: number + } + interface CollectionAuthOptions { /** - * Reverse reverses route to URL string by replacing path parameters with given params values. + * Validate implements [validation.Validatable] interface. */ - reverse(...params: { - }[]): string + validate(): void } /** - * PathParams is collections of PathParam instances with various helper methods + * CollectionViewOptions defines the "view" Collection.Options fields. */ - interface PathParams extends Array{} - interface PathParams { + interface CollectionViewOptions { + query: string + } + interface CollectionViewOptions { /** - * Get returns path parameter value for given name or default value. + * Validate implements [validation.Validatable] interface. */ - get(name: string, defaultValue: string): string + validate(): void + } + type _subJyPpQ = BaseModel + interface Log extends _subJyPpQ { + data: types.JsonMap + message: string + level: number + } + interface Log { + tableName(): string + } + type _subsZwLm = BaseModel + interface Param extends _subsZwLm { + key: string + value: types.JsonRaw + } + interface Param { + tableName(): string + } + interface TableInfoRow { + /** + * the `db:"pk"` tag has special semantic so we cannot rename + * the original field without specifying a custom mapper + */ + pk: number + index: number + name: string + type: string + notNull: boolean + defaultValue: types.JsonRaw } } -namespace store { +/** + * 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. + */ +/** + * Copyright 2023 The Go Authors. All rights reserved. + * Use of this source code is governed by a BSD-style + * license that can be found in the LICENSE file. + */ +namespace oauth2 { /** - * Store defines a concurrent safe in memory key-value data store. + * An AuthCodeOption is passed to Config.AuthCodeURL. */ - interface Store { + interface AuthCodeOption { + [key:string]: any; } - interface Store { + /** + * 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 { /** - * Reset clears the store and replaces the store data with a - * shallow copy of the provided newData. + * AccessToken is the token that authorizes and authenticates + * the requests. */ - reset(newData: _TygojaDict): void - } - interface Store { + accessToken: string /** - * Length returns the current number of elements in the store. + * TokenType is the type of token. + * The Type method returns either this or "Bearer", the default. */ - length(): number + 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 } - interface Store { + interface Token { /** - * RemoveAll removes all the existing store entries. + * Type returns t.TokenType if non-empty, else "Bearer". */ - removeAll(): void + type(): string } - interface Store { + interface Token { /** - * Remove removes a single entry from the store. + * SetAuthHeader sets the Authorization header to r using the access + * token in t. * - * Remove does nothing if key doesn't exist in the store. + * This method is unnecessary when using Transport or an HTTP Client + * returned by this package. */ - remove(key: string): void + setAuthHeader(r: http.Request): void } - interface Store { + interface Token { /** - * Has checks if element with the specified key exist or not. + * 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. */ - has(key: string): boolean + withExtra(extra: { + }): (Token) } - interface Store { + interface Token { /** - * Get returns a single element value from the store. - * - * If key is not set, the zero T value is returned. + * Extra returns an extra field. + * Extra fields are key-value pairs returned by the server as a + * part of the token retrieval response. */ - get(key: string): T + extra(key: string): { + } + } + interface Token { + /** + * Valid reports whether t is non-nil, has an AccessToken, and is not expired. + */ + valid(): boolean + } +} + +namespace mailer { + /** + * Mailer defines a base mail client interface. + */ + interface Mailer { + [key:string]: any; + /** + * Send sends an email with the provided Message. + */ + send(message: Message): void + } +} + +/** + * Package echo implements high performance, minimalist Go web framework. + * + * Example: + * + * ``` + * package main + * + * import ( + * "github.com/labstack/echo/v5" + * "github.com/labstack/echo/v5/middleware" + * "log" + * "net/http" + * ) + * + * // Handler + * func hello(c echo.Context) error { + * return c.String(http.StatusOK, "Hello, World!") + * } + * + * func main() { + * // Echo instance + * e := echo.New() + * + * // Middleware + * e.Use(middleware.Logger()) + * e.Use(middleware.Recover()) + * + * // Routes + * e.GET("/", hello) + * + * // Start server + * if err := e.Start(":8080"); err != http.ErrServerClosed { + * log.Fatal(err) + * } + * } + * ``` + * + * Learn more at https://echo.labstack.com + */ +namespace echo { + /** + * Binder is the interface that wraps the Bind method. + */ + interface Binder { + [key:string]: any; + bind(c: Context, i: { + }): void } - interface Store { + /** + * ServableContext is interface that Echo context implementation must implement to be usable in middleware/handlers and + * be able to be routed by Router. + */ + interface ServableContext { + [key:string]: any; /** - * GetAll returns a shallow copy of the current store data. + * Reset resets the context after request completes. It must be called along + * with `Echo#AcquireContext()` and `Echo#ReleaseContext()`. + * See `Echo#ServeHTTP()` */ - getAll(): _TygojaDict + reset(r: http.Request, w: http.ResponseWriter): void } - interface Store { - /** - * Set sets (or overwrite if already exist) a new value for key. - */ - set(key: string, value: T): void + // @ts-ignore + import stdContext = context + /** + * JSONSerializer is the interface that encodes and decodes JSON to and from interfaces. + */ + interface JSONSerializer { + [key:string]: any; + serialize(c: Context, i: { + }, indent: string): void + deserialize(c: Context, i: { + }): void } - 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: string, value: T, maxAllowedElements: number): boolean + /** + * HTTPErrorHandler is a centralized HTTP error handler. + */ + interface HTTPErrorHandler {(c: Context, err: Error): void } + /** + * Validator is the interface that wraps the Validate function. + */ + interface Validator { + [key:string]: any; + validate(i: { + }): 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. + * Renderer is the interface that wraps the Render function. */ - interface DateTime { + interface Renderer { + [key:string]: any; + render(_arg0: io.Writer, _arg1: string, _arg2: { + }, _arg3: Context): void } - interface DateTime { - /** - * Time returns the internal [time.Time] instance. - */ - time(): time.Time + /** + * Group is a set of sub-routes for a specified route. It can be used for inner + * routes that share a common middleware or functionality that should be separate + * from the parent echo instance while still inheriting from it. + */ + interface Group { } - interface DateTime { + interface Group { /** - * IsZero checks whether the current DateTime instance has zero time value. + * Use implements `Echo#Use()` for sub-routes within the Group. + * Group middlewares are not executed on request when there is no matching route found. */ - isZero(): boolean + use(...middleware: MiddlewareFunc[]): void } - interface DateTime { + interface Group { /** - * String serializes the current DateTime instance into a formatted - * UTC date string. - * - * The zero value is serialized to an empty string. + * CONNECT implements `Echo#CONNECT()` for sub-routes within the Group. Panics on error. */ - string(): string + connect(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface DateTime { + interface Group { /** - * MarshalJSON implements the [json.Marshaler] interface. + * DELETE implements `Echo#DELETE()` for sub-routes within the Group. Panics on error. */ - marshalJSON(): string|Array + delete(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface DateTime { + interface Group { /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. + * GET implements `Echo#GET()` for sub-routes within the Group. Panics on error. */ - unmarshalJSON(b: string|Array): void + get(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface DateTime { + interface Group { /** - * Value implements the [driver.Valuer] interface. + * HEAD implements `Echo#HEAD()` for sub-routes within the Group. Panics on error. */ - value(): any + head(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface DateTime { + interface Group { /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current DateTime instance. + * OPTIONS implements `Echo#OPTIONS()` for sub-routes within the Group. Panics on error. */ - scan(value: any): void + options(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } -} - -/** - * Package schema implements custom Schema and SchemaField datatypes - * for handling the Collection schema definitions. - */ -namespace schema { - // @ts-ignore - import validation = ozzo_validation - /** - * SchemaField defines a single schema field structure. - */ - interface SchemaField { - system: boolean - id: string - name: string - type: string - required: boolean - /** - * Presentable indicates whether the field is suitable for - * visualization purposes (eg. in the Admin UI relation views). - */ - presentable: boolean + interface Group { /** - * Deprecated: This field is no-op and will be removed in future versions. - * Please use the collection.Indexes field to define a unique constraint. + * PATCH implements `Echo#PATCH()` for sub-routes within the Group. Panics on error. */ - unique: boolean - options: any + patch(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface SchemaField { + interface Group { /** - * ColDefinition returns the field db column type definition as string. + * POST implements `Echo#POST()` for sub-routes within the Group. Panics on error. */ - colDefinition(): string + post(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface SchemaField { + interface Group { /** - * String serializes and returns the current field as string. + * PUT implements `Echo#PUT()` for sub-routes within the Group. Panics on error. */ - string(): string + put(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface SchemaField { + interface Group { /** - * MarshalJSON implements the [json.Marshaler] interface. + * TRACE implements `Echo#TRACE()` for sub-routes within the Group. Panics on error. */ - marshalJSON(): string|Array + trace(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface SchemaField { + interface Group { /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. - * - * The schema field options are auto initialized on success. + * Any implements `Echo#Any()` for sub-routes within the Group. Panics on error. */ - unmarshalJSON(data: string|Array): void + any(path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes } - interface SchemaField { + interface Group { /** - * Validate makes `SchemaField` validatable by implementing [validation.Validatable] interface. + * Match implements `Echo#Match()` for sub-routes within the Group. Panics on error. */ - validate(): void + match(methods: Array, path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes } - interface SchemaField { + interface Group { /** - * InitOptions initializes the current field options based on its type. - * - * Returns error on unknown field type. + * Group creates a new sub-group with prefix and optional sub-group-level middleware. + * Important! Group middlewares are only executed in case there was exact route match and not + * for 404 (not found) or 405 (method not allowed) cases. If this kind of behaviour is needed then add + * a catch-all route `/*` for the group which handler returns always 404 */ - initOptions(): void + group(prefix: string, ...middleware: MiddlewareFunc[]): (Group) } - interface SchemaField { + interface Group { /** - * PrepareValue returns normalized and properly formatted field value. + * Static implements `Echo#Static()` for sub-routes within the Group. */ - prepareValue(value: any): any + static(pathPrefix: string): RouteInfo } - interface SchemaField { + interface Group { /** - * PrepareValueWithModifier returns normalized and properly formatted field value - * by "merging" baseValue with the modifierValue based on the specified modifier (+ or -). - */ - prepareValueWithModifier(baseValue: any, modifier: string, modifierValue: any): any - } -} - -/** - * Package models implements all PocketBase DB models and DTOs. - */ -namespace models { - /** - * Model defines an interface with common methods that all db models should have. - */ - interface Model { - [key:string]: any; - tableName(): string - isNew(): boolean - markAsNew(): void - markAsNotNew(): void - hasId(): boolean - getId(): string - setId(id: string): void - getCreated(): types.DateTime - getUpdated(): types.DateTime - refreshId(): void - refreshCreated(): void - refreshUpdated(): void - } - /** - * BaseModel defines common fields and methods used by all other models. - */ - interface BaseModel { - id: string - created: types.DateTime - updated: types.DateTime + * StaticFS implements `Echo#StaticFS()` for sub-routes within the Group. + * + * When dealing with `embed.FS` use `fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary + * prefix for directory path. This is necessary as `//go:embed assets/images` embeds files with paths + * including `assets/images` as their prefix. + */ + staticFS(pathPrefix: string, filesystem: fs.FS): RouteInfo } - interface BaseModel { + interface Group { /** - * HasId returns whether the model has a nonzero id. + * FileFS implements `Echo#FileFS()` for sub-routes within the Group. */ - hasId(): boolean + fileFS(path: string, filesystem: fs.FS, ...m: MiddlewareFunc[]): RouteInfo } - interface BaseModel { + interface Group { /** - * GetId returns the model id. + * File implements `Echo#File()` for sub-routes within the Group. Panics on error. */ - getId(): string + file(path: string, ...middleware: MiddlewareFunc[]): RouteInfo } - interface BaseModel { + interface Group { /** - * SetId sets the model id to the provided string value. + * RouteNotFound implements `Echo#RouteNotFound()` for sub-routes within the Group. + * + * Example: `g.RouteNotFound("/*", func(c echo.Context) error { return c.NoContent(http.StatusNotFound) })` */ - setId(id: string): void + routeNotFound(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface BaseModel { + interface Group { /** - * MarkAsNew marks the model as "new" (aka. enforces m.IsNew() to be true). + * Add implements `Echo#Add()` for sub-routes within the Group. Panics on error. */ - markAsNew(): void + add(method: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): RouteInfo } - interface BaseModel { + interface Group { /** - * MarkAsNotNew marks the model as "not new" (aka. enforces m.IsNew() to be false) + * AddRoute registers a new Routable with Router */ - markAsNotNew(): void + addRoute(route: Routable): RouteInfo } - interface BaseModel { + /** + * IPExtractor is a function to extract IP addr from http.Request. + * Set appropriate one to Echo#IPExtractor. + * See https://echo.labstack.com/guide/ip-address for more details. + */ + interface IPExtractor {(_arg0: http.Request): string } + /** + * Logger defines the logging interface that Echo uses internally in few places. + * For logging in handlers use your own logger instance (dependency injected or package/public variable) from logging framework of your choice. + */ + interface Logger { + [key:string]: any; /** - * IsNew indicates what type of db query (insert or update) - * should be used with the model instance. + * Write provides writer interface for http.Server `ErrorLog` and for logging startup messages. + * `http.Server.ErrorLog` logs errors from accepting connections, unexpected behavior from handlers, + * and underlying FileSystem errors. + * `logger` middleware will use this method to write its JSON payload. */ - isNew(): boolean - } - interface BaseModel { + write(p: string|Array): number /** - * GetCreated returns the model Created datetime. + * Error logs the error */ - getCreated(): types.DateTime + error(err: Error): void } - interface BaseModel { + /** + * Response wraps an http.ResponseWriter and implements its interface to be used + * by an HTTP handler to construct an HTTP response. + * See: https://golang.org/pkg/net/http/#ResponseWriter + */ + interface Response { + writer: http.ResponseWriter + status: number + size: number + committed: boolean + } + interface Response { /** - * GetUpdated returns the model Updated datetime. + * Header returns the header map for the writer that will be sent by + * WriteHeader. Changing the header after a call to WriteHeader (or Write) has + * no effect unless the modified headers were declared as trailers by setting + * the "Trailer" header before the call to WriteHeader (see example) + * To suppress implicit response headers, set their value to nil. + * Example: https://golang.org/pkg/net/http/#example_ResponseWriter_trailers */ - getUpdated(): types.DateTime + header(): http.Header } - interface BaseModel { + interface Response { /** - * RefreshId generates and sets a new model id. - * - * The generated id is a cryptographically random 15 characters length string. + * Before registers a function which is called just before the response is written. */ - refreshId(): void + before(fn: () => void): void } - interface BaseModel { + interface Response { /** - * RefreshCreated updates the model Created field with the current datetime. + * After registers a function which is called just after the response is written. + * If the `Content-Length` is unknown, none of the after function is executed. */ - refreshCreated(): void + after(fn: () => void): void } - interface BaseModel { + interface Response { /** - * RefreshUpdated updates the model Updated field with the current datetime. + * WriteHeader sends an HTTP response header with 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. */ - refreshUpdated(): void + writeHeader(code: number): void } - interface BaseModel { + interface Response { /** - * PostScan implements the [dbx.PostScanner] interface. - * - * It is executed right after the model was populated with the db row values. + * Write writes the data to the connection as part of an HTTP reply. */ - postScan(): void - } - // @ts-ignore - import validation = ozzo_validation - /** - * CollectionBaseOptions defines the "base" Collection.Options fields. - */ - interface CollectionBaseOptions { + write(b: string|Array): number } - interface CollectionBaseOptions { + interface Response { /** - * Validate implements [validation.Validatable] interface. + * Flush implements the http.Flusher interface to allow an HTTP handler to flush + * buffered data to the client. + * See [http.Flusher](https://golang.org/pkg/net/http/#Flusher) */ - validate(): void - } - /** - * CollectionAuthOptions defines the "auth" Collection.Options fields. - */ - interface CollectionAuthOptions { - manageRule?: string - allowOAuth2Auth: boolean - allowUsernameAuth: boolean - allowEmailAuth: boolean - requireEmail: boolean - exceptEmailDomains: Array - onlyVerified: boolean - onlyEmailDomains: Array - minPasswordLength: number + flush(): void } - interface CollectionAuthOptions { + interface Response { /** - * Validate implements [validation.Validatable] interface. + * Hijack implements the http.Hijacker interface to allow an HTTP handler to + * take over the connection. + * See [http.Hijacker](https://golang.org/pkg/net/http/#Hijacker) */ - validate(): void - } - /** - * CollectionViewOptions defines the "view" Collection.Options fields. - */ - interface CollectionViewOptions { - query: string + hijack(): [net.Conn, (bufio.ReadWriter)] } - interface CollectionViewOptions { + interface Response { /** - * Validate implements [validation.Validatable] interface. + * Unwrap returns the original http.ResponseWriter. + * ResponseController can be used to access the original http.ResponseWriter. + * See [https://go.dev/blog/go1.20] */ - validate(): void - } - type _subPxYWe = BaseModel - interface Log extends _subPxYWe { - data: types.JsonMap - message: string - level: number + unwrap(): http.ResponseWriter } - interface Log { - tableName(): string + interface Routes { + /** + * Reverse reverses route to URL string by replacing path parameters with given params values. + */ + reverse(name: string, ...params: { + }[]): string } - type _subVdueA = BaseModel - interface Param extends _subVdueA { - key: string - value: types.JsonRaw + interface Routes { + /** + * FindByMethodPath searched for matching route info by method and path + */ + findByMethodPath(method: string, path: string): RouteInfo } - interface Param { - tableName(): string + interface Routes { + /** + * FilterByMethod searched for matching route info by method + */ + filterByMethod(method: string): Routes } - interface TableInfoRow { + interface Routes { /** - * the `db:"pk"` tag has special semantic so we cannot rename - * the original field without specifying a custom mapper + * FilterByPath searched for matching route info by path */ - pk: number - index: number - name: string - type: string - notNull: boolean - defaultValue: types.JsonRaw + filterByPath(path: string): Routes } -} - -/** - * 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. - */ -/** - * Copyright 2023 The Go Authors. All rights reserved. - * Use of this source code is governed by a BSD-style - * license that can be found in the LICENSE file. - */ -namespace oauth2 { - /** - * An AuthCodeOption is passed to Config.AuthCodeURL. - */ - interface AuthCodeOption { - [key:string]: any; + interface Routes { + /** + * FilterByName searched for matching route info by name + */ + filterByName(name: string): Routes } /** - * Token represents the credentials used to authorize - * the requests to access protected resources on the OAuth 2.0 - * provider's backend. + * Router is interface for routing request contexts to registered routes. * - * 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. + * Contract between Echo/Context instance and the router: + * ``` + * - all routes must be added through methods on echo.Echo instance. + * Reason: Echo instance uses RouteInfo.Params() length to allocate slice for paths parameters (see `Echo.contextPathParamAllocSize`). + * - Router must populate Context during Router.Route call with: + * - RoutableContext.SetPath + * - RoutableContext.SetRawPathParams (IMPORTANT! with same slice pointer that c.RawPathParams() returns) + * - RoutableContext.SetRouteInfo + * And optionally can set additional information to Context with RoutableContext.Set + * ``` */ - 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. + interface Router { + [key:string]: any; + /** + * Add registers Routable with the Router and returns registered RouteInfo */ - tokenType: string + add(routable: Routable): RouteInfo /** - * RefreshToken is a token that's used by the application - * (as opposed to the user) to refresh the access token - * if it expires. + * Remove removes route from the Router */ - refreshToken: string + remove(method: string, path: string): void /** - * 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. + * Routes returns information about all registered routes */ - expiry: time.Time - } - interface Token { + routes(): Routes /** - * Type returns t.TokenType if non-empty, else "Bearer". + * Route searches Router for matching route and applies it to the given context. In case when no matching method + * was not found (405) or no matching route exists for path (404), router will return its implementation of 405/404 + * handler function. */ - type(): string + route(c: RoutableContext): HandlerFunc } - interface Token { + /** + * Routable is interface for registering Route with Router. During route registration process the Router will + * convert Routable to RouteInfo with ToRouteInfo method. By creating custom implementation of Routable additional + * information about registered route can be stored in Routes (i.e. privileges used with route etc.) + */ + interface Routable { + [key:string]: any; /** - * SetAuthHeader sets the Authorization header to r using the access - * token in t. + * ToRouteInfo converts Routable to RouteInfo * - * This method is unnecessary when using Transport or an HTTP Client - * returned by this package. + * This method is meant to be used by Router after it parses url for path parameters, to store information about + * route just added. */ - setAuthHeader(r: http.Request): void - } - interface Token { + toRouteInfo(params: Array): RouteInfo /** - * 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. + * ToRoute converts Routable to Route which Router uses to register the method handler for path. + * + * This method is meant to be used by Router to get fields (including handler and middleware functions) needed to + * add Route to Router. */ - withExtra(extra: { - }): (Token) - } - interface Token { + toRoute(): Route /** - * Extra returns an extra field. - * Extra fields are key-value pairs returned by the server as a - * part of the token retrieval response. + * ForGroup recreates routable with added group prefix and group middlewares it is grouped to. + * + * Is necessary for Echo.Group to be able to add/register Routable with Router and having group prefix and group + * middlewares included in actually registered Route. */ - extra(key: string): { - } + forGroup(pathPrefix: string, middlewares: Array): Routable } - interface Token { + /** + * Routes is collection of RouteInfo instances with various helper methods. + */ + interface Routes extends Array{} + /** + * RouteInfo describes registered route base fields. + * Method+Path pair uniquely identifies the Route. Name can have duplicates. + */ + interface RouteInfo { + [key:string]: any; + method(): string + path(): string + name(): string + params(): Array /** - * Valid reports whether t is non-nil, has an AccessToken, and is not expired. + * Reverse reverses route to URL string by replacing path parameters with given params values. */ - valid(): boolean + reverse(...params: { + }[]): string } -} - -namespace mailer { /** - * Mailer defines a base mail client interface. + * PathParams is collections of PathParam instances with various helper methods */ - interface Mailer { - [key:string]: any; + interface PathParams extends Array{} + interface PathParams { /** - * Send sends an email with the provided Message. + * Get returns path parameter value for given name or default value. */ - send(message: Message): void + get(name: string, defaultValue: string): string } } @@ -17092,8 +17092,8 @@ namespace hook { * 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 _sublalpN = mainHook - interface TaggedHook extends _sublalpN { + type _subyoEUx = mainHook + interface TaggedHook extends _subyoEUx { } interface TaggedHook { /** @@ -17120,6 +17120,63 @@ namespace hook { } } +namespace migrate { + interface Migration { + file: string + up: (db: dbx.Builder) => void + down: (db: dbx.Builder) => void + } +} + +/** + * Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces. + * In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code. + */ +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 + } + /** + * 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{} + /** + * 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 + } +} + /** * Package slog provides structured logging, * in which log records include a message, @@ -17668,12 +17725,12 @@ namespace core { httpContext: echo.Context error: Error } - type _subEqhsL = BaseModelEvent - interface ModelEvent extends _subEqhsL { + type _suboxQNF = BaseModelEvent + interface ModelEvent extends _suboxQNF { dao?: daos.Dao } - type _subpEfvA = BaseCollectionEvent - interface MailerRecordEvent extends _subpEfvA { + type _subNnoVy = BaseCollectionEvent + interface MailerRecordEvent extends _subNnoVy { mailClient: mailer.Mailer message?: mailer.Message record?: models.Record @@ -17713,50 +17770,50 @@ namespace core { oldSettings?: settings.Settings newSettings?: settings.Settings } - type _subLZfSX = BaseCollectionEvent - interface RecordsListEvent extends _subLZfSX { + type _subnhCIk = BaseCollectionEvent + interface RecordsListEvent extends _subnhCIk { httpContext: echo.Context records: Array<(models.Record | undefined)> result?: search.Result } - type _subhCJrw = BaseCollectionEvent - interface RecordViewEvent extends _subhCJrw { + type _subvKEpg = BaseCollectionEvent + interface RecordViewEvent extends _subvKEpg { httpContext: echo.Context record?: models.Record } - type _subgwatK = BaseCollectionEvent - interface RecordCreateEvent extends _subgwatK { + type _subZcKDl = BaseCollectionEvent + interface RecordCreateEvent extends _subZcKDl { httpContext: echo.Context record?: models.Record uploadedFiles: _TygojaDict } - type _subYJOlw = BaseCollectionEvent - interface RecordUpdateEvent extends _subYJOlw { + type _subqOISc = BaseCollectionEvent + interface RecordUpdateEvent extends _subqOISc { httpContext: echo.Context record?: models.Record uploadedFiles: _TygojaDict } - type _subBzjCF = BaseCollectionEvent - interface RecordDeleteEvent extends _subBzjCF { + type _subcnTSG = BaseCollectionEvent + interface RecordDeleteEvent extends _subcnTSG { httpContext: echo.Context record?: models.Record } - type _subHuSaC = BaseCollectionEvent - interface RecordAuthEvent extends _subHuSaC { + type _subUQeQA = BaseCollectionEvent + interface RecordAuthEvent extends _subUQeQA { httpContext: echo.Context record?: models.Record token: string meta: any } - type _subdLEMS = BaseCollectionEvent - interface RecordAuthWithPasswordEvent extends _subdLEMS { + type _subeGkpi = BaseCollectionEvent + interface RecordAuthWithPasswordEvent extends _subeGkpi { httpContext: echo.Context record?: models.Record identity: string password: string } - type _subvSwRd = BaseCollectionEvent - interface RecordAuthWithOAuth2Event extends _subvSwRd { + type _subscnCN = BaseCollectionEvent + interface RecordAuthWithOAuth2Event extends _subscnCN { httpContext: echo.Context providerName: string providerClient: auth.Provider @@ -17764,49 +17821,49 @@ namespace core { oAuth2User?: auth.AuthUser isNewRecord: boolean } - type _subWkDbr = BaseCollectionEvent - interface RecordAuthRefreshEvent extends _subWkDbr { + type _subsdpfO = BaseCollectionEvent + interface RecordAuthRefreshEvent extends _subsdpfO { httpContext: echo.Context record?: models.Record } - type _subgKjYn = BaseCollectionEvent - interface RecordRequestPasswordResetEvent extends _subgKjYn { + type _subOOQvK = BaseCollectionEvent + interface RecordRequestPasswordResetEvent extends _subOOQvK { httpContext: echo.Context record?: models.Record } - type _subdHTYb = BaseCollectionEvent - interface RecordConfirmPasswordResetEvent extends _subdHTYb { + type _subFAlqp = BaseCollectionEvent + interface RecordConfirmPasswordResetEvent extends _subFAlqp { httpContext: echo.Context record?: models.Record } - type _subDEKIy = BaseCollectionEvent - interface RecordRequestVerificationEvent extends _subDEKIy { + type _subVMPNv = BaseCollectionEvent + interface RecordRequestVerificationEvent extends _subVMPNv { httpContext: echo.Context record?: models.Record } - type _substojr = BaseCollectionEvent - interface RecordConfirmVerificationEvent extends _substojr { + type _subtDtfj = BaseCollectionEvent + interface RecordConfirmVerificationEvent extends _subtDtfj { httpContext: echo.Context record?: models.Record } - type _subhPfGX = BaseCollectionEvent - interface RecordRequestEmailChangeEvent extends _subhPfGX { + type _subJcqOl = BaseCollectionEvent + interface RecordRequestEmailChangeEvent extends _subJcqOl { httpContext: echo.Context record?: models.Record } - type _submAbDl = BaseCollectionEvent - interface RecordConfirmEmailChangeEvent extends _submAbDl { + type _subQBIpB = BaseCollectionEvent + interface RecordConfirmEmailChangeEvent extends _subQBIpB { httpContext: echo.Context record?: models.Record } - type _subcATEz = BaseCollectionEvent - interface RecordListExternalAuthsEvent extends _subcATEz { + type _subuhTfu = BaseCollectionEvent + interface RecordListExternalAuthsEvent extends _subuhTfu { httpContext: echo.Context record?: models.Record externalAuths: Array<(models.ExternalAuth | undefined)> } - type _subnZUgX = BaseCollectionEvent - interface RecordUnlinkExternalAuthEvent extends _subnZUgX { + type _subwotFj = BaseCollectionEvent + interface RecordUnlinkExternalAuthEvent extends _subwotFj { httpContext: echo.Context record?: models.Record externalAuth?: models.ExternalAuth @@ -17860,33 +17917,33 @@ namespace core { collections: Array<(models.Collection | undefined)> result?: search.Result } - type _subOJaIs = BaseCollectionEvent - interface CollectionViewEvent extends _subOJaIs { + type _subtkVRc = BaseCollectionEvent + interface CollectionViewEvent extends _subtkVRc { httpContext: echo.Context } - type _subDOLvY = BaseCollectionEvent - interface CollectionCreateEvent extends _subDOLvY { + type _subCjDlH = BaseCollectionEvent + interface CollectionCreateEvent extends _subCjDlH { httpContext: echo.Context } - type _subLMuPk = BaseCollectionEvent - interface CollectionUpdateEvent extends _subLMuPk { + type _subyxTfj = BaseCollectionEvent + interface CollectionUpdateEvent extends _subyxTfj { httpContext: echo.Context } - type _subhrRnf = BaseCollectionEvent - interface CollectionDeleteEvent extends _subhrRnf { + type _subByycP = BaseCollectionEvent + interface CollectionDeleteEvent extends _subByycP { httpContext: echo.Context } interface CollectionsImportEvent { httpContext: echo.Context collections: Array<(models.Collection | undefined)> } - type _subDggCG = BaseModelEvent - interface FileTokenEvent extends _subDggCG { + type _subnKiiL = BaseModelEvent + interface FileTokenEvent extends _subnKiiL { httpContext: echo.Context token: string } - type _subgWBOB = BaseCollectionEvent - interface FileDownloadEvent extends _subgWBOB { + type _subZOoGq = BaseCollectionEvent + interface FileDownloadEvent extends _subZOoGq { httpContext: echo.Context record?: models.Record fileField?: schema.SchemaField @@ -17896,60 +17953,186 @@ namespace core { } /** - * Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces. - * In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code. + * 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 _subdjTan = Reader&Writer + interface ReadWriter extends _subdjTan { + } +} + +/** + * Package net provides a portable interface for network I/O, including + * TCP/IP, UDP, domain name resolution, and Unix domain sockets. + * + * Although the package provides access to low-level networking + * primitives, most clients will need only the basic interface provided + * by the Dial, Listen, and Accept functions and the associated + * Conn and Listener interfaces. The crypto/tls package uses + * the same interfaces and similar Dial and Listen functions. + * + * The Dial function connects to a server: + * + * ``` + * conn, err := net.Dial("tcp", "golang.org:80") + * if err != nil { + * // handle error + * } + * fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n") + * status, err := bufio.NewReader(conn).ReadString('\n') + * // ... + * ``` + * + * The Listen function creates servers: + * + * ``` + * ln, err := net.Listen("tcp", ":8080") + * if err != nil { + * // handle error + * } + * for { + * conn, err := ln.Accept() + * if err != nil { + * // handle error + * } + * go handleConnection(conn) + * } + * ``` + * + * # Name Resolution + * + * The method for resolving domain names, whether indirectly with functions like Dial + * or directly with functions like LookupHost and LookupAddr, varies by operating system. + * + * On Unix systems, the resolver has two options for resolving names. + * It can use a pure Go resolver that sends DNS requests directly to the servers + * listed in /etc/resolv.conf, or it can use a cgo-based resolver that calls C + * library routines such as getaddrinfo and getnameinfo. + * + * By default the pure Go resolver is used, because a blocked DNS request consumes + * only a goroutine, while a blocked C call consumes an operating system thread. + * When cgo is available, the cgo-based resolver is used instead under a variety of + * conditions: on systems that do not let programs make direct DNS requests (OS X), + * when the LOCALDOMAIN environment variable is present (even if empty), + * when the RES_OPTIONS or HOSTALIASES environment variable is non-empty, + * when the ASR_CONFIG environment variable is non-empty (OpenBSD only), + * when /etc/resolv.conf or /etc/nsswitch.conf specify the use of features that the + * Go resolver does not implement, and when the name being looked up ends in .local + * or is an mDNS name. + * + * The resolver decision can be overridden by setting the netdns value of the + * GODEBUG environment variable (see package runtime) to go or cgo, as in: + * + * ``` + * export GODEBUG=netdns=go # force pure Go resolver + * export GODEBUG=netdns=cgo # force native resolver (cgo, win32) + * ``` + * + * The decision can also be forced while building the Go source tree + * by setting the netgo or netcgo build tag. + * + * A numeric netdns setting, as in GODEBUG=netdns=1, causes the resolver + * to print debugging information about its decisions. + * To force a particular resolver while also printing debugging information, + * join the two settings by a plus sign, as in GODEBUG=netdns=go+1. + * + * On macOS, if Go code that uses the net package is built with + * -buildmode=c-archive, linking the resulting archive into a C program + * requires passing -lresolv when linking the C code. + * + * On Plan 9, the resolver always accesses /net/cs and /net/dns. + * + * On Windows, in Go 1.18.x and earlier, the resolver always used C + * library functions, such as GetAddrInfo and DnsQuery. + */ +namespace net { + /** + * Addr represents a network end point address. + * + * The two methods Network and 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") + } +} + +/** + * 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 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 - } - /** - * 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{} +/** + * Copyright 2023 The Go Authors. All rights reserved. + * Use of this source code is governed by a BSD-style + * license that can be found in the LICENSE file. + */ +namespace multipart { /** - * CompletionOptions are the options to control shell completion + * A Part represents a single part in a multipart body. */ - interface CompletionOptions { + interface Part { /** - * DisableDefaultCmd prevents Cobra from creating a default 'completion' command + * The headers of the body, if any, with the keys canonicalized + * in the same fashion that the Go http.Request headers are. + * For example, "foo-bar" changes case to "Foo-Bar" */ - disableDefaultCmd: boolean + header: textproto.MIMEHeader + } + interface Part { /** - * DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag - * for shells that support completion descriptions + * FormName returns the name parameter if p has a Content-Disposition + * of type "form-data". Otherwise it returns the empty string. */ - disableNoDescFlag: boolean + formName(): string + } + interface Part { /** - * DisableDescriptions turns off all completion descriptions for shells - * that support them + * FileName returns the filename parameter of the Part's Content-Disposition + * header. If not empty, the filename is passed through filepath.Base (which is + * platform dependent) before being returned. */ - disableDescriptions: boolean + fileName(): string + } + interface Part { /** - * HiddenDefaultCmd makes the default 'completion' command hidden + * Read reads the body of a part, after its headers and before the + * next part (if any) begins. */ - hiddenDefaultCmd: boolean + read(d: string|Array): number + } + interface Part { + close(): void } } -namespace migrate { - interface Migration { - file: string - up: (db: dbx.Builder) => void - down: (db: dbx.Builder) => void - } +namespace store { } /** @@ -18489,120 +18672,6 @@ namespace slog { import loginternal = internal } -/** - * 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 _subjqlIr = Reader&Writer - interface ReadWriter extends _subjqlIr { - } -} - -/** - * Package net provides a portable interface for network I/O, including - * TCP/IP, UDP, domain name resolution, and Unix domain sockets. - * - * Although the package provides access to low-level networking - * primitives, most clients will need only the basic interface provided - * by the Dial, Listen, and Accept functions and the associated - * Conn and Listener interfaces. The crypto/tls package uses - * the same interfaces and similar Dial and Listen functions. - * - * The Dial function connects to a server: - * - * ``` - * conn, err := net.Dial("tcp", "golang.org:80") - * if err != nil { - * // handle error - * } - * fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n") - * status, err := bufio.NewReader(conn).ReadString('\n') - * // ... - * ``` - * - * The Listen function creates servers: - * - * ``` - * ln, err := net.Listen("tcp", ":8080") - * if err != nil { - * // handle error - * } - * for { - * conn, err := ln.Accept() - * if err != nil { - * // handle error - * } - * go handleConnection(conn) - * } - * ``` - * - * # Name Resolution - * - * The method for resolving domain names, whether indirectly with functions like Dial - * or directly with functions like LookupHost and LookupAddr, varies by operating system. - * - * On Unix systems, the resolver has two options for resolving names. - * It can use a pure Go resolver that sends DNS requests directly to the servers - * listed in /etc/resolv.conf, or it can use a cgo-based resolver that calls C - * library routines such as getaddrinfo and getnameinfo. - * - * By default the pure Go resolver is used, because a blocked DNS request consumes - * only a goroutine, while a blocked C call consumes an operating system thread. - * When cgo is available, the cgo-based resolver is used instead under a variety of - * conditions: on systems that do not let programs make direct DNS requests (OS X), - * when the LOCALDOMAIN environment variable is present (even if empty), - * when the RES_OPTIONS or HOSTALIASES environment variable is non-empty, - * when the ASR_CONFIG environment variable is non-empty (OpenBSD only), - * when /etc/resolv.conf or /etc/nsswitch.conf specify the use of features that the - * Go resolver does not implement, and when the name being looked up ends in .local - * or is an mDNS name. - * - * The resolver decision can be overridden by setting the netdns value of the - * GODEBUG environment variable (see package runtime) to go or cgo, as in: - * - * ``` - * export GODEBUG=netdns=go # force pure Go resolver - * export GODEBUG=netdns=cgo # force native resolver (cgo, win32) - * ``` - * - * The decision can also be forced while building the Go source tree - * by setting the netgo or netcgo build tag. - * - * A numeric netdns setting, as in GODEBUG=netdns=1, causes the resolver - * to print debugging information about its decisions. - * To force a particular resolver while also printing debugging information, - * join the two settings by a plus sign, as in GODEBUG=netdns=go+1. - * - * On macOS, if Go code that uses the net package is built with - * -buildmode=c-archive, linking the resulting archive into a C program - * requires passing -lresolv when linking the C code. - * - * On Plan 9, the resolver always accesses /net/cs and /net/dns. - * - * On Windows, in Go 1.18.x and earlier, the resolver always used C - * library functions, such as GetAddrInfo and DnsQuery. - */ -namespace net { - /** - * Addr represents a network end point address. - * - * The two methods Network and 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") - } -} - /** * Package url parses URLs and implements query escaping. */ @@ -18636,69 +18705,71 @@ namespace url { } } +namespace hook { + /** + * Handler defines a hook handler function. + */ + interface Handler {(e: T): void } + /** + * wrapped local Hook embedded struct to limit the public API surface. + */ + type _subyqpey = Hook + interface mainHook extends _subyqpey { + } +} + /** - * 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. - */ -/** - * Copyright 2023 The Go Authors. All rights reserved. - * Use of this source code is governed by a BSD-style - * license that can be found in the LICENSE file. + * Package types implements some commonly used db serializable types + * like datetime, json, etc. */ -namespace multipart { +namespace types { /** - * A Part represents a single part in a multipart body. + * JsonRaw defines a json value type that is safe for db read/write. */ - interface Part { + interface JsonRaw extends Array{} + interface JsonRaw { /** - * The headers of the body, if any, with the keys canonicalized - * in the same fashion that the Go http.Request headers are. - * For example, "foo-bar" changes case to "Foo-Bar" + * String returns the current JsonRaw instance as a json encoded string. */ - header: textproto.MIMEHeader + string(): string } - interface Part { + interface JsonRaw { /** - * FormName returns the name parameter if p has a Content-Disposition - * of type "form-data". Otherwise it returns the empty string. + * MarshalJSON implements the [json.Marshaler] interface. */ - formName(): string + marshalJSON(): string|Array } - interface Part { + interface JsonRaw { /** - * FileName returns the filename parameter of the Part's Content-Disposition - * header. If not empty, the filename is passed through filepath.Base (which is - * platform dependent) before being returned. + * UnmarshalJSON implements the [json.Unmarshaler] interface. */ - fileName(): string + unmarshalJSON(b: string|Array): void } - interface Part { + interface JsonRaw { /** - * Read reads the body of a part, after its headers and before the - * next part (if any) begins. + * Value implements the [driver.Valuer] interface. */ - read(d: string|Array): number + value(): any } - interface Part { - close(): void + interface JsonRaw { + /** + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current JsonRaw instance. + */ + scan(value: any): void + } +} + +namespace search { + /** + * Result defines the returned search result structure. + */ + interface Result { + page: number + perPage: number + totalItems: number + totalPages: number + items: any } } @@ -18837,6 +18908,23 @@ namespace http { import urlpkg = url } +namespace mailer { + /** + * Message defines a generic email message struct. + */ + interface Message { + from: mail.Address + to: Array + bcc: Array + cc: Array + subject: string + html: string + text: string + headers: _TygojaDict + attachments: _TygojaDict + } +} + /** * Package echo implements high performance, minimalist Go web framework. * @@ -18952,81 +19040,6 @@ namespace echo { } } -namespace store { -} - -/** - * Package types implements some commonly used db serializable types - * like datetime, json, etc. - */ -namespace types { - /** - * JsonRaw defines a json value type that is safe for db read/write. - */ - interface JsonRaw extends Array{} - interface JsonRaw { - /** - * String returns the current JsonRaw instance as a json encoded string. - */ - string(): string - } - interface JsonRaw { - /** - * MarshalJSON implements the [json.Marshaler] interface. - */ - marshalJSON(): string|Array - } - interface JsonRaw { - /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. - */ - unmarshalJSON(b: string|Array): void - } - interface JsonRaw { - /** - * Value implements the [driver.Valuer] interface. - */ - value(): any - } - interface JsonRaw { - /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current JsonRaw instance. - */ - scan(value: any): void - } -} - -namespace mailer { - /** - * Message defines a generic email message struct. - */ - interface Message { - from: mail.Address - to: Array - bcc: Array - cc: Array - subject: string - html: string - text: string - headers: _TygojaDict - attachments: _TygojaDict - } -} - -namespace search { - /** - * Result defines the returned search result structure. - */ - interface Result { - page: number - perPage: number - totalItems: number - totalPages: number - items: any - } -} - namespace settings { // @ts-ignore import validation = ozzo_validation @@ -19050,19 +19063,6 @@ namespace settings { } } -namespace hook { - /** - * Handler defines a hook handler function. - */ - interface Handler {(e: T): void } - /** - * wrapped local Hook embedded struct to limit the public API surface. - */ - type _subdCtjH = Hook - interface mainHook extends _subdCtjH { - } -} - namespace subscriptions { /** * Message defines a client's channel data. @@ -19163,6 +19163,9 @@ namespace core { } } +namespace subscriptions { +} + /** * Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer * object, creating another object (Reader or Writer) that also implements @@ -19428,55 +19431,6 @@ namespace bufio { } } -/** - * Package types implements some commonly used db serializable types - * like datetime, json, etc. - */ -namespace types { -} - -/** - * Package mail implements parsing of mail messages. - * - * For the most part, this package follows the syntax as specified by RFC 5322 and - * extended by RFC 6532. - * Notable divergences: - * ``` - * - Obsolete address formats are not parsed, including addresses with - * embedded route information. - * - The full range of spacing (the CFWS syntax element) is not supported, - * such as breaking addresses across lines. - * - No unicode normalization is performed. - * - The special characters ()[]:;@\, are allowed to appear unquoted in names. - * - A leading From line is permitted, as in mbox format (RFC 4155). - * ``` - */ -namespace mail { - /** - * Address represents a single mail address. - * An address such as "Barry Gibbs " is represented - * as Address{Name: "Barry Gibbs", Address: "bg@example.com"}. - */ - interface Address { - name: string // Proper name; may be empty. - address: string // user@domain - } - interface Address { - /** - * String formats the address as a valid RFC 5322 address. - * If the address's name contains non-ASCII characters - * the name will be rendered according to RFC 2047. - */ - string(): string - } -} - -namespace search { -} - -namespace subscriptions { -} - /** * Package slog provides structured logging, * in which log records include a message, @@ -20020,6 +19974,52 @@ namespace slog { } } +/** + * Package types implements some commonly used db serializable types + * like datetime, json, etc. + */ +namespace types { +} + +namespace search { +} + +/** + * Package mail implements parsing of mail messages. + * + * For the most part, this package follows the syntax as specified by RFC 5322 and + * extended by RFC 6532. + * Notable divergences: + * ``` + * - Obsolete address formats are not parsed, including addresses with + * embedded route information. + * - The full range of spacing (the CFWS syntax element) is not supported, + * such as breaking addresses across lines. + * - No unicode normalization is performed. + * - The special characters ()[]:;@\, are allowed to appear unquoted in names. + * - A leading From line is permitted, as in mbox format (RFC 4155). + * ``` + */ +namespace mail { + /** + * Address represents a single mail address. + * An address such as "Barry Gibbs " is represented + * as Address{Name: "Barry Gibbs", Address: "bg@example.com"}. + */ + interface Address { + name: string // Proper name; may be empty. + address: string // user@domain + } + interface Address { + /** + * String formats the address as a valid RFC 5322 address. + * If the address's name contains non-ASCII characters + * the name will be rendered according to RFC 2047. + */ + string(): string + } +} + /** * Package slog provides structured logging, * in which log records include a message,